我正在尝试使用自定义处理程序在多个进程之间发送SIGUSR1 / SIGUSR2信号,但我的处理程序不起作用。它不打印任何调试消息或任何东西。
这里我创建了8个进程并尝试使用set_sigaction函数设置自定义处理程序:
int main(){
pidArray = (int *)mmap(NULL, MMAP_SIZE, PROT_READ | PROT_WRITE,MAP_ANONYMOUS | MAP_SHARED, -1, 0);//Self pid
pidArray2 = (int *)mmap(NULL, MMAP_SIZE, PROT_READ | PROT_WRITE,MAP_ANONYMOUS | MAP_SHARED, -1, 0);//Child pid
counter = (int *)mmap(NULL, MMAP_SIZE2, PROT_READ | PROT_WRITE,MAP_ANONYMOUS | MAP_SHARED, -1, 0);
counter[0]=0;
counter[1]=0;
pid_t pid, pid2;
int counter = 1;
pidArray[0]=getpid();
pid = fork(); //1
if(pid == 0){
pid = fork(); //2
if(pid != 0){
pidArray[1]=getpid();
pidArray2[1]=pid;
}
if(pid == 0){
pid2 = getpid();
pidArray[2]=pid2;
pid=fork(); //4
if(pid == 0){
pidArray[4] = getpid();
pid=fork(); //5
if(pid==0){
pidArray[5] = getpid();
pidArray2[5] = 0;
}
else
pidArray2[4] = pid;
}
if(pid2 == getpid()){
pid2 = fork(); //3
if(pid2!=0){
pid = setpgid(pid,pid2);
}
else{
pidArray[3]=getpid();
pid=fork(); //6
if(pid==0){
pidArray[6]=getpid();
pid=fork(); //7
if(pid==0){
pidArray[7]=getpid();
pid=fork(); //8
if(pid!=0)
pidArray2[7]=pid;
else{
pidArray[8]=getpid();
pidArray2[8]=pidArray[1];
}
}
else
pidArray2[6]=pid;
}
else
pidArray2[3]=pid;
}
}
}
}
set_sigaction(SIGUSR1);
sleep(5);
if(getpid()==pidArray[1])
kill(pidArray[0],SIGTERM);
if(getpid()==pidArray[1]){
send_signal(pidArray[1]);
}
sleep(100);
return 0;
这是set_sigaction函数:
static int set_sigaction(int signo)
{
struct sigaction sa;
memset(&sa, 0, sizeof(struct sigaction));
sa.sa_sigaction = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_SIGINFO;
return sigaction(signo, &sa, NULL);
}
这是处理程序:
static void handler(int signo, siginfo_t* si, void* ucontext){
int k;
int i;
pid_t pid = getpid();
for(i=1;i<9;i++){
if(pidArray[i]==pid)
k=i;
}
time_t rawtime;
time ( &rawtime );
cout << k << " " << pid << " Got USR1 " << ctime (&rawtime) << "\n";
send_signal(getpid());
}
我的send_signal函数给了我这条消息,这意味着它将SIGUSR1信号发送到第二个进程:
1 3156发送USR1 Thu Jun 22 18:04:54
我在想我的问题是如何创建多个进程或如何设置我的处理程序。
答案 0 :(得分:0)
send_signal做什么? 尝试使用kill函数发送信号:
kill(pidArray [1],SIGUSR1)