一个监控程序的问题
时间:2010-09-16
来源:互联网
刚看了点Linux进程编程的书,写了个进程监控程序,功能是fork两个子进程,然后父进程监控之,在另一个终端杀掉其中的一个,则会自动重启子进程,但问题是杀掉一个后fork了n个,怎么回事?
//monitor.c
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int main () {
pid_t pid1,pid2,pids;
int *status;
while (1) {
if ( ( pid1=fork() ) < 0 ) return 0;
else if ( pid1 == 0 ){
fprintf (stderr,"Child1 Process Create with ID:%d\n",getpid());
sleep (120);
return 0;
}
if ( ( pid2 = fork () ) <0 ) return 0;
else if ( pid2 == 0 ){
fprintf (stderr,"Child2 Process Create with ID:%d\n",getpid());
sleep (120);
return 0;
}
pids=wait(status);
kill (pid1,SIGTERM);
kill (pid2,SIGTERM);
pids=wait(status);
}
return 0;
然后make monitor
[root@zouvi fork]#make monitor
cc monitor.c -o monitor
[root@zouvi fork]# ./monitor
Child1 Process Create with ID:12283
Child2 Process Create with ID:12284
Child1 Process Create with ID:12299
Child2 Process Create with ID:12300
Child1 Process Create with ID:12301
Child2 Process Create with ID:12302
Child1 Process Create with ID:12303
Child1 Process Create with ID:12305
前两行显示正常,另开一个终端杀掉一个12284后,前个终端就出现了一大堆的创建进程,sleep(120)没有执行,为什么?
//monitor.c
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
int main () {
pid_t pid1,pid2,pids;
int *status;
while (1) {
if ( ( pid1=fork() ) < 0 ) return 0;
else if ( pid1 == 0 ){
fprintf (stderr,"Child1 Process Create with ID:%d\n",getpid());
sleep (120);
return 0;
}
if ( ( pid2 = fork () ) <0 ) return 0;
else if ( pid2 == 0 ){
fprintf (stderr,"Child2 Process Create with ID:%d\n",getpid());
sleep (120);
return 0;
}
pids=wait(status);
kill (pid1,SIGTERM);
kill (pid2,SIGTERM);
pids=wait(status);
}
return 0;
然后make monitor
[root@zouvi fork]#make monitor
cc monitor.c -o monitor
[root@zouvi fork]# ./monitor
Child1 Process Create with ID:12283
Child2 Process Create with ID:12284
Child1 Process Create with ID:12299
Child2 Process Create with ID:12300
Child1 Process Create with ID:12301
Child2 Process Create with ID:12302
Child1 Process Create with ID:12303
Child1 Process Create with ID:12305
前两行显示正常,另开一个终端杀掉一个12284后,前个终端就出现了一大堆的创建进程,sleep(120)没有执行,为什么?
作者: oxangen 发布时间: 2010-09-16
回复 oxangen
因为wait 总是返回失败,所以 while 循环不止,产生了无数的子进程。
修改 int *status; 为 int status; pids = wait(status); 为 pids = wait(&status);
因为wait 总是返回失败,所以 while 循环不止,产生了无数的子进程。
修改 int *status; 为 int status; pids = wait(status); 为 pids = wait(&status);
作者: zzyong08 发布时间: 2010-09-16
为什么要用while(1)??
作者: pengjianbokobe 发布时间: 2010-09-16
如果你这样调用wait函数,就不会上来问这个问题。
复制代码
- if((pids=wait(status)) == -1)
- {
- perror("wait() error");
- return -1;
- }
作者: krein8964 发布时间: 2010-09-16
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28