c - 如何使 putenv 成为可重入函数?

标签 c segmentation-fault

函数 putenv 不是线程安全函数,所以我想如果我在调用 putenv 之前调用 pthread_mutex_lock,我可以让 putenv 这样“线程安全”?

我试过了,但是当我运行它的时候,出现了段错误。

代码如下:

#include "apue.h"
#include <pthread.h>

pthread_mutex_t envlock = PTHREAD_MUTEX_INITIALIZER;

void thread_func(void*arg){
    pthread_mutex_lock(&envlock);        
    char env[100];
    sprintf(env,"hhh=%s",(char*)arg);
    putenv(env);
    pthread_mutex_unlock(&envlock);        
    return;
}

int main(){

    pthread_t thread0, thread1, thread2;

    void *shit;
    int err;
    char name0[]="thread0";
    err=pthread_create(&thread0,NULL,thread_func,(void*)name0);
    if(err!=0)
        exit(-1);


    char name1[]="thread1";
    err=pthread_create(&thread1,NULL,thread_func,(void*)name1);
    if(err!=0)
        exit(-1);


    char name2[]="thread2";
    err=pthread_create(&thread2,NULL,thread_func,(void*)name2);
    if(err!=0)
        exit(-1);

    pthread_join(thread0,&shit);
    pthread_join(thread1,&shit);
    pthread_join(thread2,&shit);

    char *hhh=getenv("hhh");
    printf("hhh is =%s",hhh);

    return 0;
}

最佳答案

putenv 在较新版本的 glibc 中是可重入的。问题是 putenv 不会复制给它的字符串,因此你不能将它基于你的堆栈。尝试将 char env[100] 保存在函数结束时不会被销毁的地方。

The putenv() function is not required to be reentrant, and the one in glibc 2.0 is not, but the glibc 2.1 version is.

...

Since version 2.1.2, the glibc implementation conforms to SUSv2: the pointer string given to putenv() is used. In particular, this string becomes part of the environment; changing it later will change the environment. (Thus, it is an error to call putenv() with an automatic variable as the argument, then return from the calling function while string is still part of the environment.)

关于c - 如何使 putenv 成为可重入函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58113740/

相关文章:

c - 如何将密码短语转换为 128 位/256 位 WEP key ?

c - 不兼容的 AES 实现?

c - Lua C 模块 : confused about including members

c - 操作系统的低级指针处理

c - 段错误(Core Dumped)--结构和指针--C语言

c - 我程序中的段错误

c - 找出C中查找表的大小

使用 Strcmp 的 C 段错误

c++ - 随机字符串生成器段错误

gcc - gcov 的段错误