Prayer

在一般中寻求卓越
posts - 1256, comments - 190, trackbacks - 0, articles - 0
  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

使用信号杀死其他的线程

Posted on 2009-08-05 15:15 Prayer 阅读(261) 评论(0)  编辑 收藏 引用 所属分类: LINUX/UNIX/AIX

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

#define THREAD_NUM  3
pthread_t threadBuf[THREAD_NUM];
int       tcBuf[THREAD_NUM];

void* threadOpr1(void* arg);
void* threadOpr2(void* arg);
void  sigTermHandler(void);

/**********************************
试验一个线程杀死其他的线程
但是进程不退出
***********************************/
int main(){
   int i=0;
   pthread_t killer;
  
   /*signal(SIGCLD, SIG_IGN);*/
  
    for(i = 0; i < THREAD_NUM; i++){
        tcBuf[i] = i + 1;
        if( (pthread_create(&threadBuf[i], NULL,threadOpr1,
            &tcBuf[i])) != 0 ) {
            printf("pthread_create \n");
            return -1;           
        }    
    } 
   
    sleep(5);
   
    if( (pthread_create(&killer, NULL,threadOpr2,
        NULL)) != 0 ) {
        printf("pthread_create \n");
        return -1;           
    }
   
    sleep(30);
   
    printf("main exit\n");  
      
    return 0;  
}
/**********************************
被杀死的线程函数
***********************************/
void* threadOpr1(void* arg){
    int tcId=*(int *)arg;
    int i=0;
   
    signal(SIGTERM,(void (*)( ))sigTermHandler);
   
    while(i<10){
       printf("ID%d --%d  live\n",tcId,pthread_self());
       i++;
       sleep(2); 
    }
    printf("killed exit\n");
   
   pthread_exit(NULL);
}

/**********************************
杀死其他线程的线程
***********************************/
void* threadOpr2(void* arg){
    int i=0;
   
    for(i = 0; i < THREAD_NUM; i++){
        printf("%d \n",i);        
        if( (pthread_kill(threadBuf[i],SIGTERM)) != 0 ) {
            printf("pthread_kill \n");
            pthread_exit(NULL);           
        }
        sleep(2);   
    }
    sleep(30); 
   
    printf("killer exit \n"); 
      
   pthread_exit(NULL);
}

/**********************************
信号处理函数
***********************************/
void sigTermHandler(void)
{
  /*早期版本,每次信号处理完之后,随即将信号动作复置为默认值*/
    printf("sigal exit  %d\n",pthread_self());
   signal(SIGTERM,(void (*)( ))sigTermHandler);     
   pthread_exit(NULL);

}

结果:
ID3 --772  live
ID1 --258  live
ID2 --515  live
ID3 --772  live
ID1 --258  live
ID2 --515  live
ID3 --772  live
ID1 --258  live
ID2 --515  live
0
sigal exit  258
ID3 --772  live
ID2 --515  live
1
sigal exit  515
ID3 --772  live
2
sigal exit  772
main exit


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理