1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Plan 9 environment variables.
15 // envOnce guards copyenv, which populates env.
18 // envLock guards env and envs.
21 // env maps from an environment variable to its value.
22 env = make(map[string]string)
24 // envs contains elements of env in the form "key=value".
27 errZeroLengthKey = errors.New("zero length key")
28 errShortWrite = errors.New("i/o count too small")
31 func readenv(key string) (string, error) {
32 fd, err := Open("/env/"+key, O_RDONLY)
37 l, _ := Seek(fd, 0, 2)
39 buf := make([]byte, l)
40 n, err := Read(fd, buf)
44 if n > 0 && buf[n-1] == 0 {
47 return string(buf), nil
50 func writeenv(key, value string) error {
51 fd, err := Create("/env/"+key, O_RDWR, 0666)
57 n, err := Write(fd, b)
68 fd, err := Open("/env", O_RDONLY)
73 files, err := readdirnames(fd)
77 envs = make([]string, len(files))
79 for _, key := range files {
80 v, err := readenv(key)
85 envs[i] = key + "=" + v
90 func Getenv(key string) (value string, found bool) {
96 defer envLock.RUnlock()
98 if v, ok := env[key]; ok {
101 v, err := readenv(key)
106 envs = append(envs, key+"="+v)
110 func Setenv(key, value string) error {
112 return errZeroLengthKey
116 defer envLock.Unlock()
118 err := writeenv(key, value)
123 envs = append(envs, key+"="+value)
129 defer envLock.Unlock()
131 env = make(map[string]string)
133 RawSyscall(SYS_RFORK, RFCENVG, 0, 0)
136 func Environ() []string {
138 defer envLock.RUnlock()
141 return append([]string(nil), envs...)