随笔 - 47, 文章 - 10, 评论 - 8, 引用 - 0
数据加载中……

getenv的线程安全版本

《unix环境高级编程》上的

 1 #include  < string .h >
 2 #include  < errno.h >
 3 #include  < pthread.h >
 4 #include  < stdlib.h >
 5
 6 extern   char   ** environ;
 7
 8 pthread_mutex_t env_mutex;
 9 static  pthread_once_t init_donw  =  PTHREAD_ONCE_INIT;
10
11 static   void  thread_init( void )
12 {
13     pthread_mutexattr_t attr;
14     pthread_mutexattr_init( & attr);
15     pthread_mutexattr_settype( & attr,PTHREAD_MUTEX_RECURSIVE);  //  设置可递归的互斥量
16     pthread_mutex_init( & env_mutex, & attr);
17     pthread_mutexattr_destroy( & attr);
18 }

19
20 int  getevn_r( const   char   * name,  char   * buf,  int  buflen)
21 {
22      int  i, len, olen;
23     
24     pthread_once( & init_done,thread_init);  //  确保每个进程只调用一次threaad_init()
25     len  =  strlen(name);
26     pthread_mutex_lock( & env_mutex);
27      for (i = 0 ;environ[i] != NULL;i ++ )
28      {
29          if ( (strncmp(name,environ[i],len) == 0   &&  (environ[i][len]  ==   " = " ) )
30          {
31             olen  =  strlen( & environ[i][len + 1 ]);
32              if ( olen  >  buflen )  //  检查缓冲区长度是否足够
33              {
34                 pthread_mutex_unlock( & env_mutex);
35                  return (ENOSPC);
36             }

37             strcpy(buf, & environ[i][len + 1 ]);
38             pthread_mutex_unlock( & env_mutex);
39              return ( 0 );
40         }

41     }

42     pthread_mutex_unlock( & env_mutex);
43      return (ENOENT);
44 }

45

posted on 2006-09-14 16:24 编程之道 阅读(1610) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理