sigsuspend()不会对信号做出反应

时间:2012-12-05 22:25:12

标签: c signals posix fork suspend

我的目标是将主要流程及其“叉子”儿童互通。 通过信号传递完成通信。

第一个孩子在等待SIGUSR1信号时等待等待时出现问题。

我不知道为什么会陷入这一点。如果我通过控制台发送信号,那么这个子进程似乎没有引起注意。

有人能帮助我吗?


代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

int N = 5;
int _pipe[2];
pid_t children[5];

void main(){
    pid_t parent_pid;
    pid_t pid;
    int i = 0;

    sigset_t set;
    sigfillset(&set);

    parent_pid = getpid();
    fprintf(stderr,"I am main process, here comes my pid %u\n",getpid());

    if (0>pipe(_pipe)) fprintf(stderr,"Error when creating pipe");

    //Start creating child processes
    while (i < N){
            pid = fork();
            if (pid == 0){
                close(_pipe[1]);
            break;
        }
        else{
            fprintf(stderr,"Created child with pid %u\n",pid);
            children[i] = pid;
            write(_pipe[1],&pid,sizeof(pid_t));
        }
        i = i+1;
    }

    i = 0;

    // What main process does
    if (pid>0){
        close(_pipe[0]);
        close(_pipe[1]);

        sigdelset(&set,SIGUSR2);

        sigdelset(&set,SIGTERM);
        sigdelset(&set,SIGKILL);

        // Main process sends signal to each child
        while(i < N){           
            kill(children[i],SIGUSR1);
            fprintf(stderr,"Sent SIGUSR1 to child %u\n",children[i]);
            // .. Now just wait for SIGUSR2 arrival
            sigsuspend(&set);

            i = i+1;
        }
    }
    // What children do
    else{
        // Wait for main process SIGUSR1 delivery
        sigdelset(&set,SIGUSR1);
        sigsuspend(&set);

        fprintf(stderr, "SIGUSR1 arrived child %u from its father",getpid());

        // Once SIGUSR1 has arrived, pipe is read N times
        while((i < N) && (read(_pipe[0],&pid,sizeof(pid_t))>0)){
            children[i] = pid;
            i = i+1;
        }
        close(_pipe[0]);

        // After reading pipe, a reply is sent to parent process
        kill(parent_pid,SIGUSR2);
    }
}

1 个答案:

答案 0 :(得分:3)

问题很可能与父进程分叉后立即向子进程发送信号这一事实有关,并且子进程没有阻塞信号。因此,当您在子进程中调用sigsuspend()时,信号已经传递给孩子,现在它就在那里等待一个永远不会到来的信号。在开始发送信号之前,您可以通过在主进程中调用sleep()一两秒来快速测试此理论。请记住,由于您的代码现在正在构建,sigsuspend()在没有信号处理程序的情况下无法正常工作...所以我在使用这样的信号时建议如下:

  1. 在父进程中,阻止您计划用于父进程和子进程之间通信的所有信号。您需要为此致电sigprocmask()
  2. 让父分叉子进程
  3. 在子流程中,只需使用包含用于通信的阻塞信号的信号集调用sigwait() ...您不需要sigsuspend()来处理您在此处所做的事情。
  4. 在父进程向子进程发送信号后,它也可以调用sigwait()等待子进程回复。
  5. 以下是您的代码的示例:http://ideone.com/TRcqga

相关问题