歡迎您光臨本站 註冊首頁

淺談linux模擬多線程崩潰和多進程崩潰

←手機掃碼閱讀     zmcjlove @ 2020-06-08 , reply:0

結論是:
 多線程下如果其中一個線程崩潰了會導致其他線程(整個進程)都崩潰;
 多進程下如果其中一個進程崩潰了對其餘進程沒有影響;

多線程

  #include#include#include#include#includevoid *fun1(void *arg)  {   printf("fun1 enter ");   while(1)   {    printf("%s ", __FUNCTION__);    usleep(1000 * 1000);   }   printf("fun1 exit ");   return ((void *)1);  }    void *fun2(void *arg)  {   printf("fun1 enter ");   usleep(1000 * 3000);   char * ptr = (char *)malloc(sizeof(char));   printf("ptr1: 0x%x ", ptr);   ptr = NULL;   printf("ptr2: 0x%x ", ptr);   free(ptr);   memcpy(ptr, "123", 3);   printf("ptr3: 0x%x ", ptr);   printf("fun2 exit ");   return ((void *)2);  }    int main(void)  {   pthread_t tid1, tid2;   int err;      err = pthread_create(&tid1, NULL, fun1, NULL);   assert(0 == err);   err = pthread_create(&tid2, NULL, fun2, NULL);   assert(0 == err);      printf("main join ... ");  // getchar();   pthread_join(tid1, NULL);   pthread_join(tid2, NULL);      return 0;  }

 

多進程

  #include#include#include#include#includevoid fun(void *arg)  {   printf("fun1 enter ");   usleep(1000 * 3000);   char * ptr = (char *)malloc(sizeof(char));   printf("ptr1: 0x%x ", ptr);   ptr = NULL;   printf("ptr2: 0x%x ", ptr);   free(ptr);   memcpy(ptr, "123", 3);   printf("ptr3: 0x%x ", ptr);   printf("fun2 exit ");   return ;  }    int main(int argc, char *argv[])  {   assert(2 == argc);   pid_t pid;   int i;   for(i=0; ipid)    {     printf("fork error");     exit(1);    }    else if(0 == pid)    {     printf("child pid is %lu ", (unsigned long)getpid());     fun(NULL);     exit(0);    }   }      printf("parent pid is %lu ", (unsigned long)getpid());   while(-1 != wait(NULL));  //等待所有子進程結束   printf("main return ");   getchar();      return 0;  }

 


                                                     

   


[zmcjlove ] 淺談linux模擬多線程崩潰和多進程崩潰已經有222次圍觀

http://coctec.com/docs/linux/show-post-237526.html