setitime和相关函数

博客介绍了Linux系统调用setitimer的使用,它允许设置周期性和一次性定时器,且在定时器触发时,能避免像alarm那样需要手动重新设置。在给定的示例中,setitimer用于每秒读取文件并输出内容,直到读取不足20字节。同时提到了在执行system命令期间,SIGCHLD信号会被阻塞,SIGINT和SIGQUIT会被忽略。此外,还列举了nanosleep、usleep和select等其他时间控制函数。

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

1.setitime

误差很小

NAME
getitimer, setitimer - get or set value of an interval timer

SYNOPSIS
#include <sys/time.h>

int getitimer(int which, struct itimerval *curr_value);
int setitimer(int which, const struct itimerval *new_value,
              struct itimerval *old_value);
           struct itimerval {
               struct timeval it_interval; /* next value 周期*/
               struct timeval it_value;    /* current value 初相位*/
           };

			//精度控制
           struct timeval {
               time_t      tv_sec;         /* seconds */
               suseconds_t tv_usec;        /* microseconds */
           };

当it_value 减到0的时候,就把it_interval赋值给它,原子操作,不用想alarm那样自己形成一个alarm链

2.setitimer的demo

void AlarmHandler(int nNum)
{

        //alarm(1);
}


int main(int argc, char **argv)
{
        int fd;
        char Buf[255];
        int RealSize;
        struct itimerval itv;

        if(argc < 2)
        {
                fprintf(stderr, "No enough argc\n");
                exit(1);
        }

        fd = open(argv[1], O_RDONLY );
        if(fd < 0)
        {
                perror("open()");
                exit(1);
        }

        signal(SIGALRM, AlarmHandler);

        //alarm(1);
        //1s一次不需要ms那么精确
        itv.it_interval.tv_sec = 1;
        itv.it_interval.tv_usec = 0;
        itv.it_value.tv_sec = 1;
        itv.it_value.tv_usec = 0;

        setitimer(ITIMER_REAL, &itv, NULL);


        while(1)
        {
                pause();
                RealSize = read(fd, Buf, 20);
                write(1, Buf, RealSize);
                if(RealSize < 20)
                        break;
        }



        close(fd);

        return 0;
}

3.system函数在信号程序中

 During  execution  of  the  command, SIGCHLD will be blocked, 
 and SIGINT and SIGQUIT will be ignored

4函数

1.nanosleep
2.usleep
3.select

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值