2025年4月16日 星期三 乙巳(蛇)年 正月十七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

写一个僵尸进程

时间:11-22来源:作者:点击数:29

写一个僵尸进程

wait.c

  • #include <stdio.h>
  • #include <unistd.h>
  • #include <sys/wait.h>
  • int main(int argc, char **argv)
  • {
  • pid_t pid;
  • pid = fork();
  • if (pid == 0) { // child
  • printf("child pid = %d\n", getpid());
  • printf("in child...\r\n");
  • sleep(2);
  • } else if (pid > 0) { // father
  • sleep(10); /* 子进程 2s 钟后提前结束,等待父进程回收其资源,在这期间,子进程处于僵尸状态 */
  • wait(NULL);
  • }
  • return 0;
  • }
  • $ gcc wait.c -o wait.out
  • $ ./wait.out
  • child pid = 52322
  • in child ...
  • $ ps aux
  • USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
  • root 1 0.0 0.1 169028 12960 ? Ss 07:10 0:03 /sbin/init splash
  • root 2 0.0 0.0 0 0 ? S 07:10 0:00 [kthreadd]
  • ...
  • liyongj+ 52321 0.0 0.0 2364 588 pts/3 S+ 21:39 0:00 ./wait.out
  • liyongj+ 52322 0.0 0.0 2496 76 pts/3 S+ 21:39 0:00 ./wait.out
  • liyongj+ 52323 0.0 0.0 14584 3316 pts/4 R+ 21:39 0:00 ps aux

在 wait.out 程序执行后立马使用 ps aux 查看进程信息,可以看到,wait.out 克隆出一个子进程,父子进程均处于 S(interruptible sleep, 可中断睡眠状态))状态。

2 秒钟之后再次运行 ps aux 查看进程状态

  • $ ps aux
  • USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
  • root 1 0.0 0.1 169028 12960 ? Ss 07:10 0:03 /sbin/init splash
  • root 2 0.0 0.0 0 0 ? S 07:10 0:00 [kthreadd]
  • ...
  • liyongj+ 52321 0.0 0.0 2364 588 pts/3 S+ 21:39 0:00 ./wait.out
  • liyongj+ 52322 0.0 0.0 0 0 pts/3 Z+ 21:39 0:00 [wait.out] <defunct>
  • liyongj+ 52324 0.0 0.0 14584 3312 pts/4 R+ 21:39 0:00 ps aux

可以看到子进程52322 已经变成 Z(僵尸状态)。

ps:对于进程状态不了解的可以参考这篇文章

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