#include #include /* for perror, EXIT_SUCCESS, EXIT_FAILURE, system */ #include /* for fork, getpid, getppid */ #include /* for WIFEXITED and WEXITSTATUS */ int main(int argc, char **argv) { char buffer[1000]; int status; int s; pid_t p; const pid_t pid = fork(); if (pid < 0) { perror(argv[0]); return 1; } if (pid == 0) { /* Arrive here if I am the child. */ return EXIT_SUCCESS; /* Turn into a zombie immediately. */ } /* Arrive here if I am the parent. */ sleep(1); /* Give the child time to turn into a zombie. */ printf("My PID is %d and my child's PID is %d.\n", getpid(), pid); /* minus lowercase L for "long" */ sprintf(buffer, "ps -l -p %d -p %d", getpid(), pid); system(buffer); p = wait(&status); /* Harvest the zombie. */ if (p != pid) { fprintf(stderr, "%s: my child is %d, not %d.\n", argv[0], pid, p); return 2; } if (!WIFEXITED(status)) { fprintf(stderr, "%s: parent didn't receive exit status from child.\n", argv[0]); return 3; } s = WEXITSTATUS(status); if (s != EXIT_SUCCESS) { fprintf(stderr, "%s: parent received exit status %d instead of %d from child.\n", argv[0], s, EXIT_SUCCESS); return 4; } return EXIT_SUCCESS; }