嵌入式 巧用信号处理

这篇博客介绍了嵌入式系统中信号处理的概念,特别是SIGALRM信号的使用。通过alarm函数设置超时,当时间到达时,内核发送SIGALRM信号给进程。博主展示了如何捕获并处理SIGALRM信号,通过修改标志变量is_run来结束程序中的循环,实现程序在5秒后自动停止的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

信号是软件中断,能够提供一种处理异步事件的方法。
这些信号被定义在signal.h中,列表如下:
#define SIGHUP1
#define SIGINT 2
#define SIGQUIT 3
#define SIGILL 4
#define SIGTRAP 5
#define SIGABRT 6
#define SIGIOT 6
#define SIGBUS 7
#define SIGFPE 8
#define SIGKILL 9
#define SIGUSR1 10
#define SIGSEGV 11
#define SIGUSR2 12
#define SIGPIPE 13
#define SIGALRM 14
#define SIGTERM 15
#define SIGSTKFLT 16
#define SIGCLDSIGCHLD
#define SIGCHLD 17
#define SIGCONT 18
#define SIGSTOP 19
#define SIGTSTP 20
#define SIGTTIN 21
#define SIGTTOU 22
#define SIGURG 23
#define SIGXCPU 24
#define SIGXFSZ 25
#define SIGVTALRM 26
#define SIGPROF 27
#define SIGWINCH 28
#define SIGPOLLSIGIO
#define SIGIO 29
#define SIGPWR 30
#define SIGSYS 31
#define SIGUNUSED 31
其中,有一个信号是闹钟信号SIGALRM,在程序中,我们可以调用alarm函数设置一个超时数值,当超过这个值之后内核将会向该进程发送SIGALRM信号。按POSIX的说明,如果不捕获或者忽略该信号,默认的动作是终止该进程。但事实上我们一般不会使用默认的动作,而是进行自己的处理。
alarm函数的原型是 unsigned int alarm(unsigned int seconds)
它的参数seconds是超时的秒数,它有返回值。如果上一次使用了alarm函数,并且还没有到超时时间又使用了alarm函数,它会将上一次设置的seconds返回以便程序对其进行处理。
#include
#include
#include
#include
static short int is_run = 1;
void sig_alarm(int);
int main(int argc, char *argv[])
{
if(signal(SIGALRM,sig_alarm) == SIG_ERR)
{
perror("signal()");
return0;
}
alarm(5);
printf("processwill stop after 5 seconds!\n");
while(is_run);
printf("processstop!\n");
return 0;
}
void sig_alarm(int seconds)
{
is_run = 0;
}
程序中有一个空循环,条件是is_run。而闹钟信号监听程序将is_run设置为0从而终止了该循环。其结果为:
process will stop after 5 seconds!
process stop!
其中第二句是五秒后才输出的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值