Package os

Overview ▾

Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.

The os interface is intended to be uniform across all operating systems. Features not generally available appear in the system-specific package syscall.

Here is a simple example, opening a file and reading some of it.

file, err := os.Open("file.go") // For read access.
if err != nil {
	log.Fatal(err)
}

If the open fails, the error string will be self-explanatory, like

open file.go: no such file or directory

The file's data can then be read into a slice of bytes. Read and Write take their byte counts from the length of the argument slice.

data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("read %d bytes: %q\n", count, data[:count])

Concurrency

The methods of File correspond to file system operations. All are safe for concurrent use. The maximum number of concurrent operations on a File may be limited by the OS or the system. The number should be high, but exceeding it may degrade performance or cause other issues.

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 CopyFS(dir string, fsys fs.FS) error
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
func afterResolvingSymlink(parent int, name string, f func() error) error
func atime(fi FileInfo) time.Time
func checkClonePidfd() error
func checkPidfd() error
func checkSymlink(parent int, name string, origError error) error
func chmod(name string, mode FileMode) error
func chmodat(parent int, name string, mode FileMode) error
func chownat(parent int, name string, uid, gid int) error
func chtimesUtimes(atime, mtime time.Time) [2]syscall.Timespec
func chtimesat(parent int, name string, atime time.Time, mtime time.Time) error
func convertESRCH(err error) error
func direntIno(buf []byte) (uint64, bool)
func direntNamlen(buf []byte) (uint64, bool)
func direntReclen(buf []byte) (uint64, bool)
func doInRoot[T any](r *Root, name string, flags uint, openDirFunc func(parent sysfdType, name string) (sysfdType, error), f func(parent sysfdType, name string, endsInSlash bool) (T, error)) (ret T, err error)
func endsWithDot(path string) bool
func ensurePidfd(sysAttr *syscall.SysProcAttr) (*syscall.SysProcAttr, bool)
func epipecheck(file *File, e error)
func errDeadlineExceeded() error
func errNoDeadline() error
func executable() (string, error)
func fillFileStatFromSys(fs *fileStat, name string)
func fixCount(n int, err error) (int, error)
func fixLongPath(path string) string
func genericReadFrom(f *File, r io.Reader) (int64, error)
func genericWriteTo(f *File, w io.Writer) (int64, error)
func getPidfd(sysAttr *syscall.SysProcAttr, needDup bool) (uintptr, bool)
func getPollFDAndNetwork(i any) (*poll.FD, poll.String)
func getShellName(s string) (string, int)
func hostname() (name string, err error)
func ignoreSIGSYS()
func ignoringEINTR(fn func() error) error
func ignoringEINTR2[T any](fn func() (T, error)) (T, error)
func init()
func isAlphaNum(c uint8) bool
func isDirectoryLink(fi FileInfo) bool
func isNoFollowErr(err error) bool
func isShellSpecialVar(c uint8) bool
func isUnixOrTCP(network string) bool
func isValidRootFSPath(name string) bool
func joinPath(dir, name string) string
func lchownat(parent int, name string, uid, gid int) error
func linkat(oldfd int, oldname string, newfd int, newname string) error
func mkdirat(fd int, name string, perm FileMode) error
func nextRandom() string
func open(path string, flag int, perm uint32) (int, poll.SysFile, error)
func pidfdFind(pid int) (uintptr, error)
func pidfdWorks() bool
func prefixAndSuffix(pattern string) (prefix, suffix string, err error)
func readFileContents(statSize int64, read func([]byte) (int, error)) ([]byte, error)
func readInt(b []byte, off, size uintptr) (u uint64, ok bool)
func readIntBE(b []byte, size uintptr) uint64
func readIntLE(b []byte, size uintptr) uint64
func readlink(name string) (string, error)
func readlinkat(fd int, name string) (string, error)
func removeAll(path string) error
func removeAllFrom(parentFd sysfdType, base string) error
func removeat(fd int, name string) error
func removedirat(fd int, name string) error
func removefileat(fd int, name string) error
func rename(oldname, newname string) error
func renameat(oldfd int, oldname string, newfd int, newname string) error
func restoreSIGSYS()
func rootChmod(r *Root, name string, mode FileMode) error
func rootChown(r *Root, name string, uid, gid int) error
func rootChtimes(r *Root, name string, atime time.Time, mtime time.Time) error
func rootCleanPath(s string, prefix, suffix []string) (string, error)
func rootLchown(r *Root, name string, uid, gid int) error
func rootLink(r *Root, oldname, newname string) error
func rootMkdir(r *Root, name string, perm FileMode) error
func rootMkdirAll(r *Root, fullname string, perm FileMode) error
func rootOpenDir(parent int, name string) (int, error)
func rootReadlink(r *Root, name string) (string, error)
func rootRemove(r *Root, name string) error
func rootRemoveAll(r *Root, name string) error
func rootRename(r *Root, oldname, newname string) error
func rootSymlink(r *Root, oldname, newname string) error
func runtime_args() []string
func runtime_beforeExit(exitCode int)
func runtime_rand() uint64
func sameFile(fs1, fs2 *fileStat) bool
func setStickyBit(name string) error
func sigpipe()
func splitPath(path string) (string, string)
func splitPathInRoot(s string, prefix, suffix []string) (_ []string, endsInSlash bool, err error)
func statOrZero(f *File) int64
func symlinkat(oldname string, newfd int, newname string) error
func syscallMode(i FileMode) (o uint32)
func tempDir() string
func tryLimitedReader(r io.Reader) (*io.LimitedReader, io.Reader, int64)
func underlyingError(err error) error
func underlyingErrorIs(err, target error) bool
func wrapSyscallError(name string, err error) error
type DirEntry
    func ReadDir(name string) ([]DirEntry, error)
    func newUnixDirent(parent *File, name string, typ FileMode) (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 OpenInRoot(dir, name string) (*File, error)
    func net_newUnixFile(fd int, name string) *File
    func newDirFile(fd int, name string) (*File, error)
    func newFile(fd int, name string, kind newFileKind, nonBlocking bool) *File
    func newFileFromNewFile(fd uintptr, name string) *File
    func openDir(name string) (*File, error)
    func openDirAt(dirfd sysfdType, name string) (*File, error)
    func openDirNolog(name string) (*File, error)
    func openFileNolog(name string, flag int, perm FileMode) (*File, error)
    func rootOpenFileNolog(root *Root, 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)
    func (f *File) WriteTo(w io.Writer) (n int64, err error)
    func (f *File) checkValid(op string) error
    func (f *File) chmod(mode FileMode) error
    func (file File) close() error
    func (f *File) copyFileRange(r io.Reader) (written int64, handled bool, err error)
    func (f *File) fd() uintptr
    func (f *File) lstatat(name string) (FileInfo, error)
    func (f *File) lstatatNolog(name string) (FileInfo, error)
    func (f *File) pread(b []byte, off int64) (n int, err error)
    func (f *File) pwrite(b []byte, off int64) (n int, err error)
    func (f *File) read(b []byte) (n int, err error)
    func (f *File) readFrom(r io.Reader) (written int64, handled bool, err error)
    func (f *File) readdir(n int, mode readdirMode) (names []string, dirents []DirEntry, infos []FileInfo, 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) spliceToFile(r io.Reader) (written int64, handled bool, err error)
    func (f *File) wrapErr(op string, err error) error
    func (f *File) write(b []byte) (n int, err error)
    func (f *File) writeTo(w io.Writer) (written int64, handled bool, err error)
type FileInfo
    func Lstat(name string) (FileInfo, error)
    func Stat(name string) (FileInfo, error)
    func lstatNolog(name string) (FileInfo, error)
    func lstatat(parent int, name string) (FileInfo, error)
    func lstatatWithName(parent int, origName, name string) (FileInfo, error)
    func rootStat(r *Root, name string, lstat bool) (FileInfo, error)
    func statNolog(name string) (FileInfo, error)
type FileMode
    func direntType(buf []byte) FileMode
    func modeAt(parent sysfdType, name string) (FileMode, error)
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 findProcess(pid int) (p *Process, err error)
    func newDoneProcess(pid int) *Process
    func newHandleProcess(pid int, handle uintptr) *Process
    func newPIDProcess(pid int) *Process
    func startProcess(name string, argv []string, attr *ProcAttr) (p *Process, err error)
    func (p *Process) Kill() error
    func (p *Process) Release() error
    func (p *Process) Signal(sig Signal) error
    func (p *Process) Wait() (*ProcessState, error)
    func (p *Process) WithHandle(f func(handle uintptr)) error
    func (p *Process) blockUntilWaitable() (bool, error)
    func (p *Process) doRelease(newStatus processStatus) processStatus
    func (p *Process) handleTransientAcquire() (uintptr, processStatus)
    func (p *Process) handleTransientRelease()
    func (p *Process) kill() error
    func (p *Process) pidSignal(s syscall.Signal) error
    func (p *Process) pidStatus() processStatus
    func (p *Process) pidWait() (*ProcessState, error)
    func (p *Process) pidfdSendSignal(s syscall.Signal) error
    func (p *Process) pidfdWait() (*ProcessState, error)
    func (p *Process) signal(sig Signal) error
    func (p *Process) wait() (ps *ProcessState, err error)
    func (p *Process) withHandle(f func(handle uintptr)) 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() any
    func (p *ProcessState) SysUsage() any
    func (p *ProcessState) SystemTime() time.Duration
    func (p *ProcessState) UserTime() time.Duration
    func (p *ProcessState) exited() bool
    func (p *ProcessState) success() bool
    func (p *ProcessState) sys() any
    func (p *ProcessState) sysUsage() any
    func (p *ProcessState) systemTime() time.Duration
    func (p *ProcessState) userTime() time.Duration
type Root
    func OpenRoot(name string) (*Root, error)
    func newRoot(fd int, name string) (*Root, error)
    func openRootInRoot(r *Root, name string) (*Root, error)
    func openRootNolog(name string) (*Root, error)
    func (r *Root) Chmod(name string, mode FileMode) error
    func (r *Root) Chown(name string, uid, gid int) error
    func (r *Root) Chtimes(name string, atime time.Time, mtime time.Time) error
    func (r *Root) Close() error
    func (r *Root) Create(name string) (*File, error)
    func (r *Root) FS() fs.FS
    func (r *Root) Lchown(name string, uid, gid int) error
    func (r *Root) Link(oldname, newname string) error
    func (r *Root) Lstat(name string) (FileInfo, error)
    func (r *Root) Mkdir(name string, perm FileMode) error
    func (r *Root) MkdirAll(name string, perm FileMode) error
    func (r *Root) Name() string
    func (r *Root) Open(name string) (*File, error)
    func (r *Root) OpenFile(name string, flag int, perm FileMode) (*File, error)
    func (r *Root) OpenRoot(name string) (*Root, error)
    func (r *Root) ReadFile(name string) ([]byte, error)
    func (r *Root) Readlink(name string) (string, error)
    func (r *Root) Remove(name string) error
    func (r *Root) RemoveAll(name string) error
    func (r *Root) Rename(oldname, newname string) error
    func (r *Root) Stat(name string) (FileInfo, error)
    func (r *Root) Symlink(oldname, newname string) error
    func (r *Root) WriteFile(name string, data []byte, perm FileMode) error
    func (r *Root) logOpen(name string)
    func (r *Root) logStat(name string)
type Signal
type SyscallError
    func (e *SyscallError) Error() string
    func (e *SyscallError) Timeout() bool
    func (e *SyscallError) Unwrap() error
type dirFS
    func (dir dirFS) Lstat(name string) (fs.FileInfo, error)
    func (dir dirFS) Open(name string) (fs.File, error)
    func (dir dirFS) ReadDir(name string) ([]DirEntry, error)
    func (dir dirFS) ReadFile(name string) ([]byte, error)
    func (dir dirFS) ReadLink(name string) (string, error)
    func (dir dirFS) Stat(name string) (fs.FileInfo, error)
    func (dir dirFS) join(name string) (string, error)
type dirInfo
    func (d *dirInfo) close()
type errSymlink
    func (errSymlink) Error() string
type file
    func (file *file) close() error
type fileStat
    func (fs *fileStat) IsDir() bool
    func (fs *fileStat) ModTime() time.Time
    func (fs *fileStat) Mode() FileMode
    func (fs *fileStat) Name() string
    func (fs *fileStat) Size() int64
    func (fs *fileStat) Sys() any
type fileWithoutReadFrom
    func (file fileWithoutReadFrom) close() error
type fileWithoutWriteTo
    func (file fileWithoutWriteTo) close() error
type newFileKind
type noReadFrom
    func (noReadFrom) ReadFrom(io.Reader) (int64, error)
type noWriteTo
    func (noWriteTo) WriteTo(io.Writer) (int64, error)
type processHandle
    func (ph *processHandle) acquire() (uintptr, bool)
    func (ph *processHandle) closeHandle()
    func (ph *processHandle) release()
type processStatus
type rawConn
    func newRawConn(file *File) (*rawConn, error)
    func (c *rawConn) Control(f func(uintptr)) error
    func (c *rawConn) Read(f func(uintptr) bool) error
    func (c *rawConn) Write(f func(uintptr) bool) error
type readdirMode
type root
    func (r *root) Close() error
    func (r *root) Name() string
    func (r *root) decref()
    func (r *root) incref() error
type rootFS
    func (rfs *rootFS) Lstat(name string) (FileInfo, error)
    func (rfs *rootFS) Open(name string) (fs.File, error)
    func (rfs *rootFS) ReadDir(name string) ([]DirEntry, error)
    func (rfs *rootFS) ReadFile(name string) ([]byte, error)
    func (rfs *rootFS) ReadLink(name string) (string, error)
    func (rfs *rootFS) Stat(name string) (FileInfo, error)
type syscallErrorType
type sysfdType
type timeout
type unixDirent
    func (d *unixDirent) Info() (FileInfo, error)
    func (d *unixDirent) IsDir() bool
    func (d *unixDirent) Name() string
    func (d *unixDirent) String() string
    func (d *unixDirent) Type() FileMode

Package files

dir.go dir_unix.go dirent_linux.go eloop_other.go env.go error.go error_errno.go exec.go exec_linux.go exec_posix.go exec_unix.go executable.go executable_procfs.go file.go file_open_unix.go file_posix.go file_unix.go getwd.go path.go path_unix.go pidfd_linux.go pipe2_unix.go proc.go rawconn.go removeall_at.go removeall_unix.go root.go root_nonwindows.go root_openat.go root_unix.go stat.go stat_linux.go stat_unix.go statat.go statat_unix.go sticky_notbsd.go sys.go sys_linux.go sys_unix.go tempfile.go types.go types_unix.go wait_waitid.go zero_copy_linux.go zero_copy_posix.go

Constants

const (
    errENOSYS = syscall.ENOSYS
    errERANGE = syscall.ERANGE
    errENOMEM = syscall.ENOMEM
)
const (
    // Special values for Process.Pid.
    pidUnset    = 0
    pidReleased = -1
)

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

const (
    // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    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.
    // The remaining values may be or'ed in to control behavior.
    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  // truncate regular writable file when opened.
)

Seek whence values.

Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.

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
)

