#include <unistd.h> #include <stdio.h> #include<stdlib.h> #include<signal.h> int main(void) { //signal(SIGCHLD, SIG_IGN); int i=0; printf("i son/pa ppid pid fpid\n"); //ppid指当前进程的父进程pid //pid指当前进程的pid, //fpid指fork返回给当前进程的值 while(1){ sleep(1); //之所以加入这个时间是因为,容易看出程序的变化,不然根本看不出变化,连鼠标都懂不了! pid_t fpid=fork(); if(fpid==0) {printf("%d child %4d %4d %4d\n",i,getppid(),getpid(),fpid); //return 0; //这两个效果一样的! exit(0); } } return 0; } [[email protected] Desktop]# gcc b.c [[email protected] Desktop]# ./a.out i son/pa ppid pid fpid 0 child 16980 16981 0 0 child 16980 16982 0 0 child 16980 16983 0 0 child 16980 16985 0 0 child 16980 16988 0 0 child 16980 16990 0 0 child 16980 16991 0 0 child 16980 16993 0 0 child 16980 16995 0 0 child 16980 16996 0 ^C [[email protected] Desktop]# [[email protected] Desktop]# ps aux | grep -w ‘Z‘ //产生了好多僵尸进程了 root 16981 0.0 0.0 0 0 pts/2 Z+ 20:38 0:00 [a.out] <defunct> root 16982 0.0 0.0 0 0 pts/2 Z+ 20:38 0:00 [a.out] <defunct> root 16983 0.0 0.0 0 0 pts/2 Z+ 20:38 0:00 [a.out] <defunct> root 16985 0.0 0.0 0 0 pts/2 Z+ 20:38 0:00 [a.out] <defunct> root 16987 0.0 0.0 4340 804 pts/3 S+ 20:38 0:00 grep -w Z [[email protected] Desktop]# 当把signal(SIGCHLD, SIG_IGN);这行代码加上时输出结果如下: [[email protected] Desktop]# gcc b.c [[email protected] Desktop]# ./a.out i son/pa ppid pid fpid 0 child 17135 17136 0 0 child 17135 17137 0 0 child 17135 17139 0 0 child 17135 17140 0 0 child 17135 17141 0 0 child 17135 17142 0 0 child 17135 17145 0 0 child 17135 17147 0 0 child 17135 17150 0 0 child 17135 17151 0 0 child 17135 17152 0 ^C [[email protected] Desktop]# //没有僵尸进程产生 [[email protected] Desktop]# ps aux | grep -w ‘Z‘ root 17144 0.0 0.0 4336 796 pts/3 S+ 20:42 0:00 grep -w Z [[email protected] Desktop]# ps aux | grep -w ‘Z‘ root 17149 0.0 0.0 4336 792 pts/3 S+ 20:42 0:00 grep -w Z [[email protected] Desktop]#
时间: 2024-11-03 22:59:39