Usage sample of unix signal to handle function call with a timeout value.

本文介绍了一个使用信号和长跳转实现的定时中断机制,该机制能够在指定时间内中断一个阻塞的函数调用并使其返回。通过设置报警信号并在信号触发时使用长跳转返回到调用者,可以有效地控制函数执行的最长时间。

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

Suppose a function "fun" can be blocked, and the its caller hope it will be returned back if "fun" is running too much long; in other words, "fun()" can be overwritten with "fun(int timeout)"

 

 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

#include <assert.h>

#include <signal.h>
#include <setjmp.h>


sigjmp_buf run_with_timeout_env;

void
abort_run_with_timeout (int sig)
{
        assert (sig == SIGALRM);
        siglongjmp (run_with_timeout_env, -1);
}


void fun(int secs)
{
        printf("[%d] sleep %d seconds, start.../n",time(NULL), secs);
        sleep(secs);
        printf("[%d] sleep %d seconds, end/n",time(NULL), secs);
}

int main(int argc, char* argv[])
{

        signal (SIGALRM, abort_run_with_timeout);

        if (sigsetjmp(run_with_timeout_env,1) != 0)
    {
                printf("[%d] here longjmp returned./n",time(NULL));    // "fun()" will be return in 2 seconds, so it must come here.
                signal (SIGALRM, SIG_DFL);
                return 1;
        }

        printf("[%d] start a 2 seconds alarm./n",time(NULL));
        alarm (2);   // a alarm signal will be invoked within 2 seconds.

        printf("[%d] start calling user funcation./n",time(NULL));
        fun(5);   // this require the function "fun" will return in 5 seconds, as we know there is a 2-seconds alarm signl

        printf("[%d] clear alarm./n",time(NULL));
        alarm (0);


        printf("[%d] restore signal function back./n",time(NULL));
        signal (SIGALRM, SIG_DFL);
}

 

 

The program is compiled under Solaris 5.10, Sun Studio 11

 

#:cc alarm.c
#:./a.out
[1263108032] start a 2 seconds alarm.
[1263108032] start calling user funcation.
[1263108032] sleep 5 seconds, start...
[1263108034] here longjmp returned.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值