我正在尝试使用POSIX信号处理POSIX定时器。 当我尝试执行你可以找到的代码时,我得到:
错误的timer_settime:参数无效
在GAPIL上,基于高级Linux编程和Unix网络编程,我读到这可能发生在new_value.value中你指定了一个负时间值或高于999999999的纳秒数。 但我认为我用的参数还可以......
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/fcntl.h>
#include <sys/wait.h>
#include <stdbool.h>
void termination_handler(int signum)
{
printf("Timer scaduto\n");
}
int main()
{
timer_t timer1;
struct sigevent sigeventStruct;
sigeventStruct.sigev_notify = SIGEV_SIGNAL;
sigeventStruct.sigev_signo = 10;
if(timer_create(_POSIX_MONOTONIC_CLOCK, &sigeventStruct, &timer1) == -1)
{
printf( "Errore timer_create: %s\n", strerror( errno ) );
}
printf("timer_create eseguito\n");
struct itimerspec tempoIniziale;
tempoIniziale.it_value.tv_nsec = 0;
struct itimerspec tempoFinale;
tempoFinale.it_value.tv_nsec = 10000000;
if(timer_settime(timer1, 0, &tempoIniziale, &tempoFinale) == -1)
{
printf( "Errore timer_settime: %s\n", strerror( errno ) );
}
struct sigaction newSigAzione, oldSigAzione;
newSigAzione.sa_handler = termination_handler;
//oldSigAzione.sa_handler = termination_handler;
sigemptyset (&newSigAzione.sa_mask);
newSigAzione.sa_flags = 0;
sigaction (SIGEV_SIGNAL, NULL, &oldSigAzione);
if(oldSigAzione.sa_handler != SIG_IGN)
{
//sigaction (SIGEV_SIGNAL, newSigAzione, NULL);
}
/*sigaction (SIGINT, NULL, &oldSigAzione);
if (oldSigAzione.sa_handler != SIG_IGN)
sigaction (SIGINT, &newSigAzione, NULL);
sigaction (SIGHUP, NULL, &oldSigAzione);
if (oldSigAzione.sa_handler != SIG_IGN)
sigaction (SIGHUP, &newSigAzione, NULL);
sigaction (SIGTERM, NULL, &oldSigAzione);
if (oldSigAzione.sa_handler != SIG_IGN)
sigaction (SIGTERM, &newSigAzione, NULL);*/
/*sigaction (SIGTERM, &newSigAzione, NULL);*/
return 0;
}
答案 0 :(得分:3)
_POSIX_MONOTONIC_CLOCK是一个功能测试宏,可以告诉您系统上是否有单调时钟。
您可以在Linux上传递给timer_create()的可用时钟ID是:
CLOCK_REALTIME System-wide realtime clock. Setting this clock requires appropriate privileges. CLOCK_MONOTONIC Clock that cannot be set and represents monotonic time since some unspecified starting point. CLOCK_PROCESS_CPUTIME_ID High-resolution per-process timer from the CPU. CLOCK_THREAD_CPUTIME_ID Thread-specific CPU-time clock.
您还必须初始化struct sigevent
和struct itimerspec
中的所有成员。
例如。你没有在structitimer_spec中设置.tv_sec
,只设置.tv_nsec
,这会在这些成员中产生垃圾值。
...
memset(&sigeventStruct, 0, sizeof sigeventStruct);
...
and
struct itimerspec tempoFinale;
memset(&tempoFinale, 0, sizeof tempoFinale);
tempoFinale.it_value.tv_nsec = 10000000;