我需要从客户端进程向服务器进程发送周期心跳/消息,以通知客户端进程运行正常,并且不会陷入无限循环或不可恢复的状态。对于定期通知,我使用了“ timer_create” /“ timer_settime” API来每5秒触发一次定期计时器。这样,我注意到的是,计时器是由内核代表进程触发的;因此,即使该客户端进程陷入无限循环,我仍然看到计时器被触发。 Linux中是否有任何机制可以定期等待通知,但是通知是从进程而不是内核触发的。
以下是主线程陷入无限“ while”循环的代码;计时器仍在触发。
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#define CLOCKID CLOCK_REALTIME
#define SIG SIGUSR2
static void handler(int sig, siginfo_t *si, void *uc)
{
printf("Caught signal %d and\n", sig);
}
int main()
{
timer_t timerid;
struct sigevent sev;
struct itimerspec its;
struct sigaction sa;
/* Establish handler for timer signal */
printf("Establishing handler for signal %d\n", SIG);
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = handler;
sigemptyset(&sa.sa_mask);
if (sigaction(SIG, &sa, NULL) == -1)
perror("sigaction");
/* Create the timer */
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIG;
sev.sigev_value.sival_ptr = &timerid;
if (timer_create(CLOCKID, &sev, &timerid) == -1)
perror("timer_create");
printf("timer ID is 0x%lx\n", (long) timerid);
/* Start the timer */
its.it_value.tv_sec = 2 ;
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = 2;
its.it_interval.tv_nsec = 0;
if (timer_settime(timerid, 0, &its, NULL) == -1)
perror("timer_settime");
while (1) {
}
exit(EXIT_SUCCESS);
}
先谢谢了, 西瓦南德(Shivanand)