|
《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
|