c语言sigaction,使用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,&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,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信号来终止应用程序.)

如果你想了解更多,并且对信号有更多的乐趣,你可以使用signal manual和sigaction manual来说明更多信息.请注意,您还具有sigaction结构的详细说明.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值