intmain() { pid_t childpid; int retval; int status;
/* 创建一个新进程 */ childpid = fork();
if (childpid >= 0) { // fork() 成功 if (childpid == 0) { // 子进程 printf("CHILD: I am the child process!\n"); printf("CHILD: Here's my PID: %d\n", getpid()); printf("CHILD: My parent's PID is: %d\n", getppid()); printf("CHILD: The value of fork return is: %d\n", childpid); printf("CHILD: Sleep for 1 second...\n"); sleep(1); printf("CHILD: Enter an exit value (0~255): "); scanf("%d", &retval); printf("CHILD: Goodbye!\n"); exit(retval); } else { // 父进程 printf("PARENT: I am the parent process!\n"); printf("PARENT: Here's my PID: %d\n", getpid()); printf("PARENT: The value of my child's PID is: %d\n", childpid); printf("PARENT: I will now wait for my child to exit.\n"); wait(&status); printf("PARENT: Child's exit code is: %d\n", WEXITSTATUS(status)); printf("PARENT: Goodbye!\n"); exit(0); } } else { // fork() 失败 perror("fork error!"); exit(1); } }
if (childpid >= 0) { // fork() 成功 if (childpid == 0) { // 子进程 printf("CHILD: I am the child process! Executing 'ls' command.\n"); execlp("ls", "ls", NULL); perror("execlp error!"); // 如果execlp失败,将输出错误信息 exit(1); } else { // 父进程 printf("PARENT: I am the parent process!\n"); printf("PARENT: Here's my PID: %d\n", getpid()); printf("PARENT: The value of my child's PID is: %d\n", childpid); printf("PARENT: I will now wait for my child to exit.\n"); wait(&status); printf("PARENT: Child terminated.\n"); printf("PARENT: Goodbye!\n"); exit(0); } } else { // fork() 失败 perror("fork error!"); exit(1); } }