我编写了一个简单的计时器函数并用g ++编译,奇怪的是它要求timer_create的原型是:int timer_create(clockid_t, sigevent*, void**)
,这不是真的。
我的代码如下所示。
请帮帮我。
提前致谢。
enter code here
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
static void sig_handlerTimer1(int,siginfo_t*,void*);
time_t timerid;
int main()
{
int i;
static struct sigaction sa;
static struct sigevent sevp; // argument to timer_create
static struct itimerspec its; // argument to timer_gettime
memset (&sevp, 0, sizeof (struct sigevent));
sevp.sigev_value.sival_ptr = &timerid;
sevp.sigev_notify = SIGEV_SIGNAL;
sevp.sigev_notify_attributes = NULL;
sevp.sigev_signo = SIGUSR1;
/* Setting timer interval */
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
/* Setting timer expiration */
its.it_value.tv_sec = 2; // First expiry after 1 sec
its.it_value.tv_nsec = 0;
/* Setting the signal handlers before invoking timer*/
sa.sa_sigaction = sig_handlerTimer1;
sa.sa_flags = 0;
sigaction(SIGUSR1, &sa, NULL);
if (timer_create(CLOCK_REALTIME, &sevp, &timerid) == -1)
{
fprintf(stderr, "LeakTracer (timer_trackStartTime): timer_create failed to create timer. " \
"Leak measurement will be for entire duration of the execution period:%s \n", strerror(errno));
return 0;
}
if (timer_settime(timerid, 0, &its, NULL) == -1)
{
fprintf(stderr, "LeakTracer (timer_trackStartTime): timer_settime failed to set the timer. " \
"Leak measurement will be for entire duration of execution period:%s \n", strerror(errno));
return 0;
}
for(i=0; i<10; i++)
{
printf("%d\n",i);
sleep(1);
}
}
void sig_handlerTimer1(int signum,siginfo_t* si, void* au)
{
int flag = 1;
printf("Caught signal: %d\n",signum);
if (timer_delete(&timerid) < 0)
{
fprintf(stderr, "timer deletion failed. " \
"This may result in some memory leaks (sig_handlerTimer1):%s \n", strerror(errno));
}
}
错误:
enter code here
# g++ signalTimer.cc -lrt
signalTimer.cc: In function ‘int main()’:
signalTimer.cc:40: error: cannot convert ‘time_t*’ to ‘void**’ for argument ‘3’ to ‘int timer_create(clockid_t, sigevent*, void**)’
signalTimer.cc:48: error: invalid conversion from ‘time_t’ to ‘void*’
signalTimer.cc:48: error: initializing argument 1 of ‘int timer_settime(void*, int, const itimerspec*, itimerspec*)’
答案 0 :(得分:2)
您需要timer_t
,而不是time_t
。
(您收到晦涩信息的原因是因为timer_t
实际上是void *
,一旦您跟踪了所有typedef
s。)