我提前为一些代码转储道歉,我已经修剪了尽可能多的不重要的代码:
// Global vars / mutex stuff
extern char **environ;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
int
putenv_r(char *string)
{
int len;
int key_len = 0;
int i;
sigset_t block;
sigset_t old;
sigfillset(&block);
pthread_sigmask(SIG_BLOCK, &block, &old);
// This function is thread-safe
len = strlen(string);
for (int i=0; i < len; i++) {
if (string[i] == '=') {
key_len = i; // Thanks Klas for pointing this out.
break;
}
}
// Need a string like key=value
if (key_len == 0) {
errno = EINVAL; // putenv doesn't normally return this err code
return -1;
}
// We're moving into environ territory so start locking stuff up.
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != NULL; i++) {
if (strncmp(string, environ[i], key_len) == 0) {
// Pointer assignment, so if string changes so does the env.
// This behaviour is POSIX conformant, instead of making a copy.
environ[i] = string;
pthread_mutex_unlock(&env_mutex);
return(0);
}
}
// If we get here, the env var didn't already exist, so we add it.
// Note that malloc isn't async-signal safe. This is why we block signals.
environ[i] = malloc(sizeof(char *));
environ[i] = string;
environ[i+1] = NULL;
// This ^ is possibly incorrect, do I need to grow environ some how?
pthread_mutex_unlock(&env_mutex);
pthread_sigmask(SIG_SETMASK, &old, NULL);
return(0);
}
正如标题所说,我正在尝试编写putenv
的线程安全,异步信号安全可重入版本。代码的工作原理是它设置了像putenv
那样的环境变量,但我确实有一些顾虑:
strlen
不能保证异步信号安全,这意味着我的信号阻塞必须事先发生,但也许我错了。environ
的交互,但我很乐意以其他方式证明。我找到了另一个问题here的解决方案,其中他们只是设置了适当的信号阻塞和互斥锁定(病态押韵),然后正常调用putenv
。这有效吗?如果是这样,那显然比我的方法简单得多。
对于大块代码感到抱歉,我希望我已经建立了MCVE。为简洁起见,我在代码中错过了一些错误检查。谢谢!
如果您希望自己测试代码,以下是代码的其余部分,包括main:
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
// Prototypes
static void thread_init(void);
int putenv_r(char *string);
int
main(int argc, char *argv[]) {
int ret = putenv_r("mykey=myval");
printf("%d: mykey = %s\n", ret, getenv("mykey"));
return 0;
}
答案 0 :(得分:3)
此代码存在问题:
// If we get here, the env var didn't already exist, so we add it.
// Note that malloc isn't async-signal safe. This is why we block signals.
environ[i] = malloc(sizeof(char *));
environ[i] = string;
它在堆上创建char *
,将char *
的地址分配给environ[i]
,然后使用string
中包含的地址覆盖该值。那不行。它不保证environ
之后以NULL结尾。
因为char **environ
is a pointer to an array of pointers。数组中的最后一个指针是NULL
- 代码可以告诉它到达环境变量列表的末尾。
这样的事情会更好:
unsigned int envCount;
for ( envCount = 0; environ[ envCount ]; envCount++ )
{
/* empty loop */;
}
/* since environ[ envCount ] is NULL, the environ array
of pointers has envCount + 1 elements in it */
envCount++;
/* grow the environ array by one pointer */
char ** newEnviron = realloc( environ, ( envCount + 1 ) * sizeof( char * ) );
/* add the new envval */
newEnviron[ envCount - 1 ] = newEnvval;
/* NULL-terminate the array of pointers */
newEnviron[ envCount ] = NULL;
environ = newEnviron;
请注意,没有错误检查,并且它假设原始environ
数组是通过调用malloc()
或类似内容获得的。如果该假设是错误的,则行为未定义。