• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: How to read stdout from a sub process in bash in real time

Resolved: How to read stdout from a sub process in bash in real time

0
By Isaac Tonny on 17/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have a simple C++ program that counts from 0 to 10 with an increment every 1 second. When the value is incremented, it is written to stdout. This program intentionally uses printf rather than std::cout. I want to call this program from a bash script, and perform some function (eg echo) on the value when it is written to stdout. However, my script waits for the program to terminate, and then process all the values at the same time.
C++ prog:
Is there another way to read the output of my program, that will access it in real time, rather than wait for for the process to terminate. Note: the C++ program is a demo sample – the actual program I am using also uses printf, but I am not able to make changes to this code, hence the solution needs to be in the bash script.
Many thanks, Stuart

Answer:

As you correctly observed, $(command) waits for the entire output of command, splits that output, and only after that, the for loop starts.
To read output as soon as is available, use while read:
or, if you need to access variables from inside the loop afterwards, and your system supports <()

while IFS= read -r line; do
echo “do stuff with $line”
done < <(./script-test) # do more stuff, that depends on variables set inside the loop [/code]

If you have better answer, please add a comment about this, thank you!

bash linux stdout
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: In a Pinescript v5 Strategy why is my bool not working?

02/04/2023

Resolved: net::ERR_HTTP2_PROTOCOL_ERROR by http get request angular 15.2

02/04/2023

Resolved: How do I stop the command from happening if the requirements for it to work aren’t sert Discord.js

02/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.