Flags for doInRoot.

const (
    // doInRootNoHandleTerminalSlash prevents doInRoot from applying special handling
    // for paths which end in one or more slashes.
    doInRootNoHandleTerminalSlash = 1 << iota

    // doInRootCreatingDirectory indicates that the operation is creating a directory.
    // When a path ends in /, the last path component may name a file which does not exist.
    doInRootCreatingDirectory

    // doInRootAlwaysResolveTerminalSlash causes doInRoot to resolve symlinks in the last
    // path component when a path ends in /, even on Windows. For example, this causes
    // doInRoot to resolve "symlink/" as the link target of "symlink".
    //
    // POSIX path operations resolve symlinks in this case.
    // Most Windows operations do not.
    // This flag enforces the POSIX behavior.
    doInRootAlwaysResolveTerminalSlash
)

The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

const (
    // The single letters are the abbreviations
    // used by the String method's formatting.
    ModeDir        = fs.ModeDir        // d: is a directory
    ModeAppend     = fs.ModeAppend     // a: append-only
    ModeExclusive  = fs.ModeExclusive  // l: exclusive use
    ModeTemporary  = fs.ModeTemporary  // T: temporary file; Plan 9 only
    ModeSymlink    = fs.ModeSymlink    // L: symbolic link
    ModeDevice     = fs.ModeDevice     // D: device file
    ModeNamedPipe  = fs.ModeNamedPipe  // p: named pipe (FIFO)
    ModeSocket     = fs.ModeSocket     // S: Unix domain socket
    ModeSetuid     = fs.ModeSetuid     // u: setuid
    ModeSetgid     = fs.ModeSetgid     // g: setgid
    ModeCharDevice = fs.ModeCharDevice // c: Unix character device, when ModeDevice is set
    ModeSticky     = fs.ModeSticky     // t: sticky
    ModeIrregular  = fs.ModeIrregular  // ?: non-regular file; nothing else is known about this file

    // Mask for the type bits. For regular files, none will be set.
    ModeType = fs.ModeType

    ModePerm = fs.ModePerm // Unix permission bits, 0o777
)

DevNull is the name of the operating system's “null device.” On Unix-like systems, it is "/dev/null"; on Windows, "NUL".

const DevNull = "/dev/null"
const _UTIME_OMIT = unix.UTIME_OMIT
const (
    // More than 5760 to work around https://golang.org/issue/24015.
    blockSize = 8192
)
const (
    // Maximum number of symbolic links we will follow when resolving a file in a root.
    // 8 is __POSIX_SYMLOOP_MAX (the minimum allowed value for SYMLOOP_MAX),
    // and a common limit.
    rootMaxSymlinks = 8
)

supportsCloseOnExec reports whether the platform supports the O_CLOEXEC flag. On Darwin, the O_CLOEXEC flag was introduced in OS X 10.7 (Darwin 11.0.0). See https://support.apple.com/kb/HT1633. On FreeBSD, the O_CLOEXEC flag was introduced in version 8.3.

const supportsCloseOnExec = true
const supportsCreateWithStickyBit = true

Variables

Portable analogs of some common system call errors.

Errors returned from this package may be tested against these errors with errors.Is.

var (
    // ErrInvalid indicates an invalid argument.
    // Methods on File will return this error when the receiver is nil.
    ErrInvalid = fs.ErrInvalid // "invalid argument"

    ErrPermission = fs.ErrPermission // "permission denied"
    ErrExist      = fs.ErrExist      // "file already exists"
    ErrNotExist   = fs.ErrNotExist   // "file does not exist"
    ErrClosed     = fs.ErrClosed     // "file already closed"

    ErrNoDeadline       = errNoDeadline()       // "file type does not support deadline"
    ErrDeadlineExceeded = errDeadlineExceeded() // "i/o timeout"
)
var (
    // ErrProcessDone indicates a [Process] has finished.
    ErrProcessDone = errors.New("os: process already finished")
    // errProcessReleased indicates a [Process] has been released.
    errProcessReleased = errors.New("os: process already released")
    // ErrNoHandle indicates a [Process] does not have a handle.
    ErrNoHandle = errors.New("os: process handle unavailable")
)

Stdin, Stdout, and Stderr are open Files pointing to the standard input, standard output, and standard error file descriptors.

Note that the Go runtime writes to standard error for panics and crashes; closing Stderr may cause those messages to go elsewhere, perhaps to a file opened later.

var (
    Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
)
var (
    pollCopyFileRange = poll.CopyFileRange
    pollSplice        = poll.Splice
)

Args hold the command-line arguments, starting with the program name.

