Hello,
see this fragment of your "simple program to exemplify":
pid_t pid = fork();
switch (pid) {
case -1: /* error fork unsucessful */
status = -1;
break;
case 0:
sleep(2);
status = -1;
exit(WEXITSTATUS(status)); // *** here is the bad code ***
What is the "child process"? Teach yourself: man (2) fork: " fork() causes creation of a new process. The new process (child process) is an exact copy of the calling process (parent process)".
This implies: "exit(WEXITSTATUS(status));" performs exactly the same as an exit() in parent process would do: this includes disconnect from the frontend.
My instinct: your code is incomplete. Typically you'll perform an call to exec() in the child, something like this:
execlp("sh", "sh", "-c", cmd, (char *) NULL);
next fragment or your example (that's the "parent" code after fork):
default:
while (waitpid(pid, &status_ptr, 0) != pid)
sleep(1);
if (WIFEXITED(status_ptr)) {
status = (short)WEXITSTATUS(status_ptr);
} else {
status = 1;
}
break;
Why forking (starting a new process, parent and child are running parallel) when waiting afterwards in the parent. Your code is both invalid and makes no sense.