#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
}
if (pid == 0) {
// 子进程
printf("Child process, PID: %d\n", getpid());
sleep(5); // 模拟子进程做一些工作
printf("Child process is exiting\n");
exit(0);
} else {
// 父进程
printf("Parent process, PID: %d, Child PID: %d\n", getpid(), pid);
sleep(10); // 父进程不等待子进程,继续运行
printf("Parent process is exiting without waiting for the child\n");
}
return 0;
}
fork() 创建一个子进程。fork() 返回两次,一次在父进程中返回子进程的 PID,一次在子进程中返回 0。wait() 或 waitpid() 来等待子进程结束。wait() 或 waitpid() 来回收子进程的状态信息。僵尸进程会一直存在于系统中,直到父进程回收它。这个例子展示了如何产生僵尸进程。为了避免僵尸进程,通常父进程应该调用 wait() 或 waitpid() 来等待子进程结束并回收其资源。
上一篇:linux删除某个文件
下一篇:linux poweroff
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站