var Args []string
var _ fs.StatFS = dirFS("")
var _ fs.ReadFileFS = dirFS("")
var _ fs.ReadDirFS = dirFS("")
var _ fs.ReadLinkFS = dirFS("")

checkPidfdOnce is used to only check whether pidfd works once.

var checkPidfdOnce = sync.OnceValue(checkPidfd)

checkWrapErr is the test hook to enable checking unexpected wrapped errors of poll.ErrFileClosing. It is set to true in the export_test.go for tests (including fuzz tests).

var checkWrapErr = false
var dirBufPool = sync.Pool{
    New: func() any {

        buf := make([]byte, blockSize)
        return &buf
    },
}
var errPathEscapes = errors.New("path escapes from parent")
var errPatternHasSeparator = errors.New("pattern contains path separator")
var errWriteAtInAppendMode = errors.New("os: invalid use of WriteAt on file opened with O_APPEND")
var getwdCache struct {
    sync.Mutex
    dir string
}

stathook is set in tests

var stathook func(f *File, name string) (FileInfo, error)

func Chdir

func Chdir(dir string) error

Chdir changes the current working directory to the named directory. If there is an error, it will be of type *PathError.

func Chmod

func Chmod(name string, mode FileMode) error

Chmod changes the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target. If there is an error, it will be of type *PathError.

A different subset of the mode bits are used, depending on the operating system.

On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and ModeSticky are used.

On Windows, only the 0o200 bit (owner writable) of mode is used; it controls whether the file's read-only attribute is set or cleared. The other bits are currently unused. For compatibility with Go 1.12 and earlier, use a non-zero mode. Use mode 0o400 for a read-only file and 0o600 for a readable+writable file.

On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive, and ModeTemporary are used.

Example

func Chown

func Chown(name string, uid, gid int) error

Chown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link's target. A uid or gid of -1 means to not change that value. If there is an error, it will be of type *PathError.

On Windows or Plan 9, Chown always returns the syscall.EWINDOWS or syscall.EPLAN9 error, wrapped in *PathError.

func Chtimes

func Chtimes(name string, atime time.Time, mtime time.Time) error

Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions. A zero time.Time value will leave the corresponding file time unchanged.

The underlying filesystem may truncate or round the values to a less precise time unit. If there is an error, it will be of type *PathError.

Example

func Clearenv

func Clearenv()

Clearenv deletes all environment variables.

func CopyFS 1.23

func CopyFS(dir string, fsys fs.FS) error

CopyFS copies the file system fsys into the directory dir, creating dir if necessary.

Files are created with mode 0o666 plus any execute permissions from the source, and directories are created with mode 0o777 (before umask).

CopyFS will not overwrite existing files. If a file name in fsys already exists in the destination, CopyFS will return an error such that errors.Is(err, fs.ErrExist) will be true.

Symbolic links in dir are followed.

New files added to fsys (including if dir is a subdirectory of fsys) while CopyFS is running are not guaranteed to be copied.

Copying stops at and returns the first error encountered.

func DirFS 1.16

func DirFS(dir string) fs.FS

DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.

Note that DirFS("/prefix") only guarantees that the Open calls it makes to the operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside the /prefix tree, then using DirFS does not stop the access any more than using os.Open does. Additionally, the root of the fs.FS returned for a relative path, DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not a general substitute for a chroot-style security mechanism when the directory tree contains arbitrary content.

Use Root.FS to obtain a fs.FS that prevents escapes from the tree via symbolic links.

The directory dir must not be "".

The result implements io/fs.StatFS, io/fs.ReadFileFS, io/fs.ReadDirFS, and io/fs.ReadLinkFS.

func Environ

func Environ() []string

Environ returns a copy of strings representing the environment, in the form "key=value".

func Executable 1.8

func Executable() (string, error)

Executable returns the path name for the executable that started the current process. There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, path/filepath.EvalSymlinks might help.

Executable returns an absolute path unless an error occurred.

The main use case is finding resources located relative to an executable.

func Exit

func Exit(code int)

Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.

For portability, the status code should be in the range [0, 125].

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

Example

Good morning, Gopher!

func ExpandEnv

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.

Example

gopher lives in /usr/gopher.

func Getegid

func Getegid() int

Getegid returns the numeric effective group id of the caller.

On Windows, it returns -1.

func Getenv

func Getenv(key string) string

Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present. To distinguish between an empty value and an unset value, use LookupEnv.

Example

gopher lives in /usr/gopher.

func Geteuid

func Geteuid() int

Geteuid returns the numeric effective user id of the caller.

On Windows, it returns -1.

func Getgid

func Getgid() int

Getgid returns the numeric group id of the caller.

On Windows, it returns -1.

func Getgroups

func Getgroups() ([]int, error)

Getgroups returns a list of the numeric ids of groups that the caller belongs to.

On Windows, it returns syscall.EWINDOWS. See the os/user package for a possible alternative.

func Getpagesize

func Getpagesize() int

Getpagesize returns the underlying system's memory page size.

func Getpid

func Getpid() int

Getpid returns the process id of the caller.

func Getppid

func Getppid() int

Getppid returns the process id of the caller's parent.

func Getuid

func Getuid() int

Getuid returns the numeric user id of the caller.

On Windows, it returns -1.

func Getwd

func Getwd() (dir string, err error)

Getwd returns an absolute path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.

On Unix platforms, if the environment variable PWD provides an absolute name, and it is a name of the current directory, it is returned.

func Hostname

func Hostname() (name string, err error)

Hostname returns the host name reported by the kernel.

func IsExist

func IsExist(err error) bool

IsExist returns a boolean indicating whether its argument is known to report that a file or directory already exists. It is satisfied by ErrExist as well as some syscall errors.

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrExist).

func IsNotExist

func IsNotExist(err error) bool

IsNotExist returns a boolean indicating whether its argument is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrNotExist).

func IsPathSeparator

func IsPathSeparator(c uint8) bool

IsPathSeparator reports whether c is a directory separator character.

func IsPermission

func IsPermission(err error) bool

IsPermission returns a boolean indicating whether its argument is known to report that permission is denied. It is satisfied by ErrPermission as well as some syscall errors.

This function predates errors.Is. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrPermission).

func IsTimeout 1.10

func IsTimeout(err error) bool

IsTimeout returns a boolean indicating whether its argument is known to report that a timeout occurred.

This function predates errors.Is, and the notion of whether an error indicates a timeout can be ambiguous. For example, the Unix error EWOULDBLOCK sometimes indicates a timeout and sometimes does not. New code should use errors.Is with a value appropriate to the call returning the error, such as os.ErrDeadlineExceeded.

func Lchown

func Lchown(name string, uid, gid int) error

Lchown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link itself. If there is an error, it will be of type *PathError.

On Windows, it always returns the syscall.EWINDOWS error, wrapped in *PathError.

func Link(oldname, newname string) error

Link creates newname as a hard link to the oldname file. If there is an error, it will be of type *LinkError.

func LookupEnv 1.5

func LookupEnv(key string) (string, bool)

LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.

Example

SOME_KEY=value
EMPTY_KEY=
MISSING_KEY not set

func Mkdir

func Mkdir(name string, perm FileMode) error

Mkdir creates a new directory with the specified name and permission bits (before umask). If there is an error, it will be of type *PathError.

Example

func MkdirAll

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Example

func MkdirTemp 1.16

func MkdirTemp(dir, pattern string) (string, error)

MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory. The new directory's name is generated by adding a random string to the end of pattern. If pattern includes a "*", the random string replaces the last "*" instead. The directory is created with mode 0o700 (before umask). If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling MkdirTemp simultaneously will not choose the same directory. It is the caller's responsibility to remove the directory when it is no longer needed.

Example

Example (Suffix)

func NewSyscallError

func NewSyscallError(syscall string, err error) error

NewSyscallError returns, as an error, a new SyscallError with the given system call name and error details. As a convenience, if err is nil, NewSyscallError returns nil.

func Pipe

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 ReadFile 1.16

func ReadFile(name string) ([]byte, error)

ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported. If there is an error, it will be of type *PathError.

Example

Hello, Gophers!
func Readlink(name string) (string, error)

Readlink returns the destination of the named symbolic link. If there is an error, it will be of type *PathError.

If the link destination is relative, Readlink returns the relative path without resolving it to an absolute one.

func Remove

func Remove(name string) error

Remove removes the named file or (empty) directory. If there is an error, it will be of type *PathError.

func RemoveAll

func RemoveAll(path string) error

RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error). If there is an error, it will be of type *PathError.

func Rename

func Rename(oldpath, newpath string) error

Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. If newpath already exists and is a directory, Rename returns an error. OS-specific restrictions may apply when oldpath and newpath are in different directories. Even within the same directory, on non-Unix platforms Rename is not an atomic operation. If there is an error, it will be of type *LinkError.

func SameFile

func SameFile(fi1, fi2 FileInfo) bool

SameFile reports whether fi1 and fi2 describe the same file. For example, on Unix this means that the device and inode fields of the two underlying structures are identical; on other systems the decision may be based on the path names. SameFile only applies to results returned by this package's Stat. It returns false in other cases.

func Setenv

func Setenv(key, value string) error

Setenv sets the value of the environment variable named by the key. It returns an error, if any.

func Symlink(oldname, newname string) error

Symlink creates newname as a symbolic link to oldname. On Windows, a symlink to a non-existent oldname creates a file symlink; if oldname is later created as a directory the symlink will not work. If there is an error, it will be of type *LinkError.

func TempDir

func TempDir() string

TempDir returns the default directory to use for temporary files.

On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.

The directory is neither guaranteed to exist nor have accessible permissions.

func Truncate

func Truncate(name string, size int64) error

Truncate changes the size of the named file. If the file is a symbolic link, it changes the size of the link's target. If there is an error, it will be of type *PathError.

func Unsetenv 1.4

func Unsetenv(key string) error

Unsetenv unsets a single environment variable.

