Involved Source Filesdir.godir_unix.godirent_linux.goenv.goerror.goerror_errno.goexec.goexec_linux.goexec_posix.goexec_unix.goexecutable.goexecutable_procfs.go 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.file_open_unix.gofile_posix.gofile_unix.gogetwd.gopath.gopath_unix.gopidfd_linux.gopipe2_unix.goproc.gorawconn.goremoveall_at.gostat.gostat_linux.gostat_unix.gosticky_notbsd.gosys.gosys_linux.gosys_unix.gotempfile.gotypes.gotypes_unix.gowait_waitid.gozero_copy_linux.go
Code Examples
package main
import (
"log"
"os"
)
func main() {
if err := os.Chmod("some-filename", 0644); err != nil {
log.Fatal(err)
}
}
package main
import (
"log"
"os"
"time"
)
func main() {
mtime := time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC)
atime := time.Date(2007, time.March, 2, 4, 5, 6, 0, time.UTC)
if err := os.Chtimes("some-filename", atime, mtime); err != nil {
log.Fatal(err)
}
}
package main
import (
"log"
"os"
)
func main() {
f, err := os.CreateTemp("", "example")
if err != nil {
log.Fatal(err)
}
defer os.Remove(f.Name()) // clean up
if _, err := f.Write([]byte("content")); err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
package main
import (
"log"
"os"
)
func main() {
f, err := os.CreateTemp("", "example.*.txt")
if err != nil {
log.Fatal(err)
}
defer os.Remove(f.Name()) // clean up
if _, err := f.Write([]byte("content")); err != nil {
f.Close()
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
package main
import (
"errors"
"fmt"
"io/fs"
"os"
)
func main() {
filename := "a-nonexistent-file"
if _, err := os.Stat(filename); errors.Is(err, fs.ErrNotExist) {
fmt.Println("file does not exist")
}
}
package main
import (
"fmt"
"os"
)
func main() {
mapper := func(placeholderName string) string {
switch placeholderName {
case "DAY_PART":
return "morning"
case "NAME":
return "Gopher"
}
return ""
}
fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper))
}
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("NAME", "gopher")
os.Setenv("BURROW", "/usr/gopher")
fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}."))
}
package main
import (
"fmt"
"io/fs"
"log"
"os"
)
func main() {
fi, err := os.Lstat("some-filename")
if err != nil {
log.Fatal(err)
}
fmt.Printf("permissions: %#o\n", fi.Mode().Perm()) // 0o400, 0o777, etc.
switch mode := fi.Mode(); {
case mode.IsRegular():
fmt.Println("regular file")
case mode.IsDir():
fmt.Println("directory")
case mode&fs.ModeSymlink != 0:
fmt.Println("symbolic link")
case mode&fs.ModeNamedPipe != 0:
fmt.Println("named pipe")
}
}
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("NAME", "gopher")
os.Setenv("BURROW", "/usr/gopher")
fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW"))
}
package main
import (
"fmt"
"os"
)
func main() {
show := func(key string) {
val, ok := os.LookupEnv(key)
if !ok {
fmt.Printf("%s not set\n", key)
} else {
fmt.Printf("%s=%s\n", key, val)
}
}
os.Setenv("SOME_KEY", "value")
os.Setenv("EMPTY_KEY", "")
show("SOME_KEY")
show("EMPTY_KEY")
show("MISSING_KEY")
}
package main
import (
"log"
"os"
)
func main() {
err := os.Mkdir("testdir", 0750)
if err != nil && !os.IsExist(err) {
log.Fatal(err)
}
err = os.WriteFile("testdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
if err != nil {
log.Fatal(err)
}
}
package main
import (
"log"
"os"
)
func main() {
err := os.MkdirAll("test/subdir", 0750)
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("test/subdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
if err != nil {
log.Fatal(err)
}
}
package main
import (
"log"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
file := filepath.Join(dir, "tmpfile")
if err := os.WriteFile(file, []byte("content"), 0666); err != nil {
log.Fatal(err)
}
}
package main
import (
"log"
"os"
"path/filepath"
)
func main() {
logsDir, err := os.MkdirTemp("", "*-logs")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(logsDir) // clean up
// Logs can be cleaned out earlier if needed by searching
// for all directories whose suffix ends in *-logs.
globPattern := filepath.Join(os.TempDir(), "*-logs")
matches, err := filepath.Glob(globPattern)
if err != nil {
log.Fatalf("Failed to match %q: %v", globPattern, err)
}
for _, match := range matches {
if err := os.RemoveAll(match); err != nil {
log.Printf("Failed to remove %q: %v", match, err)
}
}
}
package main
import (
"log"
"os"
)
func main() {
f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
package main
import (
"log"
"os"
)
func main() {
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
if _, err := f.Write([]byte("appended some data\n")); err != nil {
f.Close() // ignore error; Write error takes precedence
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
package main
import (
"fmt"
"log"
"os"
)
func main() {
files, err := os.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fmt.Println(file.Name())
}
}
package main
import (
"log"
"os"
)
func main() {
data, err := os.ReadFile("testdata/hello")
if err != nil {
log.Fatal(err)
}
os.Stdout.Write(data)
}
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
)
func main() {
// First, we create a relative symlink to a file.
d, err := os.MkdirTemp("", "")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(d)
targetPath := filepath.Join(d, "hello.txt")
if err := os.WriteFile(targetPath, []byte("Hello, Gophers!"), 0644); err != nil {
log.Fatal(err)
}
linkPath := filepath.Join(d, "hello.link")
if err := os.Symlink("hello.txt", filepath.Join(d, "hello.link")); err != nil {
if errors.Is(err, errors.ErrUnsupported) {
// Allow the example to run on platforms that do not support symbolic links.
fmt.Printf("%s links to %s\n", filepath.Base(linkPath), "hello.txt")
return
}
log.Fatal(err)
}
// Readlink returns the relative path as passed to os.Symlink.
dst, err := os.Readlink(linkPath)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s links to %s\n", filepath.Base(linkPath), dst)
var dstAbs string
if filepath.IsAbs(dst) {
dstAbs = dst
} else {
// Symlink targets are relative to the directory containing the link.
dstAbs = filepath.Join(filepath.Dir(linkPath), dst)
}
// Check that the target is correct by comparing it with os.Stat
// on the original target path.
dstInfo, err := os.Stat(dstAbs)
if err != nil {
log.Fatal(err)
}
targetInfo, err := os.Stat(targetPath)
if err != nil {
log.Fatal(err)
}
if !os.SameFile(dstInfo, targetInfo) {
log.Fatalf("link destination (%s) is not the same file as %s", dstAbs, targetPath)
}
}
package main
import (
"os"
)
func main() {
os.Setenv("TMPDIR", "/my/tmp")
defer os.Unsetenv("TMPDIR")
}
package main
import (
"log"
"os"
"path/filepath"
"sync"
)
func main() {
dir, dirErr := os.UserCacheDir()
if dirErr == nil {
dir = filepath.Join(dir, "ExampleUserCacheDir")
}
getCache := func(name string) ([]byte, error) {
if dirErr != nil {
return nil, &os.PathError{Op: "getCache", Path: name, Err: os.ErrNotExist}
}
return os.ReadFile(filepath.Join(dir, name))
}
var mkdirOnce sync.Once
putCache := func(name string, b []byte) error {
if dirErr != nil {
return &os.PathError{Op: "putCache", Path: name, Err: dirErr}
}
mkdirOnce.Do(func() {
if err := os.MkdirAll(dir, 0700); err != nil {
log.Printf("can't create user cache dir: %v", err)
}
})
return os.WriteFile(filepath.Join(dir, name), b, 0600)
}
// Read and store cached data.
// …
_ = getCache
_ = putCache
}
package main
import (
"bytes"
"log"
"os"
"path/filepath"
)
func main() {
dir, dirErr := os.UserConfigDir()
var (
configPath string
origConfig []byte
)
if dirErr == nil {
configPath = filepath.Join(dir, "ExampleUserConfigDir", "example.conf")
var err error
origConfig, err = os.ReadFile(configPath)
if err != nil && !os.IsNotExist(err) {
// The user has a config file but we couldn't read it.
// Report the error instead of ignoring their configuration.
log.Fatal(err)
}
}
// Use and perhaps make changes to the config.
config := bytes.Clone(origConfig)
// …
// Save changes.
if !bytes.Equal(config, origConfig) {
if configPath == "" {
log.Printf("not saving config changes: %v", dirErr)
} else {
err := os.MkdirAll(filepath.Dir(configPath), 0700)
if err == nil {
err = os.WriteFile(configPath, config, 0600)
}
if err != nil {
log.Printf("error saving config changes: %v", err)
}
}
}
}
package main
import (
"log"
"os"
)
func main() {
err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)
if err != nil {
log.Fatal(err)
}
}
Package-Level Type Names (total 27, in which 11 are exported)
/* sort exporteds by: | */
A DirEntry is an entry read from a directory
(using the [ReadDir] function or a [File.ReadDir] method).
File represents an open file descriptor.
The methods of File are safe for concurrent use. // os specific // whether file is opened for appending // nil unless directory being readfile.namestring // whether we set nonblocking modefile.pfdpoll.FD // whether this is stdout or stderr 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]. Chmod changes the mode of the file to mode.
If there is an error, it will be of type *PathError. 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. 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. Fd returns the integer Unix file descriptor referencing the open file.
If f is closed, the file descriptor becomes invalid.
If f is garbage collected, a finalizer may close the file descriptor,
making it invalid; see [runtime.SetFinalizer] for more information on when
a finalizer might be run. On Unix systems this will cause the [File.SetDeadline]
methods to stop working.
Because file descriptors can be reused, the returned file descriptor may
only be closed through the [File.Close] method of f, or by its finalizer during
garbage collection. Otherwise, during garbage collection the finalizer
may close an unrelated file descriptor with the same (reused) number.
As an alternative, see the f.SyscallConn method. Name returns the name of the file as presented to Open.
It is safe to call Name after [Close]. 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. 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. 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). ReadFrom implements io.ReaderFrom. 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. 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. 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. 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. 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. 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. Stat returns the [FileInfo] structure describing file.
If there is an error, it will be of type [*PathError]. 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. SyscallConn returns a raw file.
This implements the syscall.Conn interface. 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]. 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). 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. WriteString is like Write, but writes the contents of string s rather than
a slice of bytes. WriteTo implements io.WriterTo. checkValid checks whether f is valid for use.
If not, it returns an appropriate error, perhaps incorporating the operation name op. See docs in file.go:(*File).Chmod.( File) close() error(*File) copyFileRange(r io.Reader) (written int64, handled bool, 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. 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. read reads up to len(b) bytes from the File.
It returns the number of bytes read and an error, if any.(*File) readFrom(r io.Reader) (written int64, handled bool, err error)(*File) readdir(n int, mode readdirMode) (names []string, dirents []DirEntry, infos []FileInfo, 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. setDeadline sets the read and write deadline. setReadDeadline sets the read deadline. setWriteDeadline sets the write deadline.(*File) spliceToFile(r io.Reader) (written int64, handled bool, err 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. write writes len(b) bytes to the File.
It returns the number of bytes written and an error, if any.(*File) writeTo(w io.Writer) (written int64, handled bool, err error)
*File : internal/bisect.Writer
*File : io.Closer
*File : io.ReadCloser
*File : io.Reader
*File : io.ReaderAt
*File : io.ReaderFrom
*File : io.ReadSeekCloser
*File : io.ReadSeeker
*File : io.ReadWriteCloser
*File : io.ReadWriter
*File : io.ReadWriteSeeker
*File : io.Seeker
*File : io.StringWriter
*File : io.WriteCloser
*File : io.Writer
*File : io.WriterAt
*File : io.WriterTo
*File : io.WriteSeeker
*File : io/fs.File
*File : io/fs.ReadDirFile
*File : mime/multipart.File
*File : net/http.File
*File : syscall.Conn
*File : crypto/tls.transcriptHash
*File : net/http.http2stringWriter
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 Pipe() (r *File, w *File, err error)
func Pipe() (r *File, w *File, err error)
func net.(*TCPListener).File() (f *File, err error)
func net.(*UnixListener).File() (f *File, err error)
func net_newUnixFile(fd int, name string) *File
func newFile(fd int, name string, kind newFileKind, nonBlocking bool) *File
func openDir(name string) (*File, error)
func openDirAt(dirfd int, name string) (*File, error)
func openDirNolog(name string) (*File, error)
func openFileNolog(name string, flag int, perm FileMode) (*File, error)
func net.newUnixFile(fd int, name string) *File
func net.(*TCPListener).file() (*File, error)
func net.(*UnixListener).file() (*File, error)
func net.FileConn(f *File) (c net.Conn, err error)
func net.FileListener(f *File) (ln net.Listener, err error)
func net.FilePacketConn(f *File) (c net.PacketConn, err error)
func epipecheck(file *File, e error)
func genericReadFrom(f *File, r io.Reader) (int64, error)
func genericWriteTo(f *File, w io.Writer) (int64, error)
func newRawConn(file *File) (*rawConn, error)
func removeAllFrom(parent *File, base string) error
func net.dupSocket(f *File) (int, error)
func net.fileConn(f *File) (net.Conn, error)
func net.fileListener(f *File) (net.Listener, error)
func net.filePacketConn(f *File) (net.PacketConn, error)
func net.newFileFD(f *File) (*net.netFD, error)
var Stderr *File
var Stdin *File
var Stdout *File
A FileInfo describes a file and is returned by [Stat] and [Lstat].
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.
PathError records an error and the operation and file path that caused it.
ProcAttr holds the attributes that will be applied to a new process
started by StartProcess. If Dir is non-empty, the child changes into the directory before
creating the process. 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. 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. 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.
func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
func startProcess(name string, argv []string, attr *ProcAttr) (p *Process, err error)
Process stores the information about a process created by [StartProcess].Pidint handle is the OS handle for process actions, used only in
modeHandle.
handle must be accessed only via the handleTransientAcquire method
(or during closeHandle), not directly! handle is immutable.
On Windows, it is a handle from OpenProcess.
On Linux, it is a pidfd.
It is unused on other GOOSes.modeprocessMode Used only in modePID. // avoid race between wait and signal State contains the atomic process state.
In modePID, this consists only of the processStatus fields, which
indicate if the process is done/released.
In modeHandle, the lower bits also contain a reference count for the
handle field.
The Process itself initially holds 1 persistent reference. Any
operation that uses the handle with a system call temporarily holds
an additional transient reference. This prevents the handle from
being closed prematurely, which could result in the OS allocating a
different handle with the same value, leading to Process' methods
operating on the wrong process.
Release and Wait both drop the Process' persistent reference, but
other concurrent references may delay actually closing the handle
because they hold a transient reference.
Regardless, we want new method calls to immediately treat the handle
as unavailable after Release or Wait to avoid extending this delay.
This is achieved by setting either processStatus flag when the
Process' persistent reference is dropped. The only difference in the
flags is the reason the handle is unavailable, which affects the
errors returned by concurrent calls. 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. 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. Signal sends a signal to the [Process].
Sending [Interrupt] on Windows is not implemented. 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. 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.(*Process) closeHandle() Drop the Process' persistent reference on the handle, deactivating future
Wait/Signal calls with the passed reason.
Returns the status prior to this call. If this is not statusOK, then the
reference was not dropped or status changed.(*Process) handleTransientAcquire() (uintptr, processStatus)(*Process) handleTransientRelease()(*Process) kill() error(*Process) pidDeactivate(reason processStatus)(*Process) pidSignal(s syscall.Signal) error(*Process) pidStatus() processStatus(*Process) pidWait() (*ProcessState, error)(*Process) pidfdSendSignal(s syscall.Signal) error(*Process) pidfdWait() (*ProcessState, error)(*Process) release() error(*Process) signal(sig Signal) error(*Process) wait() (ps *ProcessState, err error)
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)
ProcessState stores information about a process, as reported by Wait. // The process's id.rusage*syscall.Rusage // System-dependent status info. ExitCode returns the exit code of the exited process, or -1
if the process hasn't exited or was terminated by a signal. 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. Pid returns the process id of the exited process.(*ProcessState) String() string Success reports whether the program exited successfully,
such as with exit status 0 on Unix. 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. 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.) SystemTime returns the system CPU time of the exited process and its children. UserTime returns the user CPU time of the exited process and its children.(*ProcessState) exited() bool(*ProcessState) success() bool(*ProcessState) sys() any(*ProcessState) sysUsage() any(*ProcessState) systemTime() time.Duration(*ProcessState) userTime() time.Duration
*ProcessState : fmt.Stringer
*ProcessState : context.stringer
*ProcessState : runtime.stringer
func (*Process).Wait() (*ProcessState, error)
func (*Process).pidfdWait() (*ProcessState, error)
func (*Process).pidWait() (*ProcessState, error)
func (*Process).wait() (ps *ProcessState, err error)
A Signal represents an operating system signal.
The usual underlying implementation is operating system-dependent:
on Unix it is syscall.Signal. // to distinguish from other Stringers( Signal) String() string
syscall.Signal
Signal : fmt.Stringer
Signal : context.stringer
Signal : runtime.stringer
func (*Process).Signal(sig Signal) error
func (*Process).signal(sig Signal) error
var Interrupt
var Kill
SyscallError records an error from a specific system call.ErrerrorSyscallstring(*SyscallError) Error() string Timeout reports whether this error represents a timeout.(*SyscallError) Unwrap() error
*SyscallError : error
*SyscallError : timeout
*SyscallError : net.timeout
( dirFS) Open(name string) (fs.File, error) ReadDir reads the named directory, returning all its directory entries sorted
by filename. Through this method, dirFS implements [io/fs.ReadDirFS]. 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].( dirFS) Stat(name string) (fs.FileInfo, error) join returns the path for name in dir.
dirFS : io/fs.FS
dirFS : io/fs.ReadDirFS
dirFS : io/fs.ReadFileFS
dirFS : io/fs.StatFS
Auxiliary information if the File describes a directory // buffer for directory I/O // location of next record in buf.musync.Mutex // length of buf; return value from Getdirentries(*dirInfo) close()
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. // whether file is opened for appending // nil unless directory being readnamestring // whether we set nonblocking modepfdpoll.FD // whether this is stdout or stderr(*file) close() error
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.File*File // os specific // whether file is opened for appending // nil unless directory being readFile.file.namestring // whether we set nonblocking modeFile.file.pfdpoll.FD // whether this is stdout or stderrnoReadFromnoReadFrom 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]. Chmod changes the mode of the file to mode.
If there is an error, it will be of type *PathError. 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. 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. Fd returns the integer Unix file descriptor referencing the open file.
If f is closed, the file descriptor becomes invalid.
If f is garbage collected, a finalizer may close the file descriptor,
making it invalid; see [runtime.SetFinalizer] for more information on when
a finalizer might be run. On Unix systems this will cause the [File.SetDeadline]
methods to stop working.
Because file descriptors can be reused, the returned file descriptor may
only be closed through the [File.Close] method of f, or by its finalizer during
garbage collection. Otherwise, during garbage collection the finalizer
may close an unrelated file descriptor with the same (reused) number.
As an alternative, see the f.SyscallConn method. Name returns the name of the file as presented to Open.
It is safe to call Name after [Close]. 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. 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. 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). 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. 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. 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. 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. 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. 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. Stat returns the [FileInfo] structure describing file.
If there is an error, it will be of type [*PathError]. 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. SyscallConn returns a raw file.
This implements the syscall.Conn interface. 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]. 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). 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. WriteString is like Write, but writes the contents of string s rather than
a slice of bytes. WriteTo implements io.WriterTo. checkValid checks whether f is valid for use.
If not, it returns an appropriate error, perhaps incorporating the operation name op. See docs in file.go:(*File).Chmod.( fileWithoutReadFrom) close() error( fileWithoutReadFrom) copyFileRange(r io.Reader) (written int64, handled bool, 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. 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. read reads up to len(b) bytes from the File.
It returns the number of bytes read and an error, if any.( fileWithoutReadFrom) readFrom(r io.Reader) (written int64, handled bool, err error)( fileWithoutReadFrom) readdir(n int, mode readdirMode) (names []string, dirents []DirEntry, infos []FileInfo, 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. setDeadline sets the read and write deadline. setReadDeadline sets the read deadline. setWriteDeadline sets the write deadline.( fileWithoutReadFrom) spliceToFile(r io.Reader) (written int64, handled bool, err 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. write writes len(b) bytes to the File.
It returns the number of bytes written and an error, if any.( fileWithoutReadFrom) writeTo(w io.Writer) (written int64, handled bool, err error)
fileWithoutReadFrom : internal/bisect.Writer
fileWithoutReadFrom : io.Closer
fileWithoutReadFrom : io.ReadCloser
fileWithoutReadFrom : io.Reader
fileWithoutReadFrom : io.ReaderAt
fileWithoutReadFrom : io.ReadSeekCloser
fileWithoutReadFrom : io.ReadSeeker
fileWithoutReadFrom : io.ReadWriteCloser
fileWithoutReadFrom : io.ReadWriter
fileWithoutReadFrom : io.ReadWriteSeeker
fileWithoutReadFrom : io.Seeker
fileWithoutReadFrom : io.StringWriter
fileWithoutReadFrom : io.WriteCloser
fileWithoutReadFrom : io.Writer
fileWithoutReadFrom : io.WriterAt
fileWithoutReadFrom : io.WriterTo
fileWithoutReadFrom : io.WriteSeeker
fileWithoutReadFrom : io/fs.File
fileWithoutReadFrom : io/fs.ReadDirFile
fileWithoutReadFrom : mime/multipart.File
fileWithoutReadFrom : net/http.File
fileWithoutReadFrom : syscall.Conn
fileWithoutReadFrom : crypto/tls.transcriptHash
fileWithoutReadFrom : net/http.http2stringWriter
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.File*File // os specific // whether file is opened for appending // nil unless directory being readFile.file.namestring // whether we set nonblocking modeFile.file.pfdpoll.FD // whether this is stdout or stderrnoWriteTonoWriteTo 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]. Chmod changes the mode of the file to mode.
If there is an error, it will be of type *PathError. 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. 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. Fd returns the integer Unix file descriptor referencing the open file.
If f is closed, the file descriptor becomes invalid.
If f is garbage collected, a finalizer may close the file descriptor,
making it invalid; see [runtime.SetFinalizer] for more information on when
a finalizer might be run. On Unix systems this will cause the [File.SetDeadline]
methods to stop working.
Because file descriptors can be reused, the returned file descriptor may
only be closed through the [File.Close] method of f, or by its finalizer during
garbage collection. Otherwise, during garbage collection the finalizer
may close an unrelated file descriptor with the same (reused) number.
As an alternative, see the f.SyscallConn method. Name returns the name of the file as presented to Open.
It is safe to call Name after [Close]. 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. 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. 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). ReadFrom implements io.ReaderFrom. 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. 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. 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. 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. 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. 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. Stat returns the [FileInfo] structure describing file.
If there is an error, it will be of type [*PathError]. 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. SyscallConn returns a raw file.
This implements the syscall.Conn interface. 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]. 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). 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. WriteString is like Write, but writes the contents of string s rather than
a slice of bytes. checkValid checks whether f is valid for use.
If not, it returns an appropriate error, perhaps incorporating the operation name op. See docs in file.go:(*File).Chmod.( fileWithoutWriteTo) close() error( fileWithoutWriteTo) copyFileRange(r io.Reader) (written int64, handled bool, 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. 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. read reads up to len(b) bytes from the File.
It returns the number of bytes read and an error, if any.( fileWithoutWriteTo) readFrom(r io.Reader) (written int64, handled bool, err error)( fileWithoutWriteTo) readdir(n int, mode readdirMode) (names []string, dirents []DirEntry, infos []FileInfo, 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. setDeadline sets the read and write deadline. setReadDeadline sets the read deadline. setWriteDeadline sets the write deadline.( fileWithoutWriteTo) spliceToFile(r io.Reader) (written int64, handled bool, err 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. write writes len(b) bytes to the File.
It returns the number of bytes written and an error, if any.( fileWithoutWriteTo) writeTo(w io.Writer) (written int64, handled bool, err error)
fileWithoutWriteTo : internal/bisect.Writer
fileWithoutWriteTo : io.Closer
fileWithoutWriteTo : io.ReadCloser
fileWithoutWriteTo : io.Reader
fileWithoutWriteTo : io.ReaderAt
fileWithoutWriteTo : io.ReaderFrom
fileWithoutWriteTo : io.ReadSeekCloser
fileWithoutWriteTo : io.ReadSeeker
fileWithoutWriteTo : io.ReadWriteCloser
fileWithoutWriteTo : io.ReadWriter
fileWithoutWriteTo : io.ReadWriteSeeker
fileWithoutWriteTo : io.Seeker
fileWithoutWriteTo : io.StringWriter
fileWithoutWriteTo : io.WriteCloser
fileWithoutWriteTo : io.Writer
fileWithoutWriteTo : io.WriterAt
fileWithoutWriteTo : io.WriteSeeker
fileWithoutWriteTo : io/fs.File
fileWithoutWriteTo : io/fs.ReadDirFile
fileWithoutWriteTo : mime/multipart.File
fileWithoutWriteTo : net/http.File
fileWithoutWriteTo : syscall.Conn
fileWithoutWriteTo : crypto/tls.transcriptHash
fileWithoutWriteTo : net/http.http2stringWriter
noReadFrom can be embedded alongside another type to
hide the ReadFrom method of that other type. ReadFrom hides another ReadFrom method.
It should never be called.
noReadFrom : io.ReaderFrom
noWriteTo can be embedded alongside another type to
hide the WriteTo method of that other type. WriteTo hides another WriteTo method.
It should never be called.
noWriteTo : io.WriterTo
Package-Level Functions (total 133, in which 61 are exported)
Chdir changes the current working directory to the named directory.
If there is an error, it will be of type *PathError.
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.
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
EPLAN9 error, wrapped in *PathError.
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].
Clearenv deletes all environment variables.
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 fsys are not supported. A *PathError with Err set
to ErrInvalid is returned when copying from a symbolic link.
Symbolic links in dir are followed.
Copying stops at and returns the first error encountered.
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.
If there is an error, it will be of type *PathError.
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.
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.
The directory dir must not be "".
The result implements [io/fs.StatFS], [io/fs.ReadFileFS] and
[io/fs.ReadDirFS].
Environ returns a copy of strings representing the environment,
in the form "key=value".
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.
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].
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]).
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.
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.
Getegid returns the numeric effective group id of the caller.
On Windows, it returns -1.
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].
Geteuid returns the numeric effective user id of the caller.
On Windows, it returns -1.
Getgid returns the numeric group id of the caller.
On Windows, it returns -1.
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.
Getpagesize returns the underlying system's memory page size.
Getpid returns the process id of the caller.
Getppid returns the process id of the caller's parent.
Getuid returns the numeric user id of the caller.
On Windows, it returns -1.
Getwd returns a rooted 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.
Hostname returns the host name reported by the kernel.
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).
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).
IsPathSeparator reports whether c is a directory separator character.
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).
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].
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.
Link creates newname as a hard link to the oldname file.
If there is an error, it will be of type *LinkError.
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.
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.
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.
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.
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.
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. On Unix systems, if the file descriptor is in
non-blocking mode, NewFile will attempt to return a pollable File
(one for which the SetDeadline methods work).
After passing it to NewFile, fd may become invalid under the same
conditions described in the comments of the Fd method, and the same
constraints apply.
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.
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.
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). If successful,
methods on the returned File can be used for I/O.
If there is an error, it will be of type *PathError.
Pipe returns a connected pair of Files; reads from r return bytes written to w.
It returns the files and an error, if any.
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.
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.
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.
Remove removes the named file or (empty) directory.
If there is an error, it will be of type *PathError.
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].
Rename renames (moves) oldpath to newpath.
If newpath already exists and is not a directory, Rename replaces it.
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.
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.
Setenv sets the value of the environment variable named by the key.
It returns an error, if any.
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].
Stat returns a [FileInfo] describing the named file.
If there is an error, it will be of type [*PathError].
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.
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.
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.
Unsetenv unsets a single environment variable.
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),
then it will return an 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),
then it will return an 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.
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.
For testing.
Provided by syscall.
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.
endsWithDot reports whether the final component of path is ".".
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.
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.
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).
getPidfd returns the value of sysAttr.PidFD (or its duplicate if needDup is
set) and a flag indicating whether the value can be used.
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.
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.
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.
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.
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.
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.
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.
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.
underlyingError returns the underlying error for known os error types.
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.
Package-Level Variables (total 24, in which 14 are exported)
Args hold the command-line arguments, starting with the program name.
Portable analogs of some common system call errors.
Errors returned from this package may be tested against these errors
with [errors.Is].
Portable analogs of some common system call errors.
Errors returned from this package may be tested against these errors
with [errors.Is].
Portable analogs of some common system call errors.
Errors returned from this package may be tested against these errors
with [errors.Is].
ErrInvalid indicates an invalid argument.
Methods on File will return this error when the receiver is nil.
Portable analogs of some common system call errors.
Errors returned from this package may be tested against these errors
with [errors.Is].
Portable analogs of some common system call errors.
Errors returned from this package may be tested against these errors
with [errors.Is].
Portable analogs of some common system call errors.
Errors returned from this package may be tested against these errors
with [errors.Is].
ErrProcessDone indicates a [Process] has finished.
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.
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.
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.
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.
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.
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).
testingForceReadDirLstat forces ReadDir to call Lstat, for testing that code path.
This can be difficult to provoke on some Unix systems otherwise.
Package-Level Constants (total 51, in which 29 are exported)
DevNull is the name of the operating system's “null device.”
On Unix-like systems, it is "/dev/null"; on Windows, "NUL".
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.
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.
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.
The single letters are the abbreviations
used by the String method's formatting.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Mask for the type bits. For regular files, none will be set.
The remaining values may be or'ed in to control behavior.
Flags to OpenFile wrapping those of the underlying system. Not all
flags may be implemented on a given system.
Flags to OpenFile wrapping those of the underlying system. Not all
flags may be implemented on a given system.
Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
Flags to OpenFile wrapping those of the underlying system. Not all
flags may be implemented on a given system.
Flags to OpenFile wrapping those of the underlying system. Not all
flags may be implemented on a given system.
Flags to OpenFile wrapping those of the underlying system. Not all
flags may be implemented on a given system.
Flags to OpenFile wrapping those of the underlying system. Not all
flags may be implemented on a given system.
More than 5760 to work around https://golang.org/issue/24015.
kindNewFile means that the descriptor was passed to us via NewFile.
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.
kindOpenFile means that the descriptor was opened using
Open, Create, or OpenFile.
kindPipe means that the descriptor was opened using Pipe.
kindSock means that the descriptor is a network file descriptor
that was created from net package and was opened using net_newUnixFile.
modeHandle means that Process operations use handle, which is
initialized with an OS process handle.
Note that Release and Wait will deactivate and eventually close the
handle, so acquire may fail, indicating the reason.
modePID means that Process operations such use the raw PID from the
Pid field. handle is not used.
This may be due to the host not supporting handles, or because
Process was created as a literal, leaving handle unset.
This must be the zero value so Process literals get modePID.
statusDone indicates that the PID/handle should not be used because
the process is done (has been successfully Wait'd on).
PID/handle OK to use.
statusReleased indicates that the PID/handle should not be used
because the process is released.
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.
The pages are generated with Goldsv0.7.6. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.