c语言sigaction,使用的sigaction(),C(Using sigaction(), c)

让我们试着去了解什么是你的代码的修改版本发生:

#include

#include

void termination_handler(int signum)

{

printf("Hello from handler\n");

sleep(1);

}

int main (void)

{

//Structs that will describe the old action and the new action

//associated to the SIGINT signal (Ctrl+c from keyboard).

struct sigaction new_action, old_action;

//Set the handler in the new_action struct

new_action.sa_handler = termination_handler;

//Set to empty the sa_mask. It means that no signal is blocked

// while the handler run.

sigemptyset(&new_action.sa_mask);

//Block the SEGTERM signal.

// It means that while the handler run, the SIGTERM signal is ignored

sigaddset(&new_action.sa_mask, SIGTERM);

//Remove any flag from sa_flag. See documentation for flags allowed

new_action.sa_flags = 0;

//Read the old signal associated to SIGINT (keyboard, see signal(7))

sigaction(SIGINT, NULL, &old_action);

//If the old handler wasn't SIG_IGN (it's a handler that just

// "ignore" the signal)

if (old_action.sa_handler != SIG_IGN)

{

//Replace the signal handler of SIGINT with the one described by new_action

sigaction(SIGINT,&new_action,NULL);

}

while(1)

{

printf("In the loop\n");

sleep(100);

}

return 0;

}

所以,如果你编译并运行它,然后按Ctrl + C,然后你就会有处理消息执行,然后你回来立即出主要的睡眠。 你可以这样做尽可能多的时间,因为你想要的,仍然显示处理程序消息和内环回消息。

所以,你给一个函数,sigaction的不挂钩与处理信号所需的一切。

那么,如何SIGTERM? 如果增加睡眠时间termination_handler,你可以按下Ctrl + C后输入类似“pkill的--signal SIGTERM ./a.out”。 然后,会发生什么? 没有! 而termination_handler运行SIGTERM信号被阻断。 但是,一旦你回到主,现在SIGTERM将杀死应用程序。

(请记住,当你正在测试此代码,您还可以通过发送SIGKILL信号杀死应用程序。)

如果您想了解更多,并与信号更多的乐趣,你有信号手动和sigaction的手册 ,告诉了很多。 请注意,你也有sigaction的结构的详细描述。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值