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