+ -
当前位置:首页 → 问答吧 → 一个监控程序的问题

一个监控程序的问题

时间: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)没有执行,为什么?

作者: oxangen   发布时间: 2010-09-16

回复 oxangen


    因为wait 总是返回失败,所以 while 循环不止,产生了无数的子进程。

    修改 int *status; 为 int status; pids = wait(status); 为 pids = wait(&status);

作者: zzyong08   发布时间: 2010-09-16

为什么要用while(1)??

作者: pengjianbokobe   发布时间: 2010-09-16

如果你这样调用wait函数,就不会上来问这个问题。
  1. if((pids=wait(status)) == -1)
  2. {
  3.         perror("wait() error");
  4.         return -1;
  5. }
复制代码

作者: krein8964   发布时间: 2010-09-16