linux网络编程二十八:多线程编程之统一信号处理

1. 以下代码取自pthread_sigmask函数的man手册。它实现了在一个线程中统一处理信号。

#include 
#include 
#include 
#include 
#include 
#include 

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

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

    for (;;) {
        //等待信号
        s = sigwait(set, &sig);
        if (s != 0)
            handler_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;

    //在主线程中设置信号掩码
    sigemptyset(&set);
    sigaddset(&set, SIGQUIT);
    sigaddset(&set, SIGUSR1);

    s = pthread_sigmask(SIG_BLOCK, &set, NULL);
    if (s != 0)
        handler_error_en(s, "pthread_sigmask");

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

    pause();

    return 0;
}





你可能感兴趣的:(linux网络编程,网络编程,linux,服务器,多线程,统一信号)