有一个定时器每 1 秒发出一次信号 SIGALARM。休眠的信号处理程序 注册了 2 秒。怎么了?具体来说,我有以下代码,其中进程运行多个线程。非常有趣的是,使用这个长信号处理程序,其他线程似乎被阻止执行...谁能解释为什么会这样?
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h> //rand
#include <sys/wait.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
#define NUM_THREADS 2
int init_timer(int real_time, int msec) {
struct itimerval timeslice;
timeslice.it_interval.tv_sec = msec / 1000;
timeslice.it_interval.tv_usec = (msec % 1000) * 1000;
timeslice.it_value.tv_sec = msec / 1000;
timeslice.it_value.tv_usec = (msec % 1000) * 1000;
setitimer(real_time ? ITIMER_REAL : ITIMER_VIRTUAL, ×lice, NULL);
return 0;
}
void install_handler(int signo, void(*handler)(int)) {
sigset_t set;
struct sigaction act;
/* Setup the handler */
act.sa_handler = handler;
act.sa_flags = SA_RESTART;
sigaction(signo, &act, 0);
/* Unblock the signal */
sigemptyset(&set);
sigaddset(&set, signo);
sigprocmask(SIG_UNBLOCK, &set, NULL);
return;
}
void timerTest(int signo)
{
printf("000\n");
sleep(1);
printf("111\n");
}
void * threadTest(void * threadId)
{
while(true)
{
printf("222\n");
}
}
int main(int argc, char *argv[]) {
int real_time = 1;
int tick_msec = 10;
init_timer(real_time, tick_msec);
install_handler(real_time ? SIGALRM : SIGVTALRM, &timerTest);
pthread_t threads[NUM_THREADS];
int rc;
long t;
for (t = 0; t < NUM_THREADS; t++) {
rc = pthread_create(&threads[t], NULL, threadTest, (void *) t);
if (rc) {
exit(-1);
}
}
void * status;
for (t = 0; t < NUM_THREADS; t++) {
rc = pthread_join(threads[t], &status);
if (rc) {
exit(-1);
}
}
pthread_exit(NULL);
}
打印输出:
222
222
222
222
...
222
000
111
000
111
...
第一个111出现后就没有222了吗?为什么会这样?
最佳答案
信号被传送到特定线程,因此信号处理程序在特定线程(信号被传送到的线程)中运行。如果信号被传递给写出 222\n
的线程,则该线程必须停止写出 222\n
并运行信号处理程序。您的示例信号处理程序需要一整秒才能运行,因此在这一整秒内该线程可能不会写出 222\n
。
此外,由于您正在使用 printf
写出所有这些字节,因此在 libc 中进行了一些锁定。由于 printf
不是“异步信号安全”函数,因此实际上未定义如果在信号处理程序中使用它会发生什么。您观察到的行为的一种可能解释是这样的。如果在该线程持有 stdout 锁时将信号传递给该线程,则在处理程序返回之前,没有其他线程能够写入 stdout,并且该线程中运行的“正常”代码可以释放该锁。不过,在这种情况下,信号处理程序仍然可以写入标准输出,因为锁是一个 rlock,它可以在任何特定线程中重复获取。不过,这可能因特定平台、C 库、线程库或月相而异。不过,您的示例很容易转换为使用 write(2),它或多或少地展示了相同的问题行为,具有或多或少相同的修复,并且不依赖于未定义的行为。
如果您在 222\n
线程中SIG_BLOCK
定时器信号,那么信号处理程序将始终在主线程中运行,您将继续获得 222\n
信号处理程序休眠时输出。
Seth 还提出了关于仅在信号处理程序中使用安全函数的重要观点。使用任何其他意味着您的程序的行为是未定义的。
关于c - 带有长信号处理程序的定时器问题 (SIGALARM),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6129927/