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");
}