Example

func UserCacheDir 1.11

func UserCacheDir() (string, error)

UserCacheDir returns the default root directory to use for user-specific cached data. Users should create their own application-specific subdirectory within this one and use that.

On Unix systems, it returns $XDG_CACHE_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.cache. On Darwin, it returns $HOME/Library/Caches. On Windows, it returns %LocalAppData%. On Plan 9, it returns $home/lib/cache.

If the location cannot be determined (for example, $HOME is not defined) or the path in $XDG_CACHE_HOME is relative, then it will return an error.

Example

func UserConfigDir 1.13

func UserConfigDir() (string, error)

UserConfigDir returns the default root directory to use for user-specific configuration data. Users should create their own application-specific subdirectory within this one and use that.

On Unix systems, it returns $XDG_CONFIG_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.config. On Darwin, it returns $HOME/Library/Application Support. On Windows, it returns %AppData%. On Plan 9, it returns $home/lib.

If the location cannot be determined (for example, $HOME is not defined) or the path in $XDG_CONFIG_HOME is relative, then it will return an error.

Example

func UserHomeDir 1.12

func UserHomeDir() (string, error)

UserHomeDir returns the current user's home directory.

On Unix, including macOS, it returns the $HOME environment variable. On Windows, it returns %USERPROFILE%. On Plan 9, it returns the $home environment variable.

If the expected variable is not set in the environment, UserHomeDir returns either a platform-specific default value or a non-nil error.

func WriteFile 1.16

func WriteFile(name string, data []byte, perm FileMode) error

WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions. Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state.

Example

func afterResolvingSymlink(parent int, name string, f func() error) error

On systems which use fchmodat, fchownat, etc., we have a race condition: When "name" is a symlink, Root.Chmod("name") should act on the target of that link. However, fchmodat doesn't allow us to chmod a file only if it is not a symlink; the AT_SYMLINK_NOFOLLOW parameter causes the operation to act on the symlink itself.

We do the best we can by first checking to see if the target of the operation is a symlink, and only attempting the fchmodat if it is not. If the target is replaced between the check and the fchmodat, we will chmod the symlink rather than following it.

This race condition is unfortunate, but does not permit escaping a root: We may act on the wrong file, but that file will be contained within the root.

func atime

func atime(fi FileInfo) time.Time

For testing.

func checkClonePidfd

func checkClonePidfd() error

Provided by syscall.

func checkPidfd

func checkPidfd() error

checkPidfd checks whether all required pidfd-related syscalls work. This consists of pidfd_open and pidfd_send_signal syscalls, waitid syscall with idtype of P_PIDFD, and clone(CLONE_PIDFD).

Reasons for non-working pidfd syscalls include an older kernel and an execution environment in which the above system calls are restricted by seccomp or a similar technology.

func checkSymlink(parent int, name string, origError error) error

checkSymlink resolves the symlink name in parent, and returns errSymlink with the link contents.

If name is not a symlink, return origError.

func chmod

func chmod(name string, mode FileMode) error

See docs in file.go:Chmod.

func chmodat

func chmodat(parent int, name string, mode FileMode) error

func chownat

func chownat(parent int, name string, uid, gid int) error

func chtimesUtimes

func chtimesUtimes(atime, mtime time.Time) [2]syscall.Timespec

func chtimesat

func chtimesat(parent int, name string, atime time.Time, mtime time.Time) error

func convertESRCH

func convertESRCH(err error) error

func direntIno

func direntIno(buf []byte) (uint64, bool)

func direntNamlen

func direntNamlen(buf []byte) (uint64, bool)

func direntReclen

func direntReclen(buf []byte) (uint64, bool)

func doInRoot

func doInRoot[T any](r *Root, name string, flags uint, openDirFunc func(parent sysfdType, name string) (sysfdType, error), f func(parent sysfdType, name string, endsInSlash bool) (T, error)) (ret T, err error)

doInRoot performs an operation on a path in a Root.

It calls f with the FD or handle for the directory containing the last path element, the name of the last path element (not including slashes), and a boolean indicating whether the original path ended in one or more slashes.

For example, given the path a/b/c it calls f with the FD for a/b and the name "c".

It applies special handling for paths ending in a slash: When a path ends in a slash (for example "a/b/"), doInRoot will check the final component ("b") before calling f. If the final component is a symlink, doInRoot will resolve it. If the final component is neither a symlink nor a directory, doInRoot will return ENOTDIR. This behavior may be disabled by passing the doInRootNoHandleTerminalSlash flag.

If openDirFunc is non-nil, it is called to open intermediate path elements. For example, given the path a/b/c openDirFunc will be called to open a and a/b in turn.

f or openDirFunc may return errSymlink to indicate that the path element is a symlink which should be followed. Note that this can result in f being called multiple times with different names. For example, given the path "link" which is a symlink to "target", f is called with the path "link", returns errSymlink("target"), and is called again with the path "target".

If f or openDirFunc return a *PathError, doInRoot will set PathError.Path to the full path which caused the error.

func endsWithDot

func endsWithDot(path string) bool

endsWithDot reports whether the final component of path is ".".

func ensurePidfd

func ensurePidfd(sysAttr *syscall.SysProcAttr) (*syscall.SysProcAttr, bool)

ensurePidfd initializes the PidFD field in sysAttr if it is not already set. It returns the original or modified SysProcAttr struct and a flag indicating whether the PidFD should be duplicated before using.

func epipecheck

func epipecheck(file *File, e error)

epipecheck raises SIGPIPE if we get an EPIPE error on standard output or standard error. See the SIGPIPE docs in os/signal, and issue 11845.

func errDeadlineExceeded

func errDeadlineExceeded() error

