1

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
        HERE CODE DOES SOMETHING
        exit(EXIT_SUCCESS);
    default:
        //Parent process 
        pid=wait(&status);

        if(pid==1){
            perror("Wait failed");
        }else{
        exit(EXIT_SUCCESS);
        }
}
  • 1
    Reading a function's documentation mostly helps: http://man7.org/linux/man-pages/man2/waitpid.2.html – alk Nov 20 '16 at 12:10
  • 1
    Other than the fact that `wait` returns -1 and not 1 in case of error, which was covered by existing answers, consider using `waitpid` to ensure that you are waiting for the process you just forked, rather than the first child process that happens to exit (possibly forked off earlier, or by another thread). Also, it's a good idea to call `_exit` instead of `exit`, to prevent inadvertent flushing of parent's stdip buffers inherited by the child process. – user4815162342 Nov 20 '16 at 13:00
  • 1
    @user4815162342 thank you. –  Nov 20 '16 at 13:14

1 Answers1

4

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);
}
chrk
  • 4,037
  • 2
  • 39
  • 47
  • Better use this http://man7.org/linux/man-pages/man2/waitpid.2.html for reference. It's more accurate, more up-tp-date and less spamed. – alk Nov 20 '16 at 12:11