go package学习——os

os package的内容基本与c的一致,如果有《Unix环境高级编程》的基础,会非常容易理解和掌握os package。这一系列的文章只作为自己学习的记录,不会面面俱到,如果有任何疑问还是建议自己阅读相关文档。

文档会以Index的自动缩进为分层次阐述的依据。一个需要注意的地方是,包中所给的是函数还是方法,以及它的返回值。

1. Index

  • Constants
  • Variables
  • 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 Environ() []string
  • 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() (pwd 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 Lchown(name string, uid, gid int) error
  • func Link(oldname, newname string) error
  • func Mkdir(name string, perm FileMode) error
  • func MkdirAll(path string, perm FileMode) error
  • func NewSyscallError(syscall string, err error) error
  • func Readlink(name string) (string, error)
  • func Remove(name string) error
  • func RemoveAll(path string) error
  • func Rename(oldname, newname 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
  • type File
    • func Create(name string) (file *File, err error)
    • func NewFile(fd uintptr, name string) *File
    • func Open(name string) (file *File, err error)
    • func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
    • func Pipe() (r *File, w *File, err 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) (fi []FileInfo, err 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) Stat() (fi FileInfo, err error)
    • func (f *File) Sync() (err 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) (ret int, err error)
  • type FileInfo
    • func Lstat(name string) (fi FileInfo, err error)
    • func Stat(name string) (fi FileInfo, err error)
  • type FileMode
    • func (m FileMode) IsDir() bool
    • func (m FileMode) IsRegular() bool
    • func (m FileMode) Perm() FileMode
    • func (m FileMode) String() string
  • type LinkError
    • func (e *LinkError) Error() string
  • type PathError
    • func (e *PathError) Error() string
  • type ProcAttr
  • type Process
    • func FindProcess(pid int) (p *Process, err 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) 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

Package Files

dir_unix.go doc.go env.go error.go error_posix.go exec.go exec_posix.go exec_unix.go file.go file_posix.go file_unix.go getwd.go path.go path_unix.go pipe_linux.go proc.go stat_linux.go sys_linux.go types.go types_notwin.go

2. os基本函数

这部分首先定义了一些常量,用于打开或创建文件、定义文件偏移、定义/dev/null等:

const (
    O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist
    O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    O_TRUNC  int = syscall.O_TRUNC  // if possible, truncate file when opened.
)
const (
    SEEK_SET int = 0 // seek relative to the origin of the file
    SEEK_CUR int = 1 // seek relative to the current offset
    SEEK_END int = 2 // seek relative to the end
)
const (
    PathSeparator     = '/' // OS-specific path separator
    PathListSeparator = ':' // OS-specific path list separator
)
const DevNull = "/dev/null"
接下来定义了一系列变量,包括系统调用产生的错误、标准输出/输入/错误、获取命令行输入的参数等:
var (
    ErrInvalid    = errors.New("invalid argument")
    ErrPermission = errors.New("permission denied")
    ErrExist      = errors.New("file already exists")
    ErrNotExist   = errors.New("file does not exist")
)
var (
    Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
)
var Args []string
Args是一个string 类型的slice,它是以程序名作为第一个元素的,也就是说Args[0]="program name"

下面就是一些基本函数了,其中不清楚的函数有:

func Expand 

func Expand(s string, mapping func(string) string) string

Expand replaces ${var} or $var in the string based on the mapping function. For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).

func Truncate

func Truncate(name string, size int64) error

改变named file的size,如果file是一个符号链接,其改变的是link过去的target。

3. type File

这部分是与文件操作相关的函数:

type File

type File struct {  // contains filtered or unexported fields }
File代表了一个打开文件描述符。

func Create

func Create(name string) (file *File, err error)
此函数与c中的create不同,采用默认权限,如果文件存在则截断,创建的文件默认可读写。

func NewFile

func NewFile(fd uintptr, name string) *File

NewFile returns a new File with the given file descriptor and name. 根据所给的文件描述符和新文件名,返回一个新文件?

func Open

func Open(name string) (file *File, err error)
利用此Open返回的File,其属性是O_RDONLY,只能进行读操作。

func OpenFile

func OpenFile(name string, flag int, perm FileMode) (file *File, err error)
OpenFile是通用的open call,它可以指定flag(O_RDONLY等)、perm(0666等)。

func (*File) Read

func (f *File) Read(b []byte) (n int, err error)
Read从f中读取len(b) bytes到b,它返回读取的bytes数。

func (*File) ReadAt

func (f *File) ReadAt(b []byte, off int64) (n int, err error)
ReadAt从byte offset off处读取len(b)个字节,返回读取的字节数;c中没有这个函数。

func (*File) Readdir

func (f *File) Readdir(n int) (fi []FileInfo, err error)
读取和f相关的目录信息,其返回值和Lstat相同;如果n>0,其返回最多n个FileInfo;如果n<=0,其返回和f相关的所有目录的FileInfo。

func (*File) Readdirnames

func (f *File) Readdirnames(n int) (names []string, err error)
与Readdir意思相同,只是返回的是目录的名字。

func (*File) Write

func (f *File) Write(b []byte) (n int, err error)
Write向f写入len(b) bytes数据(slice b中的数据),返回写入的字节数n。

func (*File) WriteString

func (f *File) WriteString(s string) (ret int, err error)
WriteString向f写入的是string,而不是byte类型的slice。

4. type FileInof

这部分描述的是FileInfo结构体及其操作,FileInfo类似c中的File结构体。

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)
}
由Stat或Lstat返回的file描述信息。

func Lstat 

func Lstat(name string) (fi FileInfo, err error)
返回name指定的文件的FileInfo,如果此文件是一个符号链接,则返回此符号链接的FileInfo;Lstat不会跟踪链接。

5. type FileMode

此部分描述的是FileMode及其相关操作,包括文件状态描述符和权限。

const (
    // The single letters are the abbreviations
    // used by the String method's formatting.
    ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
    ModeAppend                                     // a: append-only
    ModeExclusive                                  // l: exclusive use
    ModeTemporary                                  // T: temporary file (not backed up)
    ModeSymlink                                    // L: symbolic link
    ModeDevice                                     // D: device file
    ModeNamedPipe                                  // p: named pipe (FIFO)
    ModeSocket                                     // S: Unix domain socket
    ModeSetuid                                     // u: setuid
    ModeSetgid                                     // g: setgid
    ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
    ModeSticky                                     // t: sticky

    // Mask for the type bits. For regular files, none will be set.
    ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice

    ModePerm FileMode = 0777 // permission bits
)

func (FileMode) Perm 

func (m FileMode) Perm() FileMode
返回Unix permission bits。

6. type Process

type Process struct {
    Pid int
    // contains filtered or unexported fields
}
Process存储了由StartProcess创建的进程信息。

func StartProcess 

func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
根据提供的程序名、环境变量、属性等信息启动一个新的Process。StartProcess是一个低级别的接口。

func (*Process) Kill

func (p *Process) Kill() error
Kill是一个方法,会使调用它的Process立即exit。

func (*Process) Signal 

func (p *Process) Signal(sig Signal) error
向Process发一个信号。比c中的signal简单很多。

func (*Process) Wait

func (p *Process) Wait() (*ProcessState, error)
Wait等待一个Process结束,并返回一个ProcessState structure描述此退出进程的状态。

7. type ProcessState

type ProcessState struct {
    // contains filtered or unexported fields
}
存储了一个Process的信息。

func (*ProcessState) SystemTime

func (p *ProcessState) SystemTime() time.Duration
返回退出进程p及其子进程的系统CPU时间。

8. type Signal

type Signal interface {
    String() string
    Signal() // to distinguish from other Stringers
}
Signal代表了一个操作系统的signal。

var (
    Interrupt Signal = syscall.SIGINT
    Kill      Signal = syscall.SIGKILL
)
所有系统都包含的两个signal是Interrupt和Kill。

你可能感兴趣的:(go package学习——os)