考虑我设置的这个例子来说明这一点。
#define _POSIX_C_SOURCE 199506L
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <errno.h>
#include <signal.h>
#include <pthread.h>
void hand(int sig);
void *thrfn(void *arg);
int main(void)
{
struct sigaction act;
struct itimerval timer;
sigset_t mask;
pthread_t thr;
act.sa_handler = hand;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGALRM, &act, NULL);
/* error checking omitted */
timer.it_interval.tv_sec = 1;
timer.it_interval.tv_usec = 500000;
timer.it_value = timer.it_interval;
/* ultimately I want to build a loop; hence repeating */
setitimer(ITIMER_REAL, &timer, NULL);
sigemptyset(&mask);
pthread_sigmask(SIG_SETMASK, &mask, NULL);
/* why doesn't this prevent SIGALRM from interrupting main? */
pthread_create(&thr, NULL, thrfn, NULL);
puts("Main thread done.");
getchar();
return 0;
}
void hand(int sig)
{
(void)sig;
write(STDOUT_FILENO, "Handler handled.\n", 17);
}
void *thrfn(void *arg)
{
sigset_t mask;
(void)arg;
sigemptyset(&mask);
sigaddset(&mask, SIGALRM);
pthread_sigmask(SIG_SETMASK, &mask, NULL);
/* why doesn't this make pause() return in this thread? */
pause();
puts("Off thread's pause returned.");
pthread_exit(NULL);
}
这是使用 gcc 编译的输出:
Main thread done.
Handler handled.
消息之间有大约一秒半的时间。
为什么我的第二个线程pause
永远不会返回?