[英]Signal handler in Linux using sigaction (C++)
I am trying to send SIGUSR1/SIGUSR2 signals between multiple processes using custom handler, but my handler does not work. 我正在尝试使用自定义处理程序在多个进程之间发送SIGUSR1 / SIGUSR2信号,但是我的处理程序不起作用。 It is not printing any debug messages or anything. 它不打印任何调试消息或任何东西。
Here I am creating 8 processes and trying to set a custom handler using set_sigaction function: 在这里,我正在创建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;
Here is set_sigaction function: 这是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);
}
And here is the handler: 这是处理程序:
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());
}
My send_signal function gives me this message, which means it send SIGUSR1 signal to the second process: 我的send_signal函数给我此消息,这意味着它将SIGUSR1信号发送给第二个进程:
1 3156 Send USR1 Thu Jun 22 18:04:54 2017 1 3156发送USR1 2017年6月22日星期四18:04:54
I am thinking the problem is how I create multiple processes or how i set my handler. 我在想问题是如何创建多个进程或如何设置处理程序。
what does send_signal do ? send_signal做什么? Try sending the signal using the kill function as : 尝试使用kill函数发送信号:
kill(pidArray[1], SIGUSR1) kill(pidArray [1],SIGUSR1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.