- 论坛徽章:
- 0
|
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <signal.h>
void handle(sigval_t v)
{
time_t t;
char p[32];
time(&t);
strftime(p, sizeof(p), "%T", localtime(&t));
printf("%s thread %d, val = %d, signal captured.\n", p, pthread_self(), v.sival_int);
return;
}
int create(int seconds, int id)
{
timer_t tid;
struct sigevent se;
struct itimerspec ts, ots;
memset(&se, 0, sizeof(struct sigevent));
se.sigev_notify = SIGEV_THREAD;
se.sigev_notify_function = handle;
se.sigev_value.sival_int = id;
if(timer_create(CLOCK_REALTIME, &se, &tid) < 0)
{
perror ("timer_creat" ;
return -1;
}
puts("timer_create successfully." ;
ts.it_value.tv_sec = 3;
ts.it_value.tv_nsec = 0;
ts.it_interval.tv_sec = seconds;
ts.it_interval.tv_nsec = 0;
if(timer_settime(tid, TIMER_ABSTIME, &ts, &ots) < 0)
{
perror ("timer_settime" ;
return -1;
}
return 0;
}
int
main (void)
{
create(0, 1);
create(0, 2);
for(;
{
sleep(10);
}
}
为什么一开始没有等待3秒时间,就直接显示
timer_create successfully.
timer_create successfully.
15:38:50 thread -1208050768, val = 1, signal captured.
15:38:50 thread -1218540624, val = 2, signal captured.
如果设置timer_settime(tid, 0, &ts, &ots)就等待3秒后再显示
15:38:50 thread -1208050768, val = 1, signal captured.
15:38:50 thread -1218540624, val = 2, signal captured. |
|