Prayer

在一般中寻求卓越
posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

求教一个简单的多进程和信号的问题

Posted on 2009-01-04 20:04 Prayer 阅读(403) 评论(0)  编辑 收藏 引用 所属分类: LINUX/UNIX/AIX
/*编制一段程序,使用系统调用fork()创建两个子进程,
再用系统调用signal()让父进程捕捉键盘上来的中断信号(即按Del键),
当捕捉到中断信号后,父进程用系统调用kill()向两个子进程发出信号,
子进程捕捉到信号后,分别输出下列信息后终止:
    child process 1 is killed by parent!
    child process 2 is killed by parent!
    父进程等待两个子进程终止后,输出以下信息后终止:
    parent process is killed !
*/
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void waiting();
void stop();
int wait_mark;
main()
{
    int p1=-1, p2=-1;
    //signal(SIGINT, stop); // position A
    while ((p1 = fork()) == -1);
        if (p1>0)
       {   /*parent*/
           while ((p2 = fork()) == -1);
           if (p2>0)
          {   /*parent*/
              wait_mark=1;
              signal(SIGINT, stop);// position B
              waiting();
              kill(p1,16);             //*send signal 16 to end the process p1
              kill(p2,17);            //*send signal 17 to end the process p2
              wait(0);                 //*waiting for the ending of p1
              wait(0);                //*waiting for the ending of p2
              printf("parent process is killed!\n");
              exit(0);                //*quit from the parent process
          }
           else                                    //*p2 work
          {    /*child p2*/
               wait_mark=1;
               signal(17, stop);
               waiting();
               lockf(1,1,0);
               printf("child process 2 is killed by parent!\n");
               lockf(1,0,0);
            exit(0);                          //* p2  quit
          }
       }
       else                                       //*p1 work
       {      /*child p1*/
              wait_mark=1;
              signal(16, stop);         
              waiting();
              lockf(1,1,0);                          
              printf("child process 1 is killed by parent!\n");
              lockf(1,0,0);                          
              exit(0);                           //* p1 quit
     }
}

void waiting( )
{
      while (wait_mark != 0);
}

void stop()
{
      wait_mark=0;
}


又研究了一下,在两个子进程开始就加入signal(SIGINT,SIG_IGN),就满足要求了。看来原来的Ctrl-c信号对所有进程都起作用了,所以得把它给禁了,才能合要求。   

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理