C:通过alarm发送信号

可以通过alarm定时发送SIGALRM信号:

#include
unsigned int alarm(unsigned int seconds);

alarm()函数用来在seconds秒之后安排发送一个SIGALRM信号,如果seconds为0,将取消所有已设置的闹钟请求。alarm()函数的返回值是以前设置的闹钟时间的余留秒数,如果返回失败返回-1。

#include 
#include 
#include 
#include 
#include 

#include 
 
time_t timeStamp()
{
    time_t time_now = time(NULL); 
    return time_now;
}

static int alarm_done = 0;
 
void handle_alarm(int sig)
{
    printf("handle alarm ts:%ld\n", timeStamp());
    alarm_done = 1;
}
 
int main()
{
    signal(SIGALRM, handle_alarm);
    printf("set alarm ts:%ld\n", timeStamp());
    fflush(stdout);
    alarm(3);
     
    pause();
     
    if(alarm_done == 1)
    {
        printf("recv a alarm ts:%ld\n", timeStamp());
    }
 
    return 0;
}

 运行程序输出:

set alarm ts:1691316070
handle alarm ts:1691316073
recv a alarm ts:1691316073

你可能感兴趣的:(C/C++,c语言)