This is my first take on fork, exec and waitpid. I didn't quite understand why I had to use a while loop with waitpid. I discovered that waitpid sets errno to EINTR which is translated to this:#define EINTR        4  /* Interrupted system call */And I saw a suggestion in comp.unix.programmer archives to use a while loop for waitpid.My implementation works on OSX 10.10.3 but it doesn't quite satisfy me. Can you provide suggestions?main.c#include <stdio.h>#include <unistd.h>#include <sys/wait.h>#include <errno.h>#include common.hint main(int argc, const char * argv[]) {    int exit_status_raw;    pid_t pid = fork();    if (pid < 0) {        printerr(Forking failed);        return -1;    }    if (pid == 0) {        printf(CHILD says Hello\n);        execlp(./child, ./child, NULL);        printerr(exec failed);        return -1;    }    if (pid > 0) {        printf(PARENT says Hello\n);        while ((pid = waitpid(pid, &exit_status_raw, 0)) == -1) {            switch (errno) {                case EINTR:                    printerr(waitpid failed with EINTR. Retrying...);                    continue;                default:                    printerr(waitpid failed);                    break;            }        }        printf(Child exited with %d\n, WEXITSTATUS(exit_status_raw));    }    return 0;}child.c#include <stdio.h>#include common.hint main(int argc, const char * argv[]) {    printf(This is a time consuming computation\n);    // ...    printerr(Sorry. I failed to compute);    return 127;}common.h#ifndef my_common_h#define my_common_hvoid printerr(const char *message) {    fprintf(stderr, %s\n, message);}#endif
A simple fork with an ugly waitpid
c;child process;unix
I didn't quite understand why I had to use a while loop with waitpidTo loop or not to loop should be a well-thought design decision.The main reason for waiting in the loop is to monitor child's life for events other than exit (e.g. when the WUNTRACED option is set). Since you do not set this option, the only remaining reason is to deal with interrupts. It is really a minor one, and often you want to be interrupted (consider for example a child entering a non-alertable sleep).The way you are dealing with errors other than EINTR is not correct. break only breaks the switch, and the code keeps executing the loop. Since the errors like EINVAL are non-recoverable, the program would get stuck in the loop forever (hitting the same error over and over again).