Chinaunix首页 | 论坛 | 博客
  • 博客访问: 242340
  • 博文数量: 36
  • 博客积分: 743
  • 博客等级: 中士
  • 技术积分: 846
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-26 01:02
文章分类

全部博文(36)

文章存档

2014年(3)

2013年(4)

2012年(29)

分类: LINUX

2012-12-27 15:28:29

近日,程序开发用到了第一个第三方库,我自己的程序在main里,直接fork了一个子进程,父进程退出,发现fork出来的进程无法正常工作,如果不fork一切正常。
经过研究第三方的代码,发现在第三方库里定义了一个全局变量,这个全局变量的初始化,启动了一个线程。
现在问题就比较明确了。
是我的程序在fork之前,主进程就有了其他的线程,主进程退出之后,线程即停止执行,造成子进程执行异常。示例代码如下:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <errno.h>
  6. #include <pthread.h>
  7. #include <signal.h>
  8. #include <semaphore.h>

  9. typedef struct _singletone_param{
  10.     int running;
  11.     sem_t sem;
  12. }singletone_param_t;

  13. void * singletone_func(void* param){
  14.     singletone_param_t * pparam=(singletone_param_t*)param;

  15.     sem_post(&(pparam->sem));
  16.     while(pparam->running){
  17.         printf("i am running[pid=%u,tid=%lu]\n",getpid(),pthread_self());
  18.         sleep(1);
  19.     }
  20. }

  21. class singletone_t{
  22. public:
  23.     static singletone_t* Instance(){
  24.         static singletone_t obj;
  25.         return &obj;
  26.     }

  27.     ~singletone_t(){
  28.         if(tid){
  29.             param.running=0;
  30.             pthread_join(tid,NULL);
  31.         }

  32.         sem_destroy(&(param.sem));
  33.     }

  34. private:
  35.     singletone_param_t param;
  36.     pthread_t tid;

  37.     singletone_t(){
  38.         tid=0;
  39.         param.running=1;
  40.         sem_init(&(param.sem),0,0);
  41.         if(pthread_create(&tid,NULL,singletone_func,&param) !=0){
  42.             param.running=0;
  43.             printf("create thrad failed[%d(%s)]\n",errno,strerror(errno));
  44.         }
  45.         else{
  46.              while ( sem_wait(&(param.sem)) == -1 && errno == EINTR){
  47.      continue;
  48.              }
  49.         }
  50.     }
  51. };

  52. int child_running=0;

  53. void sig_handler( int sig_no ){
  54.     if(SIGINT==sig_no){
  55.         child_running=0;
  56.     }
  57. }

  58. singletone_t* obj = singletone_t::Instance();//全局变量

  59. int main(int argc,char **argv){
  60.     pid_t pid=0;

  61.     signal(SIGINT,sig_handler);

  62.     if( (pid=fork()) > 0 ){
  63.         printf("child process started:%u\n",pid);
  64.         return 0;
  65.     }
  66.     else if( pid<0 ){
  67.         printf("child process start failed[%d(%s)]\n",errno,strerror(errno));
  68.     }
  69.     else{
  70.         //singletone_t* obj2 = singletone_t::Instance();如果放到这里,就没有问题了
  71.         child_running=1;
  72.         while(child_running){
  73.             sleep(1);
  74.         }    
  75.     }
  76.     return 0;
  77. }

阅读(4022) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~