errDeadlineExceeded returns the value for os.ErrDeadlineExceeded. This error comes from the internal/poll package, which is also used by package net. Doing it this way ensures that the net package will return os.ErrDeadlineExceeded for an exceeded deadline, as documented by net.Conn.SetDeadline, without requiring any extra work in the net package and without requiring the internal/poll package to import os (which it can't, because that would be circular).

func errNoDeadline

func errNoDeadline() error

func executable

func executable() (string, error)

func fillFileStatFromSys

func fillFileStatFromSys(fs *fileStat, name string)

func fixCount

func fixCount(n int, err error) (int, error)

Many functions in package syscall return a count of -1 instead of 0. Using fixCount(call()) instead of call() corrects the count.

func fixLongPath

func fixLongPath(path string) string

fixLongPath is a noop on non-Windows platforms.

func genericReadFrom

func genericReadFrom(f *File, r io.Reader) (int64, error)

func genericWriteTo

func genericWriteTo(f *File, w io.Writer) (int64, error)

func getPidfd

func getPidfd(sysAttr *syscall.SysProcAttr, needDup bool) (uintptr, bool)

getPidfd returns the value of sysAttr.PidFD (or its duplicate if needDup is set) and a flag indicating whether the value can be used.

func getPollFDAndNetwork

func getPollFDAndNetwork(i any) (*poll.FD, poll.String)

getPollFDAndNetwork tries to get the poll.FD and network type from the given interface by expecting the underlying type of i to be the implementation of syscall.Conn that contains a *net.rawConn.

func getShellName

func getShellName(s string) (string, int)

getShellName returns the name that begins the string and the number of bytes consumed to extract it. If the name is enclosed in {}, it's part of a ${} expansion and two more bytes are needed than the length of the name.

func hostname

func hostname() (name string, err error)

func ignoreSIGSYS

func ignoreSIGSYS()

Provided by runtime.

func ignoringEINTR

func ignoringEINTR(fn func() error) error

ignoringEINTR makes a function call and repeats it if it returns an EINTR error. This appears to be required even though we install all signal handlers with SA_RESTART: see #22838, #38033, #38836, #40846. Also #20400 and #36644 are issues in which a signal handler is installed without setting SA_RESTART. None of these are the common case, but there are enough of them that it seems that we can't avoid an EINTR loop.

func ignoringEINTR2

func ignoringEINTR2[T any](fn func() (T, error)) (T, error)

ignoringEINTR2 is ignoringEINTR, but returning an additional value.

func init

func init()

func isAlphaNum

func isAlphaNum(c uint8) bool

isAlphaNum reports whether the byte is an ASCII letter, number, or underscore.

func isDirectoryLink(fi FileInfo) bool

isDirectoryLink always returns false, because Unix systems don't have separate symlink types for files and directories. (See the Windows version of this function for more details.)

func isNoFollowErr

func isNoFollowErr(err error) bool

isNoFollowErr reports whether err may result from O_NOFOLLOW blocking an open operation.

func isShellSpecialVar

func isShellSpecialVar(c uint8) bool

isShellSpecialVar reports whether the character identifies a special shell variable such as $*.

func isUnixOrTCP

func isUnixOrTCP(network string) bool

func isValidRootFSPath

func isValidRootFSPath(name string) bool

isValidRootFSPath reports whether name is a valid filename to pass a Root.FS method.

func joinPath

func joinPath(dir, name string) string

func lchownat

func lchownat(parent int, name string, uid, gid int) error

func linkat

func linkat(oldfd int, oldname string, newfd int, newname string) error

func mkdirat

func mkdirat(fd int, name string, perm FileMode) error

func nextRandom

func nextRandom() string

func open

func open(path string, flag int, perm uint32) (int, poll.SysFile, error)

func pidfdFind

func pidfdFind(pid int) (uintptr, error)

pidfdFind returns the process handle for pid.

func pidfdWorks

func pidfdWorks() bool

pidfdWorks returns whether we can use pidfd on this system.

func prefixAndSuffix

func prefixAndSuffix(pattern string) (prefix, suffix string, err error)

prefixAndSuffix splits pattern by the last wildcard "*", if applicable, returning prefix as the part before "*" and suffix as the part after "*".

func readFileContents

func readFileContents(statSize int64, read func([]byte) (int, error)) ([]byte, error)

readFileContents reads the contents of a file using the provided read function (*os.File.Read, except in tests) one or more times, until an error is seen.

The provided size is the stat size of the file, which might be 0 for a /proc-like file that doesn't report a size.

func readInt

func readInt(b []byte, off, size uintptr) (u uint64, ok bool)

readInt returns the size-bytes unsigned integer in native byte order at offset off.

func readIntBE

func readIntBE(b []byte, size uintptr) uint64

func readIntLE

func readIntLE(b []byte, size uintptr) uint64
func readlink(name string) (string, error)

func readlinkat

func readlinkat(fd int, name string) (string, error)

func removeAll

func removeAll(path string) error

func removeAllFrom

func removeAllFrom(parentFd sysfdType, base string) error

func removeat

func removeat(fd int, name string) error

func removedirat

func removedirat(fd int, name string) error

func removefileat

func removefileat(fd int, name string) error

func rename

func rename(oldname, newname string) error

func renameat

func renameat(oldfd int, oldname string, newfd int, newname string) error

func restoreSIGSYS

func restoreSIGSYS()

func rootChmod

func rootChmod(r *Root, name string, mode FileMode) error

func rootChown

func rootChown(r *Root, name string, uid, gid int) error

func rootChtimes

func rootChtimes(r *Root, name string, atime time.Time, mtime time.Time) error

func rootCleanPath

func rootCleanPath(s string, prefix, suffix []string) (string, error)

func rootLchown

func rootLchown(r *Root, name string, uid, gid int) error
func rootLink(r *Root, oldname, newname string) error

func rootMkdir

func rootMkdir(r *Root, name string, perm FileMode) error

func rootMkdirAll

func rootMkdirAll(r *Root, fullname string, perm FileMode) error

func rootOpenDir

func rootOpenDir(parent int, name string) (int, error)
func rootReadlink(r *Root, name string) (string, error)

func rootRemove

func rootRemove(r *Root, name string) error

func rootRemoveAll

func rootRemoveAll(r *Root, name string) error

func rootRename

func rootRename(r *Root, oldname, newname string) error
func rootSymlink(r *Root, oldname, newname string) error

func runtime_args

func runtime_args() []string

func runtime_beforeExit

func runtime_beforeExit(exitCode int)

func runtime_rand

func runtime_rand() uint64

random number source provided by runtime. We generate random temporary file names so that there's a good chance the file doesn't exist yet - keeps the number of tries in TempFile to a minimum.

func sameFile

func sameFile(fs1, fs2 *fileStat) bool

func setStickyBit

func setStickyBit(name string) error

setStickyBit adds ModeSticky to the permission bits of path, non atomic.

func sigpipe

func sigpipe()

func splitPath

func splitPath(path string) (string, string)

splitPath returns the base name and parent directory.

func splitPathInRoot

func splitPathInRoot(s string, prefix, suffix []string) (_ []string, endsInSlash bool, err error)

splitPathInRoot splits a path into components and joins it with the given prefix and suffix.

The path is relative to a Root, and must not be absolute, volume-relative, or "".

"." components are removed, except in the last component.

endsInSlash reports whether the path ends in one or more slashes.

func statOrZero

func statOrZero(f *File) int64

func symlinkat

func symlinkat(oldname string, newfd int, newname string) error

func syscallMode

func syscallMode(i FileMode) (o uint32)

syscallMode returns the syscall-specific mode bits from Go's portable mode bits.

func tempDir

func tempDir() string

func tryLimitedReader

func tryLimitedReader(r io.Reader) (*io.LimitedReader, io.Reader, int64)

tryLimitedReader tries to assert the io.Reader to io.LimitedReader, it returns the io.LimitedReader, the underlying io.Reader and the remaining amount of bytes if the assertion succeeds, otherwise it just returns the original io.Reader and the theoretical unlimited remaining amount of bytes.

func underlyingError

func underlyingError(err error) error

underlyingError returns the underlying error for known os error types.

func underlyingErrorIs

func underlyingErrorIs(err, target error) bool

func wrapSyscallError

func wrapSyscallError(name string, err error) error

wrapSyscallError takes an error and a syscall name. If the error is a syscall.Errno, it wraps it in an os.SyscallError using the syscall name.

type DirEntry 1.16

A DirEntry is an entry read from a directory (using the ReadDir function or a File.ReadDir method).

type DirEntry = fs.DirEntry

func ReadDir 1.16

func ReadDir(name string) ([]DirEntry, error)

ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, ReadDir returns the entries it was able to read before the error, along with the error.

Example

func newUnixDirent

func newUnixDirent(parent *File, name string, typ FileMode) (DirEntry, error)

type File

File represents an open file descriptor.

The methods of File are safe for concurrent use.

type File struct {
    *file // os specific
}

func Create

func Create(name string) (*File, error)

Create creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0o666 (before umask). If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. The directory containing the file must already exist. If there is an error, it will be of type *PathError.

func CreateTemp 1.16

func CreateTemp(dir, pattern string) (*File, error)

CreateTemp creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". The file is created with mode 0o600 (before umask). If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file. The caller can use the file's Name method to find the pathname of the file. It is the caller's responsibility to remove the file when it is no longer needed.

Example

Example (Suffix)

func NewFile

func NewFile(fd uintptr, name string) *File

NewFile returns a new File with the given file descriptor and name. The returned value will be nil if fd is not a valid file descriptor.

NewFile's behavior differs on some platforms:

Only pollable files support File.SetDeadline, File.SetReadDeadline, and File.SetWriteDeadline.

After passing it to NewFile, fd may become invalid under the same conditions described in the comments of File.Fd, and the same constraints apply.

func Open

func Open(name string) (*File, error)

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError.

func OpenFile

func OpenFile(name string, flag int, perm FileMode) (*File, error)

OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag is passed, it is created with mode perm (before umask); the containing directory must exist. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

Example

Example (Append)

func OpenInRoot 1.24

func OpenInRoot(dir, name string) (*File, error)

OpenInRoot opens the file name in the directory dir. It is equivalent to OpenRoot(dir) followed by opening the file in the root.

OpenInRoot returns an error if any component of the name references a location outside of dir.

See Root for details and limitations.

func net_newUnixFile

func net_newUnixFile(fd int, name string) *File

net_newUnixFile is a hidden entry point called by net.conn.File. This is used so that a nonblocking network connection will become blocking if code calls the Fd method. We don't want that for direct calls to NewFile: passing a nonblocking descriptor to NewFile should remain nonblocking if you get it back using Fd. But for net.conn.File the call to NewFile is hidden from the user. Historically in that case the Fd method has returned a blocking descriptor, and we want to retain that behavior because existing code expects it and depends on it.

func newDirFile

func newDirFile(fd int, name string) (*File, error)

func newFile

func newFile(fd int, name string, kind newFileKind, nonBlocking bool) *File

newFile is like NewFile, but if called from OpenFile or Pipe (as passed in the kind parameter) it tries to add the file to the runtime poller.

func newFileFromNewFile

func newFileFromNewFile(fd uintptr, name string) *File

newFileFromNewFile is called by NewFile.

func openDir

func openDir(name string) (*File, error)

openDir opens a file which is assumed to be a directory. As such, it skips the syscalls that make the file descriptor non-blocking as these take time and will fail on file descriptors for directories.

func openDirAt

func openDirAt(dirfd sysfdType, name string) (*File, error)

openDirAt opens a directory name relative to the directory referred to by the file descriptor dirfd. If name is anything but a directory (this includes a symlink to one), it should return an error. Other than that this should act like openFileNolog.

This acts like openFileNolog rather than OpenFile because we are going to (try to) remove the file. The contents of this file are not relevant for test caching.

func openDirNolog

func openDirNolog(name string) (*File, error)

func openFileNolog

func openFileNolog(name string, flag int, perm FileMode) (*File, error)

openFileNolog is the Unix implementation of OpenFile. Changes here should be reflected in openDirAt and openDirNolog, if relevant.

func rootOpenFileNolog

func rootOpenFileNolog(root *Root, name string, flag int, perm FileMode) (*File, error)

rootOpenFileNolog is Root.OpenFile.

func (*File) Chdir

func (f *File) Chdir() error

Chdir changes the current working directory to the file, which must be a directory. If there is an error, it will be of type *PathError.

func (*File) Chmod

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 (*File) Chown

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.

On Windows, it always returns the syscall.EWINDOWS error, wrapped in *PathError.

func (*File) Close

func (f *File) Close() error

Close closes the File, rendering it unusable for I/O. On files that support File.SetDeadline, any pending I/O operations will be canceled and return immediately with an ErrClosed error. Close will return an error if it has already been called.

func (*File) Fd

func (f *File) Fd() uintptr

Fd returns the system file descriptor or handle referencing the open file. If f is closed, the descriptor becomes invalid. If f is garbage collected, a finalizer may close the descriptor, making it invalid; see runtime.SetFinalizer for more information on when a finalizer might be run.

Do not close the returned descriptor; that could cause a later close of f to close an unrelated descriptor.

Fd's behavior differs on some platforms:

For most uses prefer the f.SyscallConn method.

func (*File) Name

func (f *File) Name() string

Name returns the name of the file as presented to Open.

It is safe to call Name after [Close].

func (*File) Read

func (f *File) Read(b []byte) (n int, err error)

Read reads up to len(b) bytes from the File and stores them in b. It returns the number of bytes read and any error encountered. At end of file, Read returns 0, io.EOF.

func (*File) ReadAt

func (f *File) ReadAt(b []byte, off int64) (n int, err error)

ReadAt reads len(b) bytes from the File starting at byte offset off. It returns the number of bytes read and the error, if any. ReadAt always returns a non-nil error when n < len(b). At end of file, that error is io.EOF.

func (*File) ReadDir 1.16

func (f *File) ReadDir(n int) ([]DirEntry, error)

ReadDir reads the contents of the directory associated with the file f and returns a slice of DirEntry values in directory order. Subsequent calls on the same file will yield later DirEntry records in the directory.

If n > 0, ReadDir returns at most n DirEntry records. In this case, if ReadDir returns an empty slice, it will return an error explaining why. At the end of a directory, the error is io.EOF.

If n <= 0, ReadDir returns all the DirEntry records remaining in the directory. When it succeeds, it returns a nil error (not io.EOF).

func (*File) ReadFrom 1.15

func (f *File) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReaderFrom.

func (*File) Readdir

func (f *File) Readdir(n int) ([]FileInfo, error)

Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.

If n > 0, Readdir returns at most n FileInfo structures. In this case, if Readdir returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

If n <= 0, Readdir returns all the FileInfo from the directory in a single slice. In this case, if Readdir succeeds (reads all the way to the end of the directory), it returns the slice and a nil error. If it encounters an error before the end of the directory, Readdir returns the FileInfo read until that point and a non-nil error.

Most clients are better served by the more efficient ReadDir method.

func (*File) Readdirnames

func (f *File) Readdirnames(n int) (names []string, err error)

Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names.

If n > 0, Readdirnames returns at most n names. In this case, if Readdirnames returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

If n <= 0, Readdirnames returns all the names from the directory in a single slice. In this case, if Readdirnames succeeds (reads all the way to the end of the directory), it returns the slice and a nil error. If it encounters an error before the end of the directory, Readdirnames returns the names read until that point and a non-nil error.

func (*File) Seek

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. The behavior of Seek on a file opened with O_APPEND is not specified.

func (*File) SetDeadline 1.10

func (f *File) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines for a File. It is equivalent to calling both SetReadDeadline and SetWriteDeadline.

Only some kinds of files support setting a deadline. Calls to SetDeadline for files that do not support deadlines will return ErrNoDeadline. On most systems ordinary files do not support deadlines, but pipes do.

A deadline is an absolute time after which I/O operations fail with an error instead of blocking. The deadline applies to all future and pending I/O, not just the immediately following call to Read or Write. After a deadline has been exceeded, the connection can be refreshed by setting a deadline in the future.

If the deadline is exceeded a call to Read or Write or to other I/O methods will return an error that wraps ErrDeadlineExceeded. This can be tested using errors.Is(err, os.ErrDeadlineExceeded). That error implements the Timeout method, and calling the Timeout method will return true, but there are other possible errors for which the Timeout will return true even if the deadline has not been exceeded.

An idle timeout can be implemented by repeatedly extending the deadline after successful Read or Write calls.

A zero value for t means I/O operations will not time out.

func (*File) SetReadDeadline 1.10

func (f *File) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out. Not all files support setting deadlines; see SetDeadline.

func (*File) SetWriteDeadline 1.10

func (f *File) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for any future Write calls and any currently-blocked Write call. Even if Write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out. Not all files support setting deadlines; see SetDeadline.

func (*File) Stat

func (f *File) Stat() (FileInfo, error)

Stat returns the FileInfo structure describing file. If there is an error, it will be of type *PathError.

func (*File) Sync

func (f *File) Sync() error

Sync commits the current contents of the file to stable storage. Typically, this means flushing the file system's in-memory copy of recently written data to disk.

func (*File) SyscallConn 1.12

func (f *File) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw file. This implements the syscall.Conn interface.

func (*File) Truncate

func (f *File) Truncate(size int64) error

Truncate changes the size of the file. It does not change the I/O offset. If there is an error, it will be of type *PathError.

func (*File) Write

func (f *File) Write(b []byte) (n int, err error)

Write writes len(b) bytes from b to the File. It returns the number of bytes written and an error, if any. Write returns a non-nil error when n != len(b).

func (*File) WriteAt

func (f *File) WriteAt(b []byte, off int64) (n int, err error)

WriteAt writes len(b) bytes to the File starting at byte offset off. It returns the number of bytes written and an error, if any. WriteAt returns a non-nil error when n != len(b).

If file was opened with the O_APPEND flag, WriteAt returns an error.

func (*File) WriteString

func (f *File) WriteString(s string) (n int, err error)

WriteString is like Write, but writes the contents of string s rather than a slice of bytes.

func (*File) WriteTo 1.22

func (f *File) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriterTo.

func (*File) checkValid

func (f *File) checkValid(op string) error

checkValid checks whether f is valid for use. If not, it returns an appropriate error, perhaps incorporating the operation name op.

func (*File) chmod

func (f *File) chmod(mode FileMode) error

See docs in file.go:(*File).Chmod.

func (File) close

func (file File) close() error

func (*File) copyFileRange

func (f *File) copyFileRange(r io.Reader) (written int64, handled bool, err error)

func (*File) fd

func (f *File) fd() uintptr

fd is the Unix implementation of Fd.

func (*File) lstatat

func (f *File) lstatat(name string) (FileInfo, error)

func (*File) lstatatNolog

func (f *File) lstatatNolog(name string) (FileInfo, error)

func (*File) pread

func (f *File) pread(b []byte, off int64) (n int, err error)

pread reads len(b) bytes from the File starting at byte offset off. It returns the number of bytes read and the error, if any. EOF is signaled by a zero count with err set to nil.

func (*File) pwrite

func (f *File) pwrite(b []byte, off int64) (n int, err error)

pwrite writes len(b) bytes to the File starting at byte offset off. It returns the number of bytes written and an error, if any.

func (*File) read

func (f *File) read(b []byte) (n int, err error)

read reads up to len(b) bytes from the File. It returns the number of bytes read and an error, if any.

func (*File) readFrom

func (f *File) readFrom(r io.Reader) (written int64, handled bool, err error)

func (*File) readdir

func (f *File) readdir(n int, mode readdirMode) (names []string, dirents []DirEntry, infos []FileInfo, err error)

func (*File) seek

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.

func (*File) setDeadline

func (f *File) setDeadline(t time.Time) error

setDeadline sets the read and write deadline.

func (*File) setReadDeadline

func (f *File) setReadDeadline(t time.Time) error

setReadDeadline sets the read deadline.

func (*File) setWriteDeadline

func (f *File) setWriteDeadline(t time.Time) error

setWriteDeadline sets the write deadline.

func (*File) spliceToFile

func (f *File) spliceToFile(r io.Reader) (written int64, handled bool, err error)

func (*File) wrapErr

func (f *File) wrapErr(op string, err error) error

wrapErr wraps an error that occurred during an operation on an open file. It passes io.EOF through unchanged, otherwise converts poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.

func (*File) write

func (f *File) write(b []byte) (n int, err error)

write writes len(b) bytes to the File. It returns the number of bytes written and an error, if any.

func (*File) writeTo

func (f *File) writeTo(w io.Writer) (written int64, handled bool, err error)

type FileInfo

A FileInfo describes a file and is returned by Stat and Lstat.

type FileInfo = fs.FileInfo

func Lstat

func Lstat(name string) (FileInfo, error)

Lstat returns a FileInfo describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link. If there is an error, it will be of type *PathError.

On Windows, if the file is a reparse point that is a surrogate for another named entity (such as a symbolic link or mounted folder), the returned FileInfo describes the reparse point, and makes no attempt to resolve it.

func Stat

func Stat(name string) (FileInfo, error)

Stat returns a FileInfo describing the named file. If there is an error, it will be of type *PathError.

func lstatNolog

func lstatNolog(name string) (FileInfo, error)

lstatNolog lstats a file with no test logging.

func lstatat

func lstatat(parent int, name string) (FileInfo, error)

func lstatatWithName

func lstatatWithName(parent int, origName, name string) (FileInfo, error)

func rootStat

func rootStat(r *Root, name string, lstat bool) (FileInfo, error)

func statNolog

func statNolog(name string) (FileInfo, error)

statNolog stats a file with no test logging.

type FileMode

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.

type FileMode = fs.FileMode

Example

func direntType

func direntType(buf []byte) FileMode

func modeAt

func modeAt(parent sysfdType, name string) (FileMode, error)

type LinkError

LinkError records an error during a link or symlink or rename system call and the paths that caused it.

type LinkError struct {
    Op  string
    Old string
    New string
    Err error
}

func (*LinkError) Error

func (e *LinkError) Error() string

func (*LinkError) Unwrap 1.13

func (e *LinkError) Unwrap() error

type PathError

PathError records an error and the operation and file path that caused it.

type PathError = fs.PathError

type ProcAttr

ProcAttr holds the attributes that will be applied to a new process started by StartProcess.

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.
    // On Unix systems, StartProcess will change these File values
    // to blocking mode, which means that SetDeadline will stop working
    // and calling Close will not interrupt a Read or Write.
    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
}

