In my C++ program I need to execute a bash script. I need then to return the result obtained running the script in my c++ program. I have two possibilities:
1. use system(script.sh). In script.sh I redirect the output in a file which is processd after I return to the c++ program.
2. use popen
I am interested which of this methods is preffered, considering that the output returned from script.sh could be big(100 M). Thanks.
When using system
the parent process is blocked until the child process terminates. The child process will run with full performance.
popen
will start the child process, but not wait until it ended. So the parent process can continue to do whatever it wants while the child is running, it can for example read the output of the child process. The parent process can decide if it wants to read blocking or non-blocking from the child's output pipe, depending on how much other things the parent process has to do. The child will run in parallel and write its output to the pipe. It might be blocked when writing if the parent process is not reading from the pipe and the pipe's memory limit is reached. So the parent process should keep on reading the output.
The system
approach is a bit simpler. But popen
gives you the possibility to read the process's output while it is still running. And you don't need the extra file (space). So I'd use popen
.