您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

哪个线程处理信号?

哪个线程处理信号?

如果将信号发送给进程,则该进程中的哪个线程将处理该信号尚未确定。

根据pthread(7)

POSIX.1还要求线程共享一系列其他属性(即,这些属性是进程范围而不是每个线程的属性): …- 信号处置 …

POSIX.1区分了针对整个过程的信号和针对各个线程的信号的概念。根据POSIX.1,过程控制信号(kill(2)例如,使用发送)应由过程中的单个 选择的线程处理。

如果您希望进程中的专用线程处理某些信号,请参见以下示例,其中pthread_sigmask(3)显示了操作方法

下面的程序在主线程中阻塞了一些信号,然后创建了一个专用线程来通过sigwait(3)获取这些信号。以下shell会话演示了其用法

$ ./a.out &
[1] 5423
$ kill -QUIT %1
Signal handling thread got signal 3
$ kill -USR1 %1
Signal handling thread got signal 10
$ kill -TERM %1
[1]+  Terminated              ./a.out

节目来源

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

/* Simple error handling functions */

#define handle_error_en(en, msg) \
        do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)

static void *
sig_thread(void *arg)
{
    sigset_t *set = arg;
    int s, sig;

   for (;;) {
        s = sigwait(set, &sig);
        if (s != 0)
            handle_error_en(s, "sigwait");
        printf("Signal handling thread got signal %d\n", sig);
    }
}

int
main(int argc, char *argv[])
{
    pthread_t thread;
    sigset_t set;
    int s;

   /* Block SIGQUIT and SIGUSR1; other threads created by main()
       will inherit a copy of the signal mask. */

   sigemptyset(&set);
    sigaddset(&set, SIGQUIT);
    sigaddset(&set, SIGUSR1);
    s = pthread_sigmask(SIG_BLOCK, &set, NULL);
    if (s != 0)
        handle_error_en(s, "pthread_sigmask");

   s = pthread_create(&thread, NULL, &sig_thread, (void *) &set);
    if (s != 0)
        handle_error_en(s, "pthread_create");

   /* Main thread carries on to create other threads and/or do
       other work */

   pause();            /* Dummy pause so we can test program */
}
其他 2022/1/1 18:14:13 有564人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