Fork / exec / waitpid problem

I am trying to determine if the execution failed by checking the result of waitpid (). However, even when I run a command that I know fails and writes the problem to stderr, the check below is never logged. What could be wrong with this code?

Thanks for any help.

pid_t pid; // the child process that the execution runs inside of. int ret; // exit status of child process. child = fork(); if (pid == -1) { // issue with forking } else if (pid == 0) { execvp(thingToRun, ThingToRunArray); // thingToRun is the program name, ThingToRunArray is // programName + input params to it + NULL. exit(-1); } else // We're in the parent process. { if (waitpid(pid, &ret, 0) == -1) { // Log an error. } if (!WIFEXITED(ret)) // If there was an error with the child process. { } } 
+4
source share
1 answer

waitpid returns only -1 if an error occurs with waitpid . That is, if you give it the wrong pid or breaks, etc. If the child has a failure status, waitpid will succeed (return pid) and set ret to reflect the status of the child.

To determine the status of a child, use WIFEXITED(ret) and WEXITSTATUS(ret) . For instance:

 if( waitpid( pid, &ret, 0 ) == -1 ) { perror( "waitpid" ); } else if( WIFEXITED( ret ) && WEXITSTATUS( ret ) != 0 ) { ; /* The child failed! */ } 
+4
source

All Articles