简体   繁体   English

同一主电源中的两个信号

[英]Two signals in the same main

I want to use two signals in the same main. 我想在同一主电源中使用两个信号。 So I made two handlers etc. That's my code: 所以我做了两个处理程序,等等。这就是我的代码:

volatile sig_atomic_t go_on = 0;
volatile sig_atomic_t execute = 0;

void sig_syn(int sig_no)
{
    go_on = 1;
}

void exe_handler(int sig_no)
{
    execute = 1;
}

struct sigaction action;
sigset_t mask;

struct sigaction e_action;
sigset_t e_mask;

sigfillset (&mask);
action.sa_handler = sig_syn;
action.sa_mask = mask;
action.sa_flags = 0;
sigaction (SIGRTMIN, &action, NULL);

sigfillset (&e_mask);
e_action.sa_handler = exe_handler;
e_action.sa_mask = e_mask;
e_action.sa_flags = 0;
sigaction (SIGRTMIN, &e_action, NULL);

while(go_on == 0){}         
go_on = 0;
.
.
.

while(execute == 0){}
execute = 0;
.
.
.

Is it correct that i use all these two times? 我两次都使用都正确吗? The reason I ask is because my program doesn't run but no errors appear... Any help? 我问的原因是因为我的程序无法运行,但是没有出现错误...有帮助吗? Thanks in advance! 提前致谢!

First of all, if your program doesn't run try out putting some debugging, gdb would be better, but printfs can do the job. 首先,如果您的程序没有运行,请尝试进行一些调试,gdb会更好,但是printfs可以胜任。

A Unix program can receive a lot of signals, checkout "man signal" to the usage and "man 7 signal" to all signals. 一个Unix程序可以接收很多信号,对用法检查“ man signal”,对所有信号检查“ man 7 signal”。

I'written and tested the following code. 我编写并测试了以下代码。

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
void
termination_handler (int signum)
{
    printf("Signal %d\n",signum);
    exit(0);
}

int signal1 = 0;

void
usr_signal1(int signum)
{
    printf("Signal 1 received\n");
    signal1 = 1;
}


int signal2 = 0;

void
usr_signal2(int signum)
{
    printf("Signal 2 received\n");
    signal2 = 1;
}


int
main (void)
{
    printf("My pid is : %d\n",getpid());
    if (signal (SIGTERM, termination_handler) == SIG_IGN)
        signal (SIGTERM, SIG_IGN);
    if (signal (SIGUSR1, usr_signal1) == SIG_IGN)
        signal(SIGUSR1, SIG_IGN);
    if (signal (SIGUSR2, usr_signal2) == SIG_IGN)
        signal(SIGUSR2, SIG_IGN);
    printf("Main has started\n");

    while(0 == signal1) { sleep(1); };

    printf("Main moved to stade 1 \n");

    while(0 == signal2) { sleep(1); };

    printf("Main moved to stade 2 \n");
    printf("Main is done ! \n");

    return 0;
}

After compiling and running, it will print it's pid and keep waiting signals SIGUSR1 and SIGUSR2. 编译并运行后,它将打印它的pid并保持等待信号SIGUSR1和SIGUSR2。

$ ./main 
My pid is : 6365
Main has started
Signal 1 received
Main moved to stade 1 
Signal 2 received
Main moved to stade 2 
Main is done ! 

Sending the kills with 发送杀死

kill -10 6365
kill -12 6365

works. 作品。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM