在pthread_cond_wait之前传递信号时,进程自动退出

时间:2017-09-27 09:22:57

标签: c linux systems-programming

#include "apue.h"
#include <pthread.h>

int     quitflag;
sigset_t    mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait  = PTHREAD_COND_INITIALIZER;

void *
thr_fn(void *arg)
{
    int err, signo;

    for ( ; ; ) {
    err = sigwait(&mask, &signo);
    if (err != 0)
        err_exit(err, "sigwait failed");
    switch (signo) {
        case SIGINT:
        printf("\ninterrupt\n");
        break;

        case SIGQUIT:
        pthread_mutex_lock(&lock);
        quitflag = 1;
        pthread_mutex_unlock(&lock);
        pthread_cond_signal(&wait);
        return 0;

        default:
        printf("unexpected signal %d\n", signo);
        exit(1);
    }
    }
}

int
main(void)
{
    int     err;
    sigset_t    oldmask;
    pthread_t   tid;

    sigemptyset(&mask);
    sigaddset(&mask, SIGINT);
    sigaddset(&mask, SIGQUIT);
    if ((err =  pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
        err_exit(err, "SIG_BLOCK error");

    err = pthread_create(&tid, NULL, thr_fn, 0);
    if (err != 0)
        err_exit(err, "can not create thread");

    **sleep(20);**  /* added code here */
    pthread_mutex_lock(&lock);
    while (quitflag == 0)
        pthread_cond_wait(&wait, &lock); /* first unlock, then suspend */
    pthread_mutex_unlock(&lock);

    quitflag = 0;

    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
        err_sys("SIG_SETMASK error");

    exit(0);
}    

这是检查&#34; sigwait&#34;,我插入&#34;睡眠(20)&#34;的apue代码。在调用pthread_cond_wait之前,用./a.out启动程序,然后线程thr_fn start,在&#34; 20秒&#34;之前,我发送&#34;信号退出&#34;当ctrl + \,然后线程退出,然后经过几次,主进程自动退出, 我不知道为什么?有人可以解释一下吗?我的平台是centos,谢谢

0 个答案:

没有答案