[英]pthread_sigmask:unusual behavior
I am working with Linux and trying code related to signal handling.Following code i am trying but i am not able to understand the behavior of this code. 我正在使用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 );
}
Even thoght i am using " pthread_sigmask( SIG_BLOCK, &new_set, &old_set)". 甚至在我使用“ pthread_sigmask(SIG_BLOCK,&new_set,&old_set)”的情况下。 it is not blocking the signal. 它没有阻止信号。 But if i remove "pthread_create(&a, NULL, threadmasked, NULL);" 但是,如果我删除“ pthread_create(&a,NULL,threadmasked,NULL);” its working fine and blocking the signal. 它的工作正常,并阻止信号。 And another thing i have observed here is if i change pthread_sigmask to sigprocmask behavior remains same. 我在这里观察到的另一件事是,如果我将pthread_sigmask更改为sigprocmask,行为将保持不变。
Threads inherit the signal mask from the thread they are created by. 线程从其创建线程继承信号掩码。
So as your code calls pthread_sigmask()
after it calls pthread_create()
the the freshly created thread does not have its signal mask modified. 因此,当您的代码在调用pthread_sigmask()
之后调用pthread_create()
,新创建的线程不会修改其信号掩码。
Change your code like so, do make things work as you expect: 像这样更改您的代码,使事情按预期工作:
...
pthread_sigmask( SIG_BLOCK, &new_set, &old_set);
pthread_t a;
pthread_create(&a, NULL, threadmasked, NULL);
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.