Go的基础标准库 OS(包含exec,user,signal)
文档定位:https://pkg.go.dev/os
源码定位:https://cs.opensource.google/go/go/+/refs/tags/go1.17.6:src/os/
OS包有本身函数,并向下包含三个包 os/exec,os/signal,os/user
os包中是对操作系统的文件管理相关的功能进行封装。
os/exec包是对可执行文件的控制,配合os/signal的两个控制信号的使用以达到进程属性的控制
os
要注意本身的常量,变量结构
func Chdir(dir string) error
func Chmod(name string, mode FileMode) error
func Chown(name string, uid, gid int) error
func Chtimes(name string, atime time.Time, mtime time.Time) error
func Clearenv()
func DirFS(dir string) fs.FS
func Environ() []string
func Executable() (string, error)
func Exit(code int)
func Expand(s string, mapping func(string) string) string
func ExpandEnv(s string) string
func Getegid() int
func Getenv(key string) string
func Geteuid() int
func Getgid() int
func Getgroups() ([]int, error)
func Getpagesize() int
func Getpid() int
func Getppid() int
func Getuid() int
func Getwd() (dir string, err error)
func Hostname() (name string, err error)
func IsExist(err error) bool
func IsNotExist(err error) bool
func IsPathSeparator(c uint8) bool
func IsPermission(err error) bool
func IsTimeout(err error) bool
func Lchown(name string, uid, gid int) error
func Link(oldname, newname string) error
func LookupEnv(key string) (string, bool)
func Mkdir(name string, perm FileMode) error
func MkdirAll(path string, perm FileMode) error
func MkdirTemp(dir, pattern string) (string, error)
func NewSyscallError(syscall string, err error) error
func Pipe() (r *File, w *File, err error)
func ReadFile(name string) ([]byte, error)
func Readlink(name string) (string, error)
func Remove(name string) error
func RemoveAll(path string) error
func Rename(oldpath, newpath string) error
func SameFile(fi1, fi2 FileInfo) bool
func Setenv(key, value string) error
func Symlink(oldname, newname string) error
func TempDir() string
func Truncate(name string, size int64) error
func Unsetenv(key string) error
func UserCacheDir() (string, error)
func UserConfigDir() (string, error)
func UserHomeDir() (string, error)
func WriteFile(name string, data []byte, perm FileMode) error
type DirEntry
func ReadDir(name string) ([]DirEntry, error)
type File
func Create(name string) (*File, error)
func CreateTemp(dir, pattern string) (*File, error)
func NewFile(fd uintptr, name string) *File
func Open(name string) (*File, error)
func OpenFile(name string, flag int, perm FileMode) (*File, error)
func (f *File) Chdir() error
func (f *File) Chmod(mode FileMode) error
func (f *File) Chown(uid, gid int) error
func (f *File) Close() error
func (f *File) Fd() uintptr
func (f *File) Name() string
func (f *File) Read(b []byte) (n int, err error)
func (f *File) ReadAt(b []byte, off int64) (n int, err error)
func (f *File) ReadDir(n int) ([]DirEntry, error)
func (f *File) ReadFrom(r io.Reader) (n int64, err error)
func (f *File) Readdir(n int) ([]FileInfo, error)
func (f *File) Readdirnames(n int) (names []string, err error)
func (f *File) Seek(offset int64, whence int) (ret int64, err error)
func (f *File) SetDeadline(t time.Time) error
func (f *File) SetReadDeadline(t time.Time) error
func (f *File) SetWriteDeadline(t time.Time) error
func (f *File) Stat() (FileInfo, error)
func (f *File) Sync() error
func (f *File) SyscallConn() (syscall.RawConn, error)
func (f *File) Truncate(size int64) error
func (f *File) Write(b []byte) (n int, err error)
func (f *File) WriteAt(b []byte, off int64) (n int, err error)
func (f *File) WriteString(s string) (n int, err error)
type FileInfo
func Lstat(name string) (FileInfo, error)
func Stat(name string) (FileInfo, error)
type FileMode
type LinkError
func (e *LinkError) Error() string
func (e *LinkError) Unwrap() error
type PathError
type ProcAttr
type Process
func FindProcess(pid int) (*Process, error)
func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
func (p *Process) Kill() error
func (p *Process) Release() error
func (p *Process) Signal(sig Signal) error
func (p *Process) Wait() (*ProcessState, error)
type ProcessState
func (p *ProcessState) ExitCode() int
func (p *ProcessState) Exited() bool
func (p *ProcessState) Pid() int
func (p *ProcessState) String() string
func (p *ProcessState) Success() bool
func (p *ProcessState) Sys() interface{}
func (p *ProcessState) SysUsage() interface{}
func (p *ProcessState) SystemTime() time.Duration
func (p *ProcessState) UserTime() time.Duration
type Signal
type SyscallError
func (e *SyscallError) Error() string
func (e *SyscallError) Timeout() bool
func (e *SyscallError) Unwrap() error
//os 这几个看到名字差不多就懂了
Chdir,Chmod,Chown,Getegid,Getenv,Geteuid,Getgid,Getgroups,Getpagesize,Getpid,Getppid,Getuid,Getwd,Hostname
//file 同类差不多看到名字就懂了
Create,CreateTemp,NewFile,Open,OpenFile
//
1. os 常用导出函数
func Hostname() (name string, err error) // Hostname返回内核提供的主机名
func Environ() []string // Environ返回表示环境变量的格式为”key=value”的字符串的切片拷贝
func Getenv(key string) string // Getenv检索并返回名为key的环境变量的值
func Getpid() int // Getpid返回调用者所在进程的进程ID
func Exit(code int) // Exit让当前程序以给出的状态码code退出。一般来说,状态码0表示成功,非0表示出错。程序会立刻终止,defer的函数不会被执行
func Stat(name string) (fi FileInfo, err error) // 获取文件信息
func Getwd() (dir string, err error) // Getwd返回一个对应当前工作目录的根路径
func Mkdir(name string, perm FileMode) error // 使用指定的权限和名称创建一个目录
func MkdirAll(path string, perm FileMode) error // 使用指定的权限和名称创建一个目录,包括任何必要的上级目录,并返回nil,否则返回错误
func Remove(name string) error // 删除name指定的文件或目录
func TempDir() string // 返回一个用于保管临时文件的默认目录
var Args []string Args保管了命令行参数,第一个是程序名。
————————————————
2. File 结构体
func Create(name string) (file *File, err error) // Create采用模式0666(任何人都可读写,不可执行)创建一个名为name的文件,如果文件已存在会截断它(为空文件)
func Open(name string) (file *File, err error) // Open打开一个文件用于读取。如果操作成功,返回的文件对象的方法可用于读取数据;对应的文件描述符具有O_RDONLY模式
func (f *File) Stat() (fi FileInfo, err error) // Stat返回描述文件f的FileInfo类型值
func (f *File) Readdir(n int) (fi []FileInfo, err error) // Readdir读取目录f的内容,返回一个有n个成员的[]FileInfo,这些FileInfo是被Lstat返回的,采用目录顺序
func (f *File) Read(b []byte) (n int, err error) // Read方法从f中读取最多len(b)字节数据并写入b
func (f *File) WriteString(s string) (ret int, err error) // 向文件中写入字符串
func (f *File) Sync() (err error) // Sync递交文件的当前内容进行稳定的存储。一般来说,这表示将文件系统的最近写入的数据在内存中的拷贝刷新到硬盘中稳定保存
func (f *File) Close() error // Close关闭文件f,使文件不能用于读写
————————————————
3. FileInfo 结构体
FileInfo用来描述一个文件对象,结构体定义:
type FileInfo interface {
Name() string // base name of the file
Size() int64 // length in bytes for regular files; system-dependent for others
Mode() FileMode // file mode bits
ModTime() time.Time // modification time
IsDir() bool // abbreviation for Mode().IsDir()
Sys() interface{} // underlying data source (can return nil)
}
func Stat(name string) (fi FileInfo, err error)
// Stat 返回描述文件的FileInfo。如果指定的文件对象是一个符号链接,返回的FileInfo描述该符号链接指向的文件的信息,本函数会尝试跳转该链接
func Lstat(name string) (fi FileInfo, err error)
// Lstat 返回描述文件对象的FileInfo。如果指定的文件对象是一个符号链接,返回的FileInfo描述该符号链接的信息,本函数不会试图跳转该链接。
————————————————
版权声明:本文为CSDN博主「好刚」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sanxiaxugang/article/details/61618911
os/user
包含两个主要结构 (User,Group)
type Group struct {
Gid string // group ID
Name string // group name
}
type User struct {
Uid string
Gid string
Username string
Name string
HomeDir string
}
相关函数
type Group
//获取group的Gid和Name
func LookupGroup(name string) (*Group, error)
//sample code
var name string = "Guests"
var a, _ = user.LookupGroup(name)
fmt.Println(a)
func LookupGroupId(gid string) (*Group, error)
//sample code
var name string = "S-1-5-32-546"
var a, _ = user.LookupGroupId(name)
fmt.Println(a)
type User
//获取User相关信息
func Current() (*User, error)
//sample code
start , _ := user.Current()
func Lookup(username string) (*User, error)
//sample code
info, _ := Lookup(start.Username)
func LookupId(uid string) (*User, error)
//sample code
info, _ := LookupId(start.Uid)
func (u *User) GroupIds() ([]string, error)
//sample code
User, _ := user.Current()
INFO, _ := User.GroupIds()
fmt.Println(INFO)
//以下为错误提示
type UnknownGroupError
func (e UnknownGroupError) Error() string
type UnknownGroupIdError
func (e UnknownGroupIdError) Error() string
type UnknownUserError
func (e UnknownUserError) Error() string
type UnknownUserIdError
func (e UnknownUserIdError) Error() string
os/exec
包含三个主要结构 (Cmd,Error,ExitError)
Cmd结构介绍在后面
type Cmd struct {
Path string
Args []string
Env []string
Dir string
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
ExtraFiles []*os.File
SysProcAttr *syscall.SysProcAttr
Process *os.Process
ProcessState *os.ProcessState
ctx context.Context // nil means none
lookPathErr error // LookPath error, if any.
finished bool // when Wait was called
childFiles []*os.File
closeAfterStart []io.Closer
closeAfterWait []io.Closer
goroutine []func() error
errch chan error // one send per goroutine
waitDone chan struct{}
}
运行一个命令
调用exec.Command(“ls”,"-lai"),返回的是*Cmd数据结构。调用了Run,Output,CombinedOutput方法后调用的对象就不能重复调用了。结果go并没有捕获所以控制台中没有任何的输出。
之后使用Run()函数运行外部命令,有一个error参数可接,错误信息可用cmd.Stdout/cmd.Stderr获取错误信息。
其实Run()是Start()与Wait()的封装,相关代码在exec.go中,Start()成功Process和ProcessState字段会被设置。可以检查ProcessState.Exited()。
func (c *Cmd) Run() error {
if err := c.Start(); err != nil {
return err
}
return c.Wait()
}
//Process与ProcessState是依靠os.StartProcess实现的,代码如下
c.Process, err = os.StartProcess(c.Path, c.argv(), &os.ProcAttr{
Dir: c.Dir,
Files: c.childFiles,
Env: addCriticalEnv(dedupEnv(envv)),
Sys: c.SysProcAttr,
})
Path Path string外部程序path
Args []string
Env 用来设置进程的环境变量,格式是key=value,var.Env = []string{"epath=/etc"}
Dir 工作路径,默认情况下进程的工作路径是调用这个进程的文件夹,var.Dir = "/home"
Stdin io.Reader
Stdout 设置bytes.Buffer,来实现读取 var stdoutbuff bytes.Buffer
Stderr 设置bytes.Buffer,来实现读取 var stderrbuff bytes.Buffer
ExtraFiles []*os.File
SysProcAttr *syscall.SysProcAttr
Process *os.Process
ProcessState *os.ProcessState
func LookPath(file string) (string, error) //可以用来判断外部命令是否存在
path, err := exec.LookPath("ls")
type Cmd
func Command(name string, arg ...string) *Cmd
// 命令返回 Cmd 结构来执行具有给定参数的命名程序
func CommandContext(ctx context.Context, name string, arg ...string) *Cmd
// CommandContext 与 Command 相似,但包含一个上下文。
// 如果上下文在命令完成之前完成,则提供的上下文用于终止进程(通过调用 os.Process.Kill )。
func (c *Cmd) CombinedOutput() ([]byte, error)
// 直接看代码就懂了,等同于Output(),流程初始化Stdout,Stderr在Run()
// 这里要注意不管出错与否都能一个方法获取输出结果,而Output()是命令正确才执行
/*
func (c *Cmd) CombinedOutput() ([]byte, error) {
if c.Stdout != nil {return nil, errors.New("exec: Stdout already set")}
if c.Stderr != nil {return nil, errors.New("exec: Stderr already set")}
var b bytes.Buffer
c.Stdout = &b
c.Stderr = &b
err := c.Run()
return b.Bytes(), err
}
*/
func (c *Cmd) Output() ([]byte, error) //获取命令结果
//sample code 获取命令结果
cmd := exec.Command("ls", "-lah")
data, err := cmd.Output()
func (c *Cmd) Run() error
func (c *Cmd) Start() error
func (c *Cmd) StderrPipe() (io.ReadCloser, error) // 管道相关,看源码就懂了
func (c *Cmd) StdinPipe() (io.WriteCloser, error) // 管道相关,看源码就懂了
func (c *Cmd) StdoutPipe() (io.ReadCloser, error) // 多个命令串成一个管道,管道相关,看源码就懂了
func (c *Cmd) String() string
func (c *Cmd) Wait() error
type Error
func (e *Error) Error() string
func (e *Error) Unwrap() error
type ExitError
func (e *ExitError) Error() string
os/signal
发送相关信号给程序,类似于kill -9,相关的在官方手册里都有。
func Ignore(sig ...os.Signal)
func Ignored(sig os.Signal) bool
func Notify(c chan<- os.Signal, sig ...os.Signal)
func NotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc)
func Reset(sig ...os.Signal)
func Stop(c chan<- os.Signal)
[https://colobu.com/2020/12/27/go-with-os-exec/]: go os/exec 简明教程 (colobu.com)
[https://cloud.tencent.com/developer/section/1143928]: Go - os - os/exec - 开发者手册 - 云+社区 - 腾讯云 (tencent.com)
[https://pkg.go.dev/os/]: os package - os - pkg.go.dev