type Process

Process stores the information about a process created by StartProcess.

type Process struct {
    // Pid is the operating system process ID.
    Pid int

    // state contains the atomic process state.
    //
    // This consists of the processStatus fields,
    // which indicate if the process is done/released.
    state atomic.Uint32

    // Used only when handle is nil
    sigMu sync.RWMutex // avoid race between wait and signal

    // handle, if not nil, is a pointer to a struct
    // that holds the OS-specific process handle.
    // This pointer is set when Process is created,
    // and never changed afterward.
    // This is a pointer to a separate memory allocation
    // so that we can use runtime.AddCleanup.
    handle *processHandle

    // cleanup is used to clean up the process handle.
    cleanup runtime.Cleanup
}

func FindProcess

func FindProcess(pid int) (*Process, error)

FindProcess looks for a running process by its pid.

The Process it returns can be used to obtain information about the underlying operating system process.

On Unix systems, FindProcess always succeeds and returns a Process for the given pid, regardless of whether the process exists. To test whether the process actually exists, see whether p.Signal(syscall.Signal(0)) reports an error.

func StartProcess

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. The argv slice will become os.Args in the new process, so it normally starts with the program name.

If the calling goroutine has locked the operating system thread with runtime.LockOSThread and modified any inheritable OS-level thread state (for example, Linux or Plan 9 name spaces), the new process will inherit the caller's thread state.

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 findProcess

