golang os

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
)

seek的标记,不知道什么意思

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
命令参数

 

 

 

func Chdir(dir string) error
改变工作目录
func Chmod(name string, mode FileMode) error
func Chown(name string, uid, gid int) error
相当于UNIX里面的命令
func Chtimes(name string, atime time.Time, mtime time.Time) error
改变访问时间和修改时间
func Clearenv()
清除所有环境变量
func Environ() []string
返回环境变量,以key=value的形式

func Exit(code int)
结束当前程序,非0表示错误

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 ExpandEnv(s string) string

ExpandEnv replaces ${var} or $var in the string according to the values of the current environment variables. References to undefined variables are replaced by the empty string.

  这两个函数不懂

func Getenv(key string) string
获得key对应的环境变量
func Getegid() int
返回当前用户有效的组id
func Geteuid() int
返回该用户有效的id
func Getgid() int
返回该用户的组id
func Getgroups() ([]int, error)
返回该用户属于的所有组
func Getpagesize() int
这个也不懂
func Getpid() int
返回调用者的进程id
func Getppid() int
返回调用者上一级进程的进程id
func Getuid() int
返回调用者的user id
func Getwd() (pwd string, err error)
返回什么不知道……
func Hostname() (name string, err error)
返回Host名通过kernel
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
如果有link只改link
func Link(oldname, newname string) error
链接文件
func Mkdir(name string, perm FileMode) error
创建目录,第二个参数估计是权限什么的
func MkdirAll(path string, perm FileMode) error
创建目录,如果父目录没有的话也会创建,比如 /home/mike/parentepath/man.go

func NewSyscallError(syscall string, err error) error
new 一个新的系统调用错误
func Readlink(name string) (string, error)
返回link的目的地
func Remove(name string) error
移除文件或目录
func RemoveAll(path string) error
path包含的所有也会删除
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
返回临时目录,就是那种重启了什么都会没有了的目录,比如linux里面的tmp
func Truncate(name string, size int64) error
截取文件,如果是链接,截取链接的目标

接下来是File类型,源码里面是这样的

    15    // File represents an open file descriptor.
    16    type File struct {
    17        *file
    18    }
    19    
    20    // file is the real representation of *File.
    21    // The extra level of indirection ensures that no clients of os
    22    // can overwrite this data, which could cause the finalizer
    23    // to close the wrong file descriptor.
    24    type file struct {
    25        fd      int
    26        name    string
    27        dirinfo *dirInfo // nil unless directory being read
    28        nepipe  int32    // number of consecutive EPIPE in Write
    29    }
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)
打开文件,specified flag (O_RDONLY etc.) and perm, (0666 etc.) 以相应的权限和标记打开
func Pipe() (r *File, w *File, err error)
  Pipe returns a connected pair of Files; reads from r return bytes written to w. It returns the files and an error, if any.

 建立一根管道

func (f *File) Chdir() error
改变working目录到f所在的目录,必须是一个目录


func (f *File) Chmod(mode FileMode) error
  Chmod changes the mode of the file to mode. If there is an error, it will be of type *PathError.

func (f *File) Chown(uid, gid int) error
  Chown changes the numeric uid and gid of the named file. If there is an error, it will be of type *PathError.

 不解释

func (f *File) Close() error
打开文件记得  defer f.Close()

func (f *File) Fd() uintptr
返回文件描述符
func (f *File) Name() string
返回文件名
func (f *File) Read(b []byte) (n int, err error)
  It returns the number of bytes read and an error, if any. EOF is signaled by a zero count with err set to io.EOF.

  读取缓冲大小的数据(b是切片,实际上就是一个指针)

func (f *File) ReadAt(b []byte, off int64) (n int, err error)
读取从off开始的数据
func (f *File) Readdir(n int) (fi []FileInfo, err error)
func (f *File) Readdirnames(n int) (names []string, err error)
读取目录下的文件,一个要得到info一个要得到名字,n表示的是小于0读取全部,大于0就读取到n个

func (f *File) Seek(offset int64, whence int) (ret int64, err error)
Seek sets the offset for the next Read or Write on file to offset, interpreted according to whence: 0 means relative to the origin of the file, 1 means relative to the current offset, and 2 means relative to the end. It returns the new offset and an error, if any.

  offst偏移量,whence 0 表示从原始位置算, whence 1表示从当前位置算,whence2表示从末尾算(话说这个直接用数字来代表相对位置很奇怪……)

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 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)
}

 FileInfo记录的文件的信息

