我的目标是使主进程及其“分叉”子进程相互通信。通信是通过信号传递来完成的。
当第一个孩子在等待 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);
}
}