linux下pthread_create与fork的安全问题

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");
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值