UNIX环境高级编程学习之第十二章线程控制-可重入(线程安全)的getenv方法
[code lang=”cpp”]/*
FileName: getenv_r.c
Date: 20100625
Desc: gcc getenv_r.c -lpthread -o demo
可重入(线程安全)的getenv方法
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
extern char **environ;
pthread_mutex_t g_env_mutex; // 互斥锁定义 环境变量互斥锁
static pthread_once_t g_init_done = PTHREAD_ONCE_INIT; // 每个进程里只调用一次

static void thread_init(void) // 线程里初始化互斥锁
{
pthread_mutexattr_t attr; // 定义互斥锁属性
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); // 设置互斥锁为多次加锁
pthread_mutex_init(&g_env_mutex, &attr); // 互斥锁定义并初始化
pthread_mutexattr_destroy(&attr);
}
int getenv_r(const char *name, char *buf, const int buflen)
{
int i, len, olen;
pthread_once(&g_init_done, thread_init); // 本进程只调用一次thread_init方法
len = strlen(name);
pthread_mutex_lock(&g_env_mutex);
for (i=0; environ[i] != NULL; i++)
{
if (strncmp(name, environ[i], len) == 0 && environ[i][len] == ‘=’)
{
olen = strlen(&environ[i][len+1]);
if (olen >= buflen)
{
pthread_mutex_unlock(&g_env_mutex);
return ENOSPC;
}
strcpy(buf, &environ[i][len+1]);
pthread_mutex_unlock(&g_env_mutex);
return 0;
}
}
pthread_mutex_unlock(&g_env_mutex);
return ENOENT;
}

void* thread_fun(void * arg)
{
while (1)
{
char buf[256] = { 0x00 };
getenv_r("PWD", buf, sizeof(buf));
printf("PID=%ul getenv_r(/"PWD/")=%s /n", pthread_self(), buf);
usleep(1);
}
return (void*)1;
}

int main(int argc, char* argv[])
{
int ret;
pthread_t t1, t2;
ret = pthread_create(&t1, NULL, thread_fun, NULL);
if (ret != 0)
{
printf("pthread_create() is Error t1 /n");
exit(-1);
}
ret = pthread_create(&t2, NULL, thread_fun, NULL);
if (ret != 0)
{
printf("pthread_create() is Error t2 /n");
exit(-1);
}
while (1)
{
if (getchar() == ‘q’)
{
break;
}
}
pthread_mutex_destroy(&g_env_mutex); // 销毁互斥锁 环境变量互斥锁
return 0;
}

[/code]

发表评论