当前位置 博文首页 > lyndon:写一个僵尸进程

    lyndon:写一个僵尸进程

    作者:[db:作者] 时间:2021-06-26 15:36

    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:对于进程状态不了解的可以参考我的前一篇文章。