linux下pthread_create與fork的安全問題
pthread_create 線程資源的釋放
1.等待線程退出,並釋放線程所佔用的資源。
pthread_t t;
pthread_create( &t, NULL, Thread, NULL);
pthread_join(t);
2.創建線程時將線程屬性設置爲爲detach,線程結束時由系統釋放線程資源
pthread_t t;
pthread_attr_t a;
pthread_attr_init(&a);
pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
pthread_create( &t, &a, GetAndSaveAuthviewSDRStub, (void*)lp);
3.線程將自己屬性更改爲detach,線程結束時由系統釋放線程資源
pthread_detach(pthread_self());
fork 進程資源的釋放
1.等待子進程結束,父進程回收資源
int childpid = fork();
if (childpid == 0)
{
printf("i am child!\n");
exit(0);
}
else if (childpid > 0)
{
printf("i am father!\n");
wait(&childpid);
printf("child is done\n\n");
}
2.創建回調函數進行回收
static void signal_call(int signo)
{
int status;
int pid_num;
if (signo == SIGCHLD)
{
pid_num = waitpid(-1, &status, WNOHANG);
printf("pid_num is %d\n", pid_num);
}
return;
}
if (signal(SIGCHLD, signal_call) == SIG_ERR)
{
perror("signal error");
}
3.由Init回收資源
int childpid = fork();
signal(SIGCHLD,SIG_IGN);
if (childpid == 0)
{
printf("i am child!\n");
exit(0);
}
else if (childpid > 0)
{
printf("i am father!\n");
}