3
我的目標是讓主流程及其「叉」兒童相互通信。通信是通過信號傳遞完成的。sigsuspend()不會對信號做出反應
我的問題出現在第一個孩子在等待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);
}
}
非常感謝@jason,但真正的問題是沒有的,其時收到「sigsuspended」信號定義RAS方法。 在接下來的幾天中,我將恢復我所做的最終代碼。 – xsubira