Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to popen/pclose?

Tags:

c

process

popen

I'm writing a program that has to execute other external processes; right now the program launches the processes' commandlines via popen, grabs any output, and then grabs the exit status via pclose.

What is happening, however, is that for fast-running processes (e.g. the launched process errors out quickly) the pclose call cannot get the exit status (pclose returns -1, errno is ECHILD).

Is there a way for me to mimic the popen/pclose type behavior, except in a manner that guarantees capturing the process end "event" and the resultant return code? How do I avoid the inherent race condition with pclose and the termination of the launched process?

like image 638
Joe Avatar asked Oct 14 '22 14:10

Joe


1 Answers

fork/exec/wait

popen is just a wrapper to simplify the fork/exec calls. If you want to acquire the output of the child, you'll need to create a pipe, call fork, dup the child's file descriptors to the pipe, and then exec. The parent can read the output from the pipe and call wait to get the child's exit status.

like image 85
William Pursell Avatar answered Oct 18 '22 21:10

William Pursell