题目
代码实现一个僵尸进程
代码
实现僵尸进程,只需让子进程先于父进程结束,并且父进程不调用 wait/ waitpid 函数回收子进程的退出状态。在父进程没有退出的转态下使用 ps 命令即可查看存在的僵尸进程信息。
下图运行结果,红框里为僵尸子进程
/************************************************************************* > File Name: main.c > Author: 杨永利 > Mail: 1795018360@qq.com > Created Time: 2021年07月14日 星期三 21时46分58秒 ************************************************************************/ #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char const *argv[]) { pid_t pid; // 创建进程 pid = fork(); // 创建失败 if (pid < 0) { perror("fork error:"); exit(1); } // 子进程 else if (pid == 0) { printf("I am child process.I am exiting.\n"); exit(0); } printf("I am father process.I will sleep two seconds\n"); //等待子进程先退出 sleep(2); //输出进程信息 system("ps -o pid,ppid,state,tty,command"); printf("father process is exiting.\n"); return 0; }
知识回顾
详细内容请移驾另一篇博客: