- UID
- 1029342
- 性别
- 男
|
僵尸进程测试2:父进程循环创建子进程,子进程退出,造成多个僵尸进程,程序如下所示:
[url=][/url]
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <errno.h> 5 6 int main() 7 { 8 pid_t pid; 9 //循环创建子进程10 while(1)11 {12 pid = fork();13 if (pid < 0)14 {15 perror("fork error:");16 exit(1);17 }18 else if (pid == 0)19 {20 printf("I am a child process.\nI am exiting.\n");21 //子进程退出,成为僵尸进程22 exit(0);23 }24 else25 {26 //父进程休眠20s继续创建子进程27 sleep(20);28 continue;29 }30 }31 return 0;32 }[url=][/url]
程序测试结果如下所示:
4、僵尸进程解决办法
(1)通过信号机制
子进程退出时向父进程发送SIGCHILD信号,父进程处理SIGCHILD信号。在信号处理函数中调用wait进行处理僵尸进程。测试程序如下所示:
[url=][/url]
1 #include <stdio.h> 2 #include <unistd.h> 3 #include <errno.h> 4 #include <stdlib.h> 5 #include <signal.h> 6 7 static void sig_child(int signo); 8 9 int main()10 {11 pid_t pid;12 //创建捕捉子进程退出信号13 signal(SIGCHLD,sig_child);14 pid = fork();15 if (pid < 0)16 {17 perror("fork error:");18 exit(1);19 }20 else if (pid == 0)21 {22 printf("I am child process,pid id %d.I am exiting.\n",getpid());23 exit(0);24 }25 printf("I am father process.I will sleep two seconds\n");26 //等待子进程先退出27 sleep(2);28 //输出进程信息29 system("ps -o pid,ppid,state,tty,command");30 printf("father process is exiting.\n");31 return 0;32 }33 34 static void sig_child(int signo)35 {36 pid_t pid;37 int stat;38 //处理僵尸进程39 while ((pid = waitpid(-1, &stat, WNOHANG)) >0)40 printf("child %d terminated.\n", pid);41 } |
|