我正在測試基於Linux 2.6.21和pThread庫。 我嘗試了幾個案例,以找出解決方法如何避免主進程終止。但是,我沒有發現它。 請告訴我爲什麼退出線程函數導致主進程終止? 這裏是下面的測試代碼,爲什麼pThread退出導致主進程終止?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/signal.h>
#include <linux/input.h>
#include <fcntl.h>
#include <errno.h>
#include <dlfcn.h>
#include <time.h>
#include <pthread.h>
int handle = 0;
int main_loop = 0;
void *testThread(void *pParm)
{
int i;
for (i=0; i < 5 ; i++){
printf("====testThread loop %d\n", i);
sleep(1);
}
if (main_loop == 1){
exit(0);
}
else if (main_loop == 2)
{
sleep(10);
exit(0);
}
else if (main_loop == 3)
{
pthread_exit(NULL);
}
else if (main_loop == 4)
{
sleep(10);
pthread_exit(NULL);
}
}
int main(int argc, char *argv[])
{
pthread_t pTestThread;
int i, ret;
if (argc == 2){
main_loop = atoi(argv[1]);
}
if (argc == 3){
main_loop = atoi(argv[1]);
handle = atoi(argv[2]);
}
ret = pthread_create(&pTestThread, NULL, (void *)testThread, NULL);
if (0 == ret){
if (handle == 0)
pthread_detach(pTestThread);
printf("====Thread creation okay!\n");
}else{
printf("====Thread creation error!\n");
return 0;
}
if (handle == 1)
{
printf("====pthread_join waiting\n");
pthread_join(pTestThread, (void **)&ret);
printf("====pthread_join ret %d\n", ret);
}
for (i=0; i < 20; i++)
{
printf("====Main loop %d\n", i);
sleep(1);
}
printf("====Main Exit\n");
return 0;
}
在該代碼中,我從未見過「====主退出」的日誌用的各種組合(自變量第二和第三)。
請發佈一個完整的程序(包括全局變量,頭文件),以及在意外終止時使用的命令行輸入(或者 - 更好 - 刪除與意外終止無關的代碼,因此不存在依賴關係在命令行參數上)。 –
main_loop的價值是什麼? – immibis
什麼是「pThread退出」? –