func findProcess(pid int) (p *Process, err error)

func newDoneProcess

func newDoneProcess(pid int) *Process

newDoneProcess returns a Process for the given PID that is already marked as done. This is used on Unix systems if the process is known to not exist.

func newHandleProcess

func newHandleProcess(pid int, handle uintptr) *Process

newHandleProcess returns a Process with the given PID and handle.

func newPIDProcess

func newPIDProcess(pid int) *Process

newPIDProcess returns a Process for the given PID.

func startProcess

func startProcess(name string, argv []string, attr *ProcAttr) (p *Process, err error)

func (*Process) Kill

func (p *Process) Kill() error

Kill causes the Process to exit immediately. Kill does not wait until the Process has actually exited. This only kills the Process itself, not any other processes it may have started.

func (*Process) Release

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 Process.Wait is not.

func (*Process) Signal

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

Signal sends a signal to the Process. Sending Interrupt on Windows is not implemented.

func (*Process) Wait

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. On most operating systems, the Process must be a child of the current process or an error will be returned.

func (*Process) WithHandle 1.26

func (p *Process) WithHandle(f func(handle uintptr)) error

WithHandle calls a supplied function f with a valid process handle as an argument. The handle is guaranteed to refer to process p until f returns, even if p terminates. This function cannot be used after Process.Release or Process.Wait.

If process handles are not supported or a handle is not available, it returns ErrNoHandle. Currently, process handles are supported on Linux 5.4 or later (pidfd) and Windows.

func (*Process) blockUntilWaitable

func (p *Process) blockUntilWaitable() (bool, error)

blockUntilWaitable attempts to block until a call to p.Wait will succeed immediately, and reports whether it has done so. It does not actually call p.Wait.

func (*Process) doRelease

func (p *Process) doRelease(newStatus processStatus) processStatus

doRelease releases a Process, setting the status to newStatus. If the previous status is not statusOK, this does nothing. It returns the previous status.

func (*Process) handleTransientAcquire

func (p *Process) handleTransientAcquire() (uintptr, processStatus)

handleTransientAcquire returns the process handle or, if the process is not ready, the current status.

func (*Process) handleTransientRelease

func (p *Process) handleTransientRelease()

handleTransientRelease releases a handle returned by handleTransientAcquire.

func (*Process) kill

func (p *Process) kill() error

func (*Process) pidSignal

func (p *Process) pidSignal(s syscall.Signal) error

func (*Process) pidStatus

func (p *Process) pidStatus() processStatus

pidStatus returns the current process status.

func (*Process) pidWait

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

func (*Process) pidfdSendSignal

func (p *Process) pidfdSendSignal(s syscall.Signal) error

pidfdSendSignal sends a signal to the process.

func (*Process) pidfdWait

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

pidfdWait waits for the process to complete, and updates the process status to done.

func (*Process) signal

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

func (*Process) wait

func (p *Process) wait() (ps *ProcessState, err error)

func (*Process) withHandle

func (p *Process) withHandle(f func(handle uintptr)) error

type ProcessState

ProcessState stores information about a process, as reported by Wait.

type ProcessState struct {
    pid    int                // The process's id.
    status syscall.WaitStatus // System-dependent status info.
    rusage *syscall.Rusage
}

func (*ProcessState) ExitCode 1.12

func (p *ProcessState) ExitCode() int

ExitCode returns the exit code of the exited process, or -1 if the process hasn't exited or was terminated by a signal.

func (*ProcessState) Exited

func (p *ProcessState) Exited() bool

Exited reports whether the program has exited. On Unix systems this reports true if the program exited due to calling exit, but false if the program terminated due to a signal.

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() any

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() any

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.

func (*ProcessState) exited

func (p *ProcessState) exited() bool

func (*ProcessState) success

func (p *ProcessState) success() bool

func (*ProcessState) sys

func (p *ProcessState) sys() any

func (*ProcessState) sysUsage

func (p *ProcessState) sysUsage() any

func (*ProcessState) systemTime

func (p *ProcessState) systemTime() time.Duration

func (*ProcessState) userTime

func (p *ProcessState) userTime() time.Duration

type Root 1.24

Root may be used to only access files within a single directory tree.

Methods on Root can only access files and directories beneath a root directory. If any component of a file name passed to a method of Root references a location outside the root, the method returns an error. File names may reference the directory itself (.).

Methods on Root will follow symbolic links, but symbolic links may not reference a location outside the root. Symbolic links must not be absolute.

Methods on Root do not prohibit traversal of filesystem boundaries, Linux bind mounts, /proc special files, or access to Unix device files.

Methods on Root are safe to be used from multiple goroutines simultaneously.

On most platforms, creating a Root opens a file descriptor or handle referencing the directory. If the directory is moved, methods on Root reference the original directory in its new location.

Root's behavior differs on some platforms:

type Root struct {
    root *root
}

func OpenRoot 1.24

func OpenRoot(name string) (*Root, error)

OpenRoot opens the named directory. It follows symbolic links in the directory name. If there is an error, it will be of type *PathError.

func newRoot

func newRoot(fd int, name string) (*Root, error)

newRoot returns a new Root. If fd is not a directory, it closes it and returns an error.

func openRootInRoot

func openRootInRoot(r *Root, name string) (*Root, error)

openRootInRoot is Root.OpenRoot.

func openRootNolog

func openRootNolog(name string) (*Root, error)

openRootNolog is OpenRoot.

func (*Root) Chmod 1.25

func (r *Root) Chmod(name string, mode FileMode) error

Chmod changes the mode of the named file in the root to mode. See Chmod for more details.

func (*Root) Chown 1.25

func (r *Root) Chown(name string, uid, gid int) error

Chown changes the numeric uid and gid of the named file in the root. See Chown for more details.

func (*Root) Chtimes 1.25

func (r *Root) Chtimes(name string, atime time.Time, mtime time.Time) error

Chtimes changes the access and modification times of the named file in the root. See Chtimes for more details.

func (*Root) Close 1.24

func (r *Root) Close() error

Close closes the Root. After Close is called, methods on Root return errors.

func (*Root) Create 1.24

func (r *Root) Create(name string) (*File, error)

Create creates or truncates the named file in the root. See Create for more details.

func (*Root) FS 1.24

func (r *Root) FS() fs.FS

FS returns a file system (an fs.FS) for the tree of files in the root.

The result implements io/fs.StatFS, io/fs.ReadFileFS, io/fs.ReadDirFS, and io/fs.ReadLinkFS.

func (*Root) Lchown 1.25

func (r *Root) Lchown(name string, uid, gid int) error

Lchown changes the numeric uid and gid of the named file in the root. See Lchown for more details.

func (r *Root) Link(oldname, newname string) error

Link creates newname as a hard link to the oldname file. Both paths are relative to the root. See Link for more details.

If oldname is a symbolic link, Link creates new link to oldname and not its target. This behavior may differ from that of Link on some platforms.

When GOOS=js, Link returns an error if oldname is a symbolic link.

func (*Root) Lstat 1.24

func (r *Root) Lstat(name string) (FileInfo, error)

Lstat returns a FileInfo describing the named file in the root. If the file is a symbolic link, the returned FileInfo describes the symbolic link. See Lstat for more details.

func (*Root) Mkdir 1.24

func (r *Root) Mkdir(name string, perm FileMode) error

Mkdir creates a new directory in the root with the specified name and permission bits (before umask). See Mkdir for more details.

If perm contains bits other than the nine least-significant bits (0o777), Mkdir returns an error.

func (*Root) MkdirAll 1.25

func (r *Root) MkdirAll(name string, perm FileMode) error

MkdirAll creates a new directory in the root, along with any necessary parents. See MkdirAll for more details.

If perm contains bits other than the nine least-significant bits (0o777), MkdirAll returns an error.

func (*Root) Name 1.24

func (r *Root) Name() string

Name returns the name of the directory presented to OpenRoot.

It is safe to call Name after [Close].

func (*Root) Open 1.24

func (r *Root) Open(name string) (*File, error)

Open opens the named file in the root for reading. See Open for more details.

func (*Root) OpenFile 1.24

func (r *Root) OpenFile(name string, flag int, perm FileMode) (*File, error)

OpenFile opens the named file in the root. See OpenFile for more details.

If perm contains bits other than the nine least-significant bits (0o777), OpenFile returns an error.

func (*Root) OpenRoot 1.24

func (r *Root) OpenRoot(name string) (*Root, error)

OpenRoot opens the named directory in the root. If there is an error, it will be of type *PathError.

func (*Root) ReadFile 1.25

func (r *Root) ReadFile(name string) ([]byte, error)

ReadFile reads the named file in the root and returns its contents. See ReadFile for more details.

func (r *Root) Readlink(name string) (string, error)

Readlink returns the destination of the named symbolic link in the root. See Readlink for more details.

func (*Root) Remove 1.24

func (r *Root) Remove(name string) error

Remove removes the named file or (empty) directory in the root. See Remove for more details.

func (*Root) RemoveAll 1.25

func (r *Root) RemoveAll(name string) error

RemoveAll removes the named file or directory and any children that it contains. See RemoveAll for more details.

func (*Root) Rename 1.25

func (r *Root) Rename(oldname, newname string) error

Rename renames (moves) oldname to newname. Both paths are relative to the root. See Rename for more details.

func (*Root) Stat 1.24

func (r *Root) Stat(name string) (FileInfo, error)

Stat returns a FileInfo describing the named file in the root. See Stat for more details.

func (r *Root) Symlink(oldname, newname string) error

Symlink creates newname as a symbolic link to oldname. See Symlink for more details.

Symlink does not validate oldname, which may reference a location outside the root.

On Windows, a directory link is created if oldname references a directory within the root. Otherwise a file link is created.

func (*Root) WriteFile 1.25

func (r *Root) WriteFile(name string, data []byte, perm FileMode) error

