linux pthread阻塞等待信号到来
时间: 2023-07-09 10:24:00 浏览: 74
在Linux下,我们可以使用pthread_sigmask函数来阻塞或解除阻塞特定的信号。在阻塞特定信号后,我们可以使用sigwait函数来等待信号到来。sigwait函数会一直等待,直到指定的信号被捕获。
下面是一个简单的例子,展示了如何使用pthread_sigmask和sigwait函数来等待一个信号:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <signal.h>
void *sig_thread(void *arg) {
sigset_t *set = (sigset_t *)arg;
int sig;
while (1) {
sigwait(set, &sig);
printf("Received signal %d\n", sig);
}
return NULL;
}
int main() {
pthread_t tid;
sigset_t set;
// 阻塞SIGINT信号
sigemptyset(&set);
sigaddset(&set, SIGINT);
pthread_sigmask(SIG_BLOCK, &set, NULL);
// 创建线程等待信号
pthread_create(&tid, NULL, sig_thread, &set);
// 主线程等待信号
int sig;
sigwait(&set, &sig); // 这里会一直等待直到SIGINT信号到来
// 取消子线程
pthread_cancel(tid);
pthread_join(tid, NULL);
return 0;
}
```
在上面的例子中,主线程和子线程都会阻塞SIGINT信号。主线程使用sigwait函数等待信号,子线程使用sigwait函数等待信号并打印信号号码。当SIGINT信号到来时,主线程会解除阻塞并打印信号号码,子线程也会打印信号号码。最后,主线程会取消子线程并等待子线程结束。
需要注意的是,如果多个线程阻塞了同一个信号,那么只有其中一个线程会捕获到信号。