linux c线程收到信号挂起,LINUX C语言:开启一个专门用来接收信号的子线程。

以下这个小程序实现这个功能。

上代码:

#include

#include

#include

#include

#include

#include

//程序发生了严重的错误,输出

void error_quit(const char *str)

{

fprintf(stderr, "%s\n", str);

exit(1);

}

//专门用于接收信号的线程函数

static void *sig_thread(void *arg)

{

printf("subthread tid: %u\n", (unsigned int)pthread_self());

sigset_t *set = (sigset_t *) arg;

int res, sig;

while( 1 )

{

//挂起程序,等待信号的到来

res = sigwait(set, &sig);

if( res != 0 )

error_quit("sigwait error");

printf("tid: %u ", (unsigned int)pthread_self());

if( SIGALRM == sig )

{

printf("time out\n");

//循环设置闹钟信号,每5秒响一次

alarm(5);

}

else if( SIGTSTP == sig )

{

printf("catch quit signal\n");

break;

}

else if( SIGINT == sig )

{

printf("quit program\n");

exit(0);

}

}

}

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

{

pthread_t stid;

sigset_t set;

int res;

printf("main pid: %u, tid: %u\n",

(unsigned int)getpid(),

(unsigned int)pthread_self());

//设置要被线程处理的信号集

sigemptyset(&set);

sigaddset(&set, SIGINT);

sigaddset(&set, SIGTSTP);

sigaddset(&set, SIGALRM);

res = pthread_sigmask(SIG_BLOCK, &set, NULL);

if( res != 0 )

error_quit("pthread sigmask error");

alarm(1);

//开启信号处理线程,并让主线程等待其退出后才退出

res = pthread_create(&stid, NULL, &sig_thread, (void *) &set);

if (res != 0)

error_quit("pthread_create error");

pthread_join(stid, NULL);

printf("finish\n");

return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值