linux线程终止信号,c-如何终止正在等待信号量操作的线程

我正在编写一个使用共享内存和ipc信号灯的程序.有一个主服务器进程创建共享内存和信号灯.任何数量的客户端进程都可以连接到共享内存,并在允许时对其进行读写.信号量提供了阻止机制来控制读取和写入.一切正常,除非我尝试终止客户端.用于访问共享内存的信号量块在一个线程中,并且在进程终止时,我无法释放信号量块,因此线程可以正确退出.我将如何处理?这是针对Linux的.

具体来说,有一个shm和两个sems.第一学期阻止写作,第二学期阻止阅读.当客户端有要写入的内容时,它将等待写入sem为0,然后将其设置为1,进行写入,然后将读取sem设置为0,这将释放等待的服务器以读取客户端写入的内容.读取后,服务器会将写入sem设置回0,并且下一个客户端将开始写入.它挂在一个semop调用上,当读sem为0时释放该semop调用.此semop调用在线程中,我需要弄清楚如何在退出主线程之前正确退出该线程.

这是我想做的但不起作用的示例(睡眠伪装成挂断电话):

#include

#include

#include

#include

#include

#include

void termination_handler (int signum) {

printf( "Got Signal

" );

}

void *threadfunc( void *parm ) {

struct sigaction action;

action.sa_handler = termination_handler;

sigemptyset( &action.sa_mask );

action.sa_flags = 0;

sigaction( SIGUSR1, &action, NULL );

printf("Thread executing

");

sleep( 100 ); // pretending to be the semaphore

pthread_exit( NULL );

}

int main() {

int status;

pthread_t threadid;

int thread_stat;

status = pthread_create( &threadid, NULL, threadfunc, NULL );

if ( status < 0) {

perror("pthread_create failed");

exit(1);

}

sleep( 5 );

status = pthread_kill( threadid, SIGUSR1 );

if ( status < 0 )

perror("pthread_kill failed");

status = pthread_join( threadid, (void *)&thread_stat );

if ( status < 0 )

perror("pthread_join failed");

exit( 0 );

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值