#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid;
int status;
// 创建子进程
pid = fork();
if (pid < 0) {
// 创建子进程失败
perror("fork failed");
exit(1);
} else if (pid == 0) {
// 子进程代码
printf("Child process: PID = %d\n", getpid());
sleep(2); // 模拟子进程执行一段时间
exit(0);
} else {
// 父进程代码
printf("Parent process: Child PID = %d\n", pid);
// 父进程等待子进程结束
wait(&status);
if (WIFEXITED(status)) {
printf("Child exited with status %d\n", WEXITSTATUS(status));
} else {
printf("Child terminated abnormally\n");
}
}
return 0;
}
fork():创建一个子进程。返回值为子进程的PID(在父进程中),或者0(在子进程中),如果失败则返回负值。wait(&status):父进程调用 wait 函数,阻塞并等待子进程结束。status 变量用于存储子进程退出的状态信息。WIFEXITED(status) 和 WEXITSTATUS(status):宏用于检查子进程是否正常退出,并获取其退出状态码。sleep(2):模拟子进程执行一段时间后退出。这个示例展示了如何使用 wait 来等待子进程结束,并获取其退出状态。
上一篇:linux 查看进程id
下一篇:linux 重命名文件名
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站