Golang 之os 包功能分析及实例

接口函数列表

func Hostname
func Hostname() (name string, err error)
Hostname返回内核提供的主机名。

func Getpagesize 
func Getpagesize() int
Getpagesize返回底层的系统内存页的尺寸。


func Environ
func Environ() []string
Environ返回表示环境变量的格式为"key=value"的字符串的切片拷贝。

func Getenv
func Getenv(key string) string
Getenv检索并返回名为key的环境变量的值。如果不存在该环境变量会返回空字符串。

func Setenv
func Setenv(key, value string) error
Setenv设置名为key的环境变量。如果出错会返回该错误。


func Clearenv
func Clearenv()
Clearenv删除所有环境变量。

func Exit
func Exit(code int)
Exit让当前程序以给出的状态码code退出。一般来说,状态码0表示成功,非0表示出错。程序会立刻终止,defer的函数不会被执行。

func Getuid
func Getuid() int
Getuid返回调用者的用户ID。

func Getgid
func Getgid() int
Getgid返回调用者的组ID。

func Getpid
func Getpid() int
Getpid返回调用者所在进程的进程ID。

func Getppid
func Getppid() int
Getppid返回调用者所在进程的父进程的进程ID。

实例

package main

import (
	"log"
	"os"
	"strconv"
)

func example_Getenv() {
    
    
	gopath := os.Getenv("GOPATH")
	log.Println(gopath)
}

func example_ExpandEnv() {
    
    
	s := "golan $GOPATH"
	log.Println(os.ExpandEnv(s))
	name, _ := os.Hostname()
	log.Println(name)
}

func example_Getpid() {
    
    
	log.Println("pid:" + strconv.Itoa(os.Getppid()))
	log.Println("page size:" + strconv.Itoa(os.Getpagesize()))
	log.Println("ppid:" + strconv.Itoa(os.Getppid()))
	grp, _ := os.Getgroups()
	log.Println(grp)
	log.Println("euid:" + strconv.Itoa(os.Geteuid()))
}

func main() {
    
    
	example_Getenv()
	example_ExpandEnv()
	example_Getpid()
}

运行结果

robot@ubuntu:~/go-workspace/src/project/os$ ./os 
2021/08/18 02:55:35 /home/robot/golang
2021/08/18 02:55:35 ubuntu
2021/08/18 02:55:35 golan /home/robot/golang
2021/08/18 02:55:35 pid:37510
2021/08/18 02:55:35 page size:4096
2021/08/18 02:55:35 ppid:37510
2021/08/18 02:55:35 [4 24 27 30 46 116 126 1000]
2021/08/18 02:55:35 euid:1000

猜你喜欢

转载自blog.csdn.net/weixin_38387929/article/details/119785940
今日推荐