gpt4 book ai didi

c - 同一主干中的两个信号

转载 作者:行者123 更新时间:2023-11-30 15:32:32 25 4
gpt4 key购买 nike

我想在同一个 main 中使用两个信号。所以我做了两个处理程序等。这是我的代码:

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;
.
.
.

我使用这两次是否正确?我问的原因是因为我的程序无法运行但没有出现错误......有什么帮助吗?提前致谢!

最佳答案

首先,如果你的程序无法运行,请尝试进行一些调试,gdb 会更好,但 printfs 可以完成这项工作。

一个 Unix 程序可以接收很多信号,查看“man signal”的用法和“man 7 signal”查看所有信号。

我编写并测试了以下代码。

#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;
}

编译运行后,会打印自己的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 !

发送击杀数据

kill -10 6365
kill -12 6365

有效。

关于c - 同一主干中的两个信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24206803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com