Source file src/os/exec_posix.go

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build unix || (js && wasm) || wasip1 || windows
     6  
     7  package os
     8  
     9  import (
    10  	"internal/itoa"
    11  	"internal/syscall/execenv"
    12  	"runtime"
    13  	"syscall"
    14  )
    15  
    16  // The only signal values guaranteed to be present in the os package on all
    17  // systems are os.Interrupt (send the process an interrupt) and os.Kill (force
    18  // the process to exit). On Windows, sending os.Interrupt to a process with
    19  // os.Process.Signal is not implemented; it will return an error instead of
    20  // sending a signal.
    21  var (
    22  	Interrupt Signal = syscall.SIGINT
    23  	Kill      Signal = syscall.SIGKILL
    24  )
    25  
    26  func startProcess(name string, argv []string, attr *ProcAttr) (p *Process, err error) {
    27  	// If there is no SysProcAttr (ie. no Chroot or changed
    28  	// UID/GID), double-check existence of the directory we want
    29  	// to chdir into. We can make the error clearer this way.
    30  	if attr != nil && attr.Sys == nil && attr.Dir != "" {
    31  		if _, err := Stat(attr.Dir); err != nil {
    32  			pe := err.(*PathError)
    33  			pe.Op = "chdir"
    34  			return nil, pe
    35  		}
    36  	}
    37  
    38  	attrSys, shouldDupPidfd := ensurePidfd(attr.Sys)
    39  	sysattr := &syscall.ProcAttr{
    40  		Dir: attr.Dir,
    41  		Env: attr.Env,
    42  		Sys: attrSys,
    43  	}
    44  	if sysattr.Env == nil {
    45  		sysattr.Env, err = execenv.Default(sysattr.Sys)
    46  		if err != nil {
    47  			return nil, err
    48  		}
    49  	}
    50  	sysattr.Files = make([]uintptr, 0, len(attr.Files))
    51  	for _, f := range attr.Files {
    52  		sysattr.Files = append(sysattr.Files, f.Fd())
    53  	}
    54  
    55  	pid, h, e := syscall.StartProcess(name, argv, sysattr)
    56  
    57  	// Make sure we don't run the finalizers of attr.Files.
    58  	runtime.KeepAlive(attr)
    59  
    60  	if e != nil {
    61  		return nil, &PathError{Op: "fork/exec", Path: name, Err: e}
    62  	}
    63  
    64  	// For Windows, syscall.StartProcess above already returned a process handle.
    65  	if runtime.GOOS != "windows" {
    66  		var ok bool
    67  		h, ok = getPidfd(sysattr.Sys, shouldDupPidfd)
    68  		if !ok {
    69  			return newPIDProcess(pid), nil
    70  		}
    71  	}
    72  
    73  	return newHandleProcess(pid, h), nil
    74  }
    75  
    76  func (p *Process) kill() error {
    77  	return p.Signal(Kill)
    78  }
    79  
    80  func (p *Process) withHandle(f func(handle uintptr)) error {
    81  	if p.handle == nil {
    82  		return ErrNoHandle
    83  	}
    84  	handle, status := p.handleTransientAcquire()
    85  	switch status {
    86  	case statusDone:
    87  		return ErrProcessDone
    88  	case statusReleased:
    89  		return errProcessReleased
    90  	}
    91  	defer p.handleTransientRelease()
    92  	f(handle)
    93  
    94  	return nil
    95  }
    96  
    97  // ProcessState stores information about a process, as reported by Wait.
    98  type ProcessState struct {
    99  	pid    int                // The process's id.
   100  	status syscall.WaitStatus // System-dependent status info.
   101  	rusage *syscall.Rusage
   102  }
   103  
   104  // Pid returns the process id of the exited process.
   105  func (p *ProcessState) Pid() int {
   106  	return p.pid
   107  }
   108  
   109  func (p *ProcessState) exited() bool {
   110  	return p.status.Exited()
   111  }
   112  
   113  func (p *ProcessState) success() bool {
   114  	return p.status.ExitStatus() == 0
   115  }
   116  
   117  func (p *ProcessState) sys() any {
   118  	return p.status
   119  }
   120  
   121  func (p *ProcessState) sysUsage() any {
   122  	return p.rusage
   123  }
   124  
   125  func (p *ProcessState) String() string {
   126  	if p == nil {
   127  		return "<nil>"
   128  	}
   129  	status := p.Sys().(syscall.WaitStatus)
   130  	res := ""
   131  	switch {
   132  	case status.Exited():
   133  		code := status.ExitStatus()
   134  		if runtime.GOOS == "windows" && uint(code) >= 1<<16 { // windows uses large hex numbers
   135  			res = "exit status " + itoa.Uitox(uint(code))
   136  		} else { // unix systems use small decimal integers
   137  			res = "exit status " + itoa.Itoa(code) // unix
   138  		}
   139  	case status.Signaled():
   140  		res = "signal: " + status.Signal().String()
   141  	case status.Stopped():
   142  		res = "stop signal: " + status.StopSignal().String()
   143  		if status.StopSignal() == syscall.SIGTRAP && status.TrapCause() != 0 {
   144  			res += " (trap " + itoa.Itoa(status.TrapCause()) + ")"
   145  		}
   146  	case status.Continued():
   147  		res = "continued"
   148  	}
   149  	if status.CoreDump() {
   150  		res += " (core dumped)"
   151  	}
   152  	return res
   153  }
   154  
   155  // ExitCode returns the exit code of the exited process, or -1
   156  // if the process hasn't exited or was terminated by a signal.
   157  func (p *ProcessState) ExitCode() int {
   158  	// return -1 if the process hasn't started.
   159  	if p == nil {
   160  		return -1
   161  	}
   162  	return p.status.ExitStatus()
   163  }
   164  

View as plain text