WriteFile writes data to the named file in the root, creating it if necessary. See WriteFile for more details.

func (*Root) logOpen

func (r *Root) logOpen(name string)

func (*Root) logStat

func (r *Root) logStat(name string)

type Signal

A Signal represents an operating system signal. The usual underlying implementation is operating system-dependent: on Unix it is syscall.Signal.

type Signal interface {
    String() string
    Signal() // to distinguish from other Stringers
}

The only signal values guaranteed to be present in the os package on all systems are os.Interrupt (send the process an interrupt) and os.Kill (force the process to exit). On Windows, sending os.Interrupt to a process with os.Process.Signal is not implemented; it will return an error instead of sending a signal.

var (
    Interrupt Signal = syscall.SIGINT
    Kill      Signal = syscall.SIGKILL
)

type SyscallError

SyscallError records an error from a specific system call.

type SyscallError struct {
    Syscall string
    Err     error
}

func (*SyscallError) Error

func (e *SyscallError) Error() string

func (*SyscallError) Timeout 1.10

func (e *SyscallError) Timeout() bool

Timeout reports whether this error represents a timeout.

func (*SyscallError) Unwrap 1.13

func (e *SyscallError) Unwrap() error

type dirFS

type dirFS string

func (dirFS) Lstat

func (dir dirFS) Lstat(name string) (fs.FileInfo, error)

func (dirFS) Open

func (dir dirFS) Open(name string) (fs.File, error)

func (dirFS) ReadDir

func (dir dirFS) ReadDir(name string) ([]DirEntry, error)

ReadDir reads the named directory, returning all its directory entries sorted by filename. Through this method, dirFS implements io/fs.ReadDirFS.

func (dirFS) ReadFile

func (dir dirFS) ReadFile(name string) ([]byte, error)

The ReadFile method calls the ReadFile function for the file with the given name in the directory. The function provides robust handling for small files and special file systems. Through this method, dirFS implements io/fs.ReadFileFS.

func (dir dirFS) ReadLink(name string) (string, error)

func (dirFS) Stat

func (dir dirFS) Stat(name string) (fs.FileInfo, error)

func (dirFS) join

func (dir dirFS) join(name string) (string, error)

join returns the path for name in dir.

type dirInfo

Auxiliary information if the File describes a directory

type dirInfo struct {
    mu   sync.Mutex
    buf  *[]byte // buffer for directory I/O
    nbuf int     // length of buf; return value from Getdirentries
    bufp int     // location of next record in buf.
}

func (*dirInfo) close

func (d *dirInfo) close()

errSymlink reports that a file being operated on is actually a symlink, and the target of that symlink.

type errSymlink string

func (errSymlink) Error

func (errSymlink) Error() string

type file

file is the real representation of *File. The extra level of indirection ensures that no clients of os can overwrite this data, which could cause the finalizer to close the wrong file descriptor.

type file struct {
    pfd         poll.FD
    name        string
    dirinfo     atomic.Pointer[dirInfo] // nil unless directory being read
    nonblock    bool                    // whether we set nonblocking mode
    stdoutOrErr bool                    // whether this is stdout or stderr
    appendMode  bool                    // whether file is opened for appending
    inRoot      bool                    // whether file is opened in a Root
}

func (*file) close

func (file *file) close() error

type fileStat

A fileStat is the implementation of FileInfo returned by Stat and Lstat.

type fileStat struct {
    name    string
    size    int64
    mode    FileMode
    modTime time.Time
    sys     syscall.Stat_t
}

func (*fileStat) IsDir

func (fs *fileStat) IsDir() bool

func (*fileStat) ModTime

func (fs *fileStat) ModTime() time.Time

func (*fileStat) Mode

func (fs *fileStat) Mode() FileMode

func (*fileStat) Name

func (fs *fileStat) Name() string

func (*fileStat) Size

func (fs *fileStat) Size() int64

func (*fileStat) Sys

func (fs *fileStat) Sys() any

type fileWithoutReadFrom

fileWithoutReadFrom implements all the methods of *File other than ReadFrom. This is used to permit ReadFrom to call io.Copy without leading to a recursive call to ReadFrom.

type fileWithoutReadFrom struct {
    noReadFrom
    *File
}

func (fileWithoutReadFrom) close

func (file fileWithoutReadFrom) close() error

type fileWithoutWriteTo

fileWithoutWriteTo implements all the methods of *File other than WriteTo. This is used to permit WriteTo to call io.Copy without leading to a recursive call to WriteTo.

type fileWithoutWriteTo struct {
    noWriteTo
    *File
}

func (fileWithoutWriteTo) close

func (file fileWithoutWriteTo) close() error

type newFileKind

newFileKind describes the kind of file to newFile.

type newFileKind int
const (
    // kindNewFile means that the descriptor was passed to us via NewFile.
    kindNewFile newFileKind = iota
    // kindOpenFile means that the descriptor was opened using
    // Open, Create, or OpenFile.
    kindOpenFile
    // kindPipe means that the descriptor was opened using Pipe.
    kindPipe
    // kindSock means that the descriptor is a network file descriptor
    // that was created from net package and was opened using net_newUnixFile.
    kindSock
    // kindNoPoll means that we should not put the descriptor into
    // non-blocking mode, because we know it is not a pipe or FIFO.
    // Used by openDirAt and openDirNolog for directories.
    kindNoPoll
)

type noReadFrom

noReadFrom can be embedded alongside another type to hide the ReadFrom method of that other type.

type noReadFrom struct{}

func (noReadFrom) ReadFrom

func (noReadFrom) ReadFrom(io.Reader) (int64, error)

ReadFrom hides another ReadFrom method. It should never be called.

type noWriteTo

noWriteTo can be embedded alongside another type to hide the WriteTo method of that other type.

type noWriteTo struct{}

func (noWriteTo) WriteTo

func (noWriteTo) WriteTo(io.Writer) (int64, error)

WriteTo hides another WriteTo method. It should never be called.

type processHandle

processHandle holds an operating system handle to a process. This is only used on systems that support that concept, currently Linux and Windows. This maintains a reference count to the handle, and closes the handle when the reference drops to zero.

type processHandle struct {
    // The actual handle. This field should not be used directly.
    // Instead, use the acquire and release methods.
    //
    // On Windows this is a handle returned by OpenProcess.
    // On Linux this is a pidfd.
    handle uintptr

    // Number of active references. When this drops to zero
    // the handle is closed.
    refs atomic.Int32
}

func (*processHandle) acquire

func (ph *processHandle) acquire() (uintptr, bool)

acquire adds a reference and returns the handle. The bool result reports whether acquire succeeded; it fails if the handle is already closed. Every successful call to acquire should be paired with a call to release.

func (*processHandle) closeHandle

func (ph *processHandle) closeHandle()

func (*processHandle) release

func (ph *processHandle) release()

release releases a reference to the handle.

type processStatus

processStatus describes the status of a Process.

type processStatus uint32
const (
    // statusOK means that the Process is ready to use.
    statusOK processStatus = iota

    // statusDone indicates that the PID/handle should not be used because
    // the process is done (has been successfully Wait'd on).
    statusDone

    // statusReleased indicates that the PID/handle should not be used
    // because the process is released.
    statusReleased
)

type rawConn

rawConn implements syscall.RawConn.

type rawConn struct {
    file *File
}

func newRawConn

func newRawConn(file *File) (*rawConn, error)

func (*rawConn) Control

func (c *rawConn) Control(f func(uintptr)) error

func (*rawConn) Read

func (c *rawConn) Read(f func(uintptr) bool) error

func (*rawConn) Write

func (c *rawConn) Write(f func(uintptr) bool) error

type readdirMode

type readdirMode int
const (
    readdirName readdirMode = iota
    readdirDirEntry
    readdirFileInfo
)

type root

root implementation for platforms with a function to open a file relative to a directory.

type root struct {
    name string

    // refs is incremented while an operation is using fd.
    // closed is set when Close is called.
    // fd is closed when closed is true and refs is 0.
    mu     sync.Mutex
    fd     sysfdType
    refs   int  // number of active operations
    closed bool // set when closed
}

func (*root) Close

func (r *root) Close() error

func (*root) Name

func (r *root) Name() string

func (*root) decref

func (r *root) decref()

func (*root) incref

func (r *root) incref() error

type rootFS

type rootFS Root

func (*rootFS) Lstat

func (rfs *rootFS) Lstat(name string) (FileInfo, error)

func (*rootFS) Open

func (rfs *rootFS) Open(name string) (fs.File, error)

func (*rootFS) ReadDir

func (rfs *rootFS) ReadDir(name string) ([]DirEntry, error)

func (*rootFS) ReadFile

func (rfs *rootFS) ReadFile(name string) ([]byte, error)
func (rfs *rootFS) ReadLink(name string) (string, error)

func (*rootFS) Stat

func (rfs *rootFS) Stat(name string) (FileInfo, error)

type syscallErrorType

type syscallErrorType = syscall.Errno

type sysfdType

sysfdType is the native type of a file handle (int on Unix, syscall.Handle on Windows), permitting helper functions to be written portably.

type sysfdType = int

type timeout

type timeout interface {
    Timeout() bool
}

type unixDirent

type unixDirent struct {
    parent string
    name   string
    typ    FileMode
    info   FileInfo
}

func (*unixDirent) Info

func (d *unixDirent) Info() (FileInfo, error)

func (*unixDirent) IsDir

func (d *unixDirent) IsDir() bool

func (*unixDirent) Name

func (d *unixDirent) Name() string

func (*unixDirent) String

func (d *unixDirent) String() string

func (*unixDirent) Type

func (d *unixDirent) Type() FileMode

Subdirectories

Name Synopsis
..
exec Package exec runs external commands.
internal
fdtest Package fdtest provides test helpers for working with file descriptors across exec.
signal Package signal implements access to incoming signals.
user Package user allows user account lookups by name or id.