Linux使用SIGALARM信号的定时器

版权声明:所有的博客都是个人笔记,交流可以留言或者加QQ:2630492017 https://blog.csdn.net/qq_35976351/article/details/86532889

基本的alarm()函数使用方式

alarm函数的定义:

#include <unistd.h>
unsigned int alarm(unsigned int seconds);

该函数精确到秒级别,如果失败返回-1

下面给出一个一秒的定时器,每隔一秒执行一次,自动设置。

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>
#include <bits/signum.h>

void sig_handler (int sig) {
    if (sig == SIGALRM) {
        puts ("+1s...");
        alarm (1);  // 重新设置1秒定时器
    }
}

int main() {

    struct sigaction sa;
    bzero (&sa, sizeof (sa) );
    sa.sa_handler = sig_handler;
    sa.sa_flags |= SA_RESTART;
    assert (sigaction (SIGALRM, &sa, NULL) != -1);

    alarm(1);

    while (1) {
        sleep (1);
    }
    return 0;
}

由上述代码可以看出,时间到时,触发SIGALRM信号,之后处理有关的信号函数。

在实际的应用中,为了防止信号被屏蔽,一般使用管道方式向进程管道写入数据,然后在主循环中处理信号,这种方式参考这篇博客:https://blog.csdn.net/qq_35976351/article/details/85524540

猜你喜欢

转载自blog.csdn.net/qq_35976351/article/details/86532889