// 创建子进程 pid = fork(); if (pid < 0) { // fork失败 perror("fork"); exit(EXIT_FAILURE); } elseif (pid == 0) { // 子进程 printf("Child process with PID: %d\n", getpid()); // 子进程立即退出 exit(EXIT_SUCCESS); } else { // 父进程 printf("Parent process with PID: %d, Child PID: %d\n", getpid(), pid);
// 父进程等待子进程结束 int status; pid_t wpid = wait(&status); if (wpid == -1) { perror("wait"); exit(EXIT_FAILURE); }
// 检查子进程的退出状态 if (WIFEXITED(status)) { printf("Child process exited with status %d\n", WEXITSTATUS(status)); } else { printf("Child process terminated by signal %d\n", WTERMSIG(status)); } }
// 父进程继续执行其他任务,例如睡眠一段时间 printf("Parent process continue do something\n"); sleep(10);