c++ - pthread_sigmask :unusual behavior

标签 c++ c linux pthreads signals

我正在使用 Linux 并尝试与信号处理相关的代码。我正在尝试以下代码,但我无法理解此代码的行为。

/**Globally declared variable**/

    time_t start, finish;
    struct sigaction sact;
    sigset_t new_set, old_set,test;
    double diff;

/**Function to Catch Signal**/
void catcher( int sig )
{
    cout<< "inside catcher() function\n"<<endl;
}


void Initialize_Signalhandler()
{

    sigemptyset( &sact.sa_mask );
    sact.sa_flags = 0;
    sact.sa_handler = catcher;
    sigaction( SIGALRM, &sact, NULL );

    sigemptyset( &new_set );
    sigaddset( &new_set, SIGALRM );

}


/**Function called by thread**/
void *threadmasked(void *parm)
{

/**To produce delay of 10sec**/
        do {
         time( &finish );
         diff = difftime( finish, start );
    } while (diff < 10);

    cout<<"Thread Exit"<<endl;

}


int main( int argc, char *argv[] ) {

    Initialize_Signalhandler();

    pthread_t a;
    pthread_create(&a, NULL, threadmasked, NULL);

    pthread_sigmask( SIG_BLOCK, &new_set, &old_set);

    time( &start );
    cout<<"SIGALRM signals blocked at %s\n"<< ctime(&start) <<endl;


    alarm(2); //to raise SIGALM signal


/**To produce delay of 10sec**/
        do {
         time( &finish );
         diff = difftime( finish, start );
    } while (diff < 10);


return( 0 );
}

甚至认为我正在使用“pthread_sigmask(SIG_BLOCK, &new_set, &old_set)”。它没有阻挡信号。但是如果我删除“pthread_create(&a, NULL, threadmasked, NULL);”它工作正常并阻止了信号。我在这里观察到的另一件事是,如果我将 pthread_sigmask 更改为 sigprocmask,行为保持不变。

最佳答案

线程从创建它们的线程继承信号掩码。

因此,当您的代码调用 pthread_sigmask() after 它调用 pthread_create() 时,新创建的线程不会修改其信号掩码.

像这样更改你的代码,让事情按你预期的那样工作:

...

pthread_sigmask( SIG_BLOCK, &new_set, &old_set);

pthread_t a;
pthread_create(&a, NULL, threadmasked, NULL);

...

关于c++ - pthread_sigmask :unusual behavior,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14495192/

相关文章:

c++ - 在 C++ 中调用 free() 在调试中触发 ntdll!DbgBreakPoint() 但在发布时崩溃

c++ - GCC 和 MS 编译器的模板实例化细节

c++ - 异或 char* 数组

C++ EOF 命名空间

linux - 如何检查字符串是否包含子字符串并且 Bash 中不包含子字符串

linux - 组合两个否定的文件检查条件(-f 和 -s)似乎返回不正确的结果

c++ - C++中的开源随机数生成算法?

c - 以下 C 代码有什么问题?

c - 如何修复在句子数组中提取偶数索引值并将其与奇数索引值组合的代码?

java - 我的java版本是jdk 1.7.但是maven使用jdk 1.6