go package学习——os

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

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

1. Index

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。

转载于:https://my.oschina.net/renguijiayi/blog/159073

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值