侧边栏壁纸
博主头像
noerror

虚灵不寐,众理具而万事出。

  • 累计撰写 239 篇文章
  • 累计创建 9 个标签
  • 累计收到 2 条评论
标签搜索

目 录CONTENT

文章目录

pthread_sigmask函数用法详解

noerror
2022-10-04 / 0 评论 / 0 点赞 / 300 阅读 / 582 字 / 正在检测是否收录...

pthread_sigmask函数用法详解

pthread_sigmask函数简介

  • 头文件包含
#include <signal.h>
  • 函数定义
int pthread_sigmask(int  how , const sigset_t * set \
  • 编译链接选项
-pthread

pthread_sigmask函数常见使用错误

  • 链接错误
    undefined reference to `pthread_sigmask'
    解决办法:添加链接选项
-pthread
  • 编译错误
    warning: implicit declaration of function ‘pthread_sigmask’ [-Wimplicit-function-declaration]
    解决办法:包含头文件
#include <signal.h>

pthread_sigmask函数详细描述

pthread_sigmask ()函数与sigprocmask (2)类似,不同之处在于它在多线程程序中的使用是由POSIX.1显式指定的。本页注明了其他差异。
有关此函数的参数和操作的说明,请参见sigprocmask (2)

pthread_sigmask函数返回值

成功时,pthread_sigmask ()返回0;出错时,它返回一个错误号。

pthread_sigmask函数错误码

参见sigprocmask (2)

pthread_sigmask函数其他说明

新线程继承其创建者的信号掩码的副本。
glibc pthread_sigmask ()函数静默地忽略阻止NPTL线程实现在内部使用的两个实时信号的尝试。详见nptl (7)。

pthread_sigmask函数使用举例

下面的程序阻止主线程中的一些信号,然后创建一个专用线程通过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

Program source&

#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) \e
       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\en", 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, &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 */
}
0

评论区