process_unix.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //go:build !windows
  2. // +build !windows
  3. package process
  4. import (
  5. "bytes"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strconv"
  11. "golang.org/x/sys/unix"
  12. )
  13. // Alive returns true if process with a given pid is running.
  14. func Alive(pid int) bool {
  15. switch runtime.GOOS {
  16. case "darwin":
  17. // OS X does not have a proc filesystem. Use kill -0 pid to judge if the
  18. // process exists. From KILL(2): https://www.freebsd.org/cgi/man.cgi?query=kill&sektion=2&manpath=OpenDarwin+7.2.1
  19. //
  20. // Sig may be one of the signals specified in sigaction(2) or it may
  21. // be 0, in which case error checking is performed but no signal is
  22. // actually sent. This can be used to check the validity of pid.
  23. err := unix.Kill(pid, 0)
  24. // Either the PID was found (no error) or we get an EPERM, which means
  25. // the PID exists, but we don't have permissions to signal it.
  26. return err == nil || err == unix.EPERM
  27. default:
  28. _, err := os.Stat(filepath.Join("/proc", strconv.Itoa(pid)))
  29. return err == nil
  30. }
  31. }
  32. // Kill force-stops a process.
  33. func Kill(pid int) error {
  34. err := unix.Kill(pid, unix.SIGKILL)
  35. if err != nil && err != unix.ESRCH {
  36. return err
  37. }
  38. return nil
  39. }
  40. // Zombie return true if process has a state with "Z"
  41. // http://man7.org/linux/man-pages/man5/proc.5.html
  42. func Zombie(pid int) (bool, error) {
  43. data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
  44. if err != nil {
  45. if os.IsNotExist(err) {
  46. return false, nil
  47. }
  48. return false, err
  49. }
  50. if cols := bytes.SplitN(data, []byte(" "), 4); len(cols) >= 3 && string(cols[2]) == "Z" {
  51. return true, nil
  52. }
  53. return false, nil
  54. }