我正在使用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 );
}
即使thoght我正在使用“pthread_sigmask(SIG_BLOCK,&amp; new_set,&amp; old_set)”。它没有阻挡信号。但是,如果我删除“pthread_create(&amp; a,NULL,threadmasked,NULL);”它工作正常并阻止信号。我在这里观察到的另一件事是,如果我将 pthread_sigmask 更改为 sigprocmask ,则行为保持不变。
答案 0 :(得分:2)
线程从它们创建的线程继承信号掩码。
因此,当您的代码在之后调用pthread_sigmask()
时,它会调用pthread_create()
新创建的线程没有修改其信号掩码。
像这样更改代码,确保按预期工作:
...
pthread_sigmask( SIG_BLOCK, &new_set, &old_set);
pthread_t a;
pthread_create(&a, NULL, threadmasked, NULL);
...