gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:45:52 25 4
gpt4 key购买 nike

函数 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com