krm krm - 19 days ago 5
Linux Question

Checking if wait() failed

In order to know if wait() has worked, will it be correct to check it like the following? In theory, if wait() does not fail, should return to the parent process the ended child pid, otherwise parent pid will be 1, right?

switch (process = fork())
{
case -1:
// Fork fail
perror("Fork failed");
exit(EXIT_FAILURE);

case 0:
//Child process
exit(EXIT_SUCCESS);
default:
//Parent process
pid=wait(&status);

if(pid==1){
perror("Wait failed");
}else{
exit(EXIT_SUCCESS);
}
}

Answer

Quoting man 2 wait:

RETURN VALUE

wait(): on success, returns the process ID of the terminated child; on error, -1 is returned.

So to check if wait(2) failed, this should be enough:

if (wait(&status) == -1) {
    perror("wait failed");
    exit(1);
}