Is that possible with C to wait until the popen subprocess is finished?
I have a script launched by a C daemon which will connect to a wifi network when an external signal is triggered.
Here is my code for now :
********************* Wait for external event here *********************** if((fp = popen(CONNECTION_SCRIPT, "r")) == NULL) { SYSLOG_ERR("[Error] Impossible to open pipe to execute %sn", CONNECTION_SCRIPT); exit(EXIT_FAILURE); } while(fgets(scriptBuffer, SCRIPT_BUF_SIZE, fp) != NULL) { SYSLOG("[%s] %s", CONNECTION_SCRIPT, scriptBuffer); } if(pclose(fp)) { SYSLOG_ERR("[Error] Error with %s execution n", CONNECTION_SCRIPT); exit(EXIT_FAILURE); }
However, I’m not waiting for the subprocess to finish so when I’m closing the pipe, the ressource is busy because the script is stil writting in. Is there a way to wait for the end of the connection script before reading in the pipe and closing it?
I know I could do it by forking the process and waiting for the child to terminate but it’s quite a lot of modifications just to synchronize threads
Advertisement
Answer
I’m guessing that you say that you get a “resource busy” error because errno
has the value EBUSY
when you log the error in the third last line of your snippet. That may well be misleading.
In general, you should only check the value of errno
if you have a solid indication that an error occurred. In the case of pclose
, that indication would be that the function returns precisely -1 (and not any non-zero value, as is the case with your current code).
Any value other than -1 returned by pclose
should be interpreted as the subprocess’s termination code; in such a case, errno
will have an unspecified (and therefore misleading) value. You can use the WEXITSTATUS
, WIFSIGNALED
and WTERMSIG
macros as explained in the waitpid
manpage to interpret the return value from pclose
.
As documented in its manpage, pclose
waits for the subprocess to terminate, so it already does what you request. It will return an actual error indication (-1) if its use of waitpid
returns an error (unlikely, but anything is possible).