我想使用下面的C++代码等待预定义的时间(在本例中总是2秒),但是仍然会被信号打断(这就是为什么我不使用睡眠):
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <iostream>
using namespace std;
int measure() {
itimerval idle;
sigset_t sigset;
int sig;
idle.it_value.tv_sec = 2;
idle.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &idle, NULL); // TODO: check return value
sigemptyset(&sigset);
sigaddset(&sigset, SIGALRM); // TODO return values
sigaddset(&sigset, SIGUSR1);
sigprocmask(SIG_BLOCK, &sigset, NULL); // TODO return value?
sigwait(&sigset, &sig); // TODO check return value
while(sig != SIGUSR1) {
cout << "Hohoho" << endl;
idle.it_value.tv_sec = 2;
idle.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &idle, NULL); // TODO: check return value
sigwait(&sigset, &sig); // TODO check return value
}
cout << "Done with measurements." << endl;
return 0;
}
int main(int argc, char **argv) {
//if(fork() != 0) exit(0);
//if(fork() == 0) exit(0);
return measure();
}我希望这段代码每2秒打印一次"Hohoho“,直到它接收到SIGUSR1。然后打印“用测量完成”。和出口。第二部分按预期工作。但是,我没有看到"Hohoho",所以在我看来,SIGALRM从某种程度上没有收到。奇怪的是,如果我以前做过叉子,程序就会像预期的那样工作。更具体地说,如果我在末尾取消注释这两个叉命令中的任何一个,它就能工作。因此,它不依赖于它是父进程还是子进程,但是在某种程度上,叉子事件很重要。有人能向我解释一下发生了什么事,以及如何修复我的代码吗?
非常感谢,卢茨
发布于 2014-05-19 03:03:21
(1)你的setitimer失败了,因为你没有正确设置它。Struct itimerval包含两个类型为timeval的结构。您只设置一个,从而在声明idle时拾取本地存储中的垃圾。
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 */
};如果您希望每2秒有一个重复计时器,那么将第二个定时器设置为使用相同的值重复。
idle.it_value.tv_sec = 2;
idle.it_value.tv_usec = 0;
idle.it_interval.tv_sec = 2;
idle.it_interval.tv_usec = 0;https://stackoverflow.com/questions/23728706
复制相似问题