UNIX环境高级编程学习之第十二章线程控制-可重入(线程安全)的getenv方法
2010-06-25 14:26
435 查看
UNIX环境高级编程学习之第十二章线程控制-可重入(线程安全)的getenv方法
/* 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; }
相关文章推荐
- UNIX环境高级编程学习之第十二章线程控制-以分离状态创建线程
- UNIX环境高级编程 第十二章:线程控制
- UNIX环境高级编程学习之第十一章线程-线程的创建、退出、等待、取消、分离
- (十) 一起学 Unix 环境高级编程 (APUE) 之 线程控制
- UNIX环境高级编程(第12章 线程控制)
- Unix高级环境编程学习之-----线程pthread_create
- UNIX环境高级编程 第12章 线程控制
- UNIX环境高级编程-第12章- 线程控制 - 一
- UNIX环境编程学习笔记(27)——多线程编程(二):控制线程属性
- unix环境高级编程-线程控制(1)
- UNIX环境高级编程学习之第十一章线程-使用读写锁
- UNIX环境高级编程学习之第十一章线程-使用条件变量
- UNIX环境高级编程(十二)线程控制
- unix环境高级编程学习(1)-apue最简单编译方法
- UNIX环境高级编程-第12章- 线程控制 - 二
- UNIX环境编程学习笔记(27)——多线程编程(二):控制线程属性
- unix环境高级编程-线程控制(2)
- Unix环境高级编程:进程控制-线程控制-僵尸进程
- UNIX环境高级编程学习之第十一章线程-用互斥锁传送安全线程参数
- UNIX环境高级编程学习之第八章进程控制-用父子进程实现打开kate,返回kate关闭状态