|
| 1 | +#include <sys/types.h> |
| 2 | +#include <sys/wait.h> |
| 3 | +#include <errno.h> |
| 4 | +#include <stdio.h> |
| 5 | +#include <stdlib.h> |
| 6 | +#include <string.h> |
| 7 | +#include <unistd.h> |
| 8 | + |
| 9 | +// Sample program that will take another program on the command line |
| 10 | +// and call execvp on it. |
| 11 | +// So, argv[0] = this process's name |
| 12 | +// argv[1] = the program we want to exec |
| 13 | +// argv[2-end] = the arguments to the program we want to exec |
| 14 | +// |
| 15 | +int main(int argc, char *argv[]) { |
| 16 | + (void)argc; |
| 17 | + |
| 18 | + pid_t parent_pid = getpid(); |
| 19 | + |
| 20 | + printf("Hello from parent pid %d\n", parent_pid); |
| 21 | + |
| 22 | + pid_t child = fork(); |
| 23 | + |
| 24 | + if (child == 0) { |
| 25 | + printf("Hi! I'm the child pid %d\n", getpid()); |
| 26 | + |
| 27 | + if (execvp(argv[1], argv+1) == -1) { |
| 28 | + printf("The exec failed: %s\n", strerror(errno)); |
| 29 | + exit(1); |
| 30 | + } |
| 31 | + |
| 32 | + printf("The exec succeeded! Here is pid %d\n", getpid()); |
| 33 | + } else if (child > 0) { |
| 34 | + printf("Hi! I'm the parent pid %d\n", getpid()); |
| 35 | + } else { |
| 36 | + printf("Fork failed!\n"); |
| 37 | + } |
| 38 | + |
| 39 | + // Wait for the child to exit |
| 40 | + int exit_status; |
| 41 | + pid_t exit_pid; |
| 42 | + while (1) { |
| 43 | + exit_pid = waitpid(child, &exit_status, WUNTRACED | WCONTINUED); |
| 44 | + if (WIFEXITED(exit_status)) |
| 45 | + break; |
| 46 | + else if (WIFSIGNALED(exit_status)) { |
| 47 | + printf("Child received a signal\n"); |
| 48 | + break; |
| 49 | + } else if (WIFSTOPPED(exit_status)) { |
| 50 | + printf("Child process is stopped; keep waiting\n"); |
| 51 | + } |
| 52 | + // If we got here, we still have a child - sleep a bit and |
| 53 | + // wait. |
| 54 | + sleep(1); |
| 55 | + } |
| 56 | + printf("Child %d exited with status: %d\n", |
| 57 | + exit_pid, WEXITSTATUS(exit_status)); |
| 58 | +} |
0 commit comments