Reputation: 507
When I use setenv to set an environment value, it cannot be got by os.Getenv. Can someone tell me why?
package main
/*
#include <stdlib.h>
#include <stdio.h>
*/
import "C"
import "os"
import "strings"
import "fmt"
func main() {
C.setenv(C.CString("CSET"), C.CString("1.1.1.1:1111"), C.int(1)) //call setenv
C.puts(C.getenv(C.CString("CSET"))) // call getenv
addrs := strings.Split(os.Getenv("CSET"), ";")
fmt.Printf("addrs = %v\n", addrs)
os.Setenv("GOSET", "2.2.2.2:2222")
C.puts(C.getenv(C.CString("GOSET")))
}
dingrui@dingrui-PC:~/Projects/Temp$ go run env.go
1.1.1.1:1111
addrs = []
2.2.2.2:2222
Upvotes: 0
Views: 260
Reputation: 22154
This is a feature of Getenv
.
In the source file syscall/env_unix.go
, we see that a copy of the environment variables is made in the program initialization phase (envs []string = runtime_envs()
).
This copy is not updated if you modify the program environment variables in the background using the C functions.
Unfortunately, there is no way around this feature.
Upvotes: 1