func Lstat(name string) (fi FileInfo, err error)
返回Link的fi,而不是所指向的fi
func Stat(name string) (fi FileInfo, err error)
返回文件信息
type FileMode uint32
A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is ModeDir for directories.

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 (m FileMode) IsDir() bool
FileMode形容的是否是目录
func (m FileMode) IsRegular() bool
是否是一般文件,没有设置Mode

func (m FileMode) Perm() FileMode
权限
func (m FileMode) String() string
对应的string

进程属性
type ProcAttr struct { // If Dir is non-empty, the child changes into the directory before // creating the process. Dir string // If Env is non-nil, it gives the environment variables for the // new process in the form returned by Environ. // If it is nil, the result of Environ will be used. Env []string // Files specifies the open files inherited by the new process. The // first three entries correspond to standard input, standard output, and // standard error. An implementation may support additional entries, // depending on the underlying operating system. A nil entry corresponds // to that file being closed when the process starts. Files []*File // Operating system-specific process creation attributes. // Note that setting this field means that your program // may not execute properly or even compile on some // operating systems. Sys *syscall.SysProcAttr }
func FindProcess(pid int) (p *Process, err error)
获取进程
func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)

StartProcess starts a new process with the program, arguments and attributes specified by name, argv and attr.

StartProcess is a low-level interface. The os/exec package provides higher-level interfaces.

If there is an error, it will be of type *PathError.

 启动进程

func (p *Process) Kill() error

Kill causes the Process to exit immediately.

func (p *Process) Release() error

Release releases any resources associated with the Process p, rendering it unusable in the future. Release only needs to be called if Wait is not.

func (p *Process) Signal(sig Signal) error

Signal sends a signal to the Process.

func (p *Process) Wait() (*ProcessState, error)

Wait waits for the Process to exit, and then returns a ProcessState describing its status and an error, if any. Wait releases any resources associated with the Process.

 剩下的标准暂时不明白,也暂时不需要看

type ProcessState

type ProcessState struct {
        // contains filtered or unexported fields
}
ProcessState stores information about a process, as reported by Wait.

func (*ProcessState) Exited

func (p *ProcessState) Exited() bool
Exited reports whether the program has exited.

func (*ProcessState) Pid

func (p *ProcessState) Pid() int
Pid returns the process id of the exited process.

func (*ProcessState) String

func (p *ProcessState) String() string
func (*ProcessState) Success

func (p *ProcessState) Success() bool
Success reports whether the program exited successfully, such as with exit status 0 on Unix.

func (*ProcessState) Sys

func (p *ProcessState) Sys() interface{}
Sys returns system-dependent exit information about the process. Convert it to the appropriate underlying type, such as syscall.WaitStatus on Unix, to access its contents.

func (*ProcessState) SysUsage

func (p *ProcessState) SysUsage() interface{}
SysUsage returns system-dependent resource usage information about the exited process. Convert it to the appropriate underlying type, such as *syscall.Rusage on Unix, to access its contents. (On Unix, *syscall.Rusage matches struct rusage as defined in the getrusage(2) manual page.)

func (*ProcessState) SystemTime

func (p *ProcessState) SystemTime() time.Duration
SystemTime returns the system CPU time of the exited process and its children.

func (*ProcessState) UserTime

func (p *ProcessState) UserTime() time.Duration
UserTime returns the user CPU time of the exited process and its children.

type Signal

type Signal interface {
        String() string
        Signal() // to distinguish from other Stringers
}
A Signal represents an operating system signal. The usual underlying implementation is operating system-dependent: on Unix it is syscall.Signal.

var (
        Interrupt Signal = syscall.SIGINT
        Kill      Signal = syscall.SIGKILL
)
The only signal values guaranteed to be present on all systems are Interrupt (send the process an interrupt) and Kill (force the process to exit).

type SyscallError

type SyscallError struct {
        Syscall string
        Err     error
}
SyscallError records an error from a specific system call.

func (*SyscallError) Error

func (e *SyscallError) Error() string
View Code

 

 
posted @ 2014-02-10 12:30  ggaaooppeenngg  阅读(1324)  评论(0编辑  收藏  举报