#include #include #include #include #include #include void main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "usage: %s [args...]\n", argv[0]); exit(EXIT_FAILURE); } printf("parent process PID=%d is starting\n", getpid()); pid_t pid = vfork(); // use vfork to create child process if (pid < 0) { // vfork fail perror("vfork fail"); exit(EXIT_FAILURE); } else if (pid == 0) { // child process printf("child process PID=%d will start: %s\n", getpid(), argv[1]); // execute program which is pass in via argv execvp(argv[1], &argv[1]); perror("execvp fail"); exit(EXIT_FAILURE); } else { // parent process printf("parent process PID=%d wait for child process PID=%d\n", getpid(), pid); int status; pid_t wait_pid = waitpid(pid, &status, 0); // wait for child process terminating if (wait_pid < 0) { perror("waitpid fail"); } else if (WIFEXITED(status)) { printf("child process exit,exit code: %d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("child process is terminated by signal,signal is: %d\n", WTERMSIG(status)); } printf("parent process exit\n"); } exit(0); }