process_unix.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //go:build linux || freebsd || darwin
  2. // +build linux freebsd darwin
  3. package system // import "github.com/docker/docker/pkg/system"
  4. import (
  5. "fmt"
  6. "os"
  7. "strings"
  8. "golang.org/x/sys/unix"
  9. )
  10. // IsProcessAlive returns true if process with a given pid is running.
  11. func IsProcessAlive(pid int) bool {
  12. err := unix.Kill(pid, 0)
  13. if err == nil || err == unix.EPERM {
  14. return true
  15. }
  16. return false
  17. }
  18. // KillProcess force-stops a process.
  19. func KillProcess(pid int) {
  20. unix.Kill(pid, unix.SIGKILL)
  21. }
  22. // IsProcessZombie return true if process has a state with "Z"
  23. // http://man7.org/linux/man-pages/man5/proc.5.html
  24. func IsProcessZombie(pid int) (bool, error) {
  25. statPath := fmt.Sprintf("/proc/%d/stat", pid)
  26. dataBytes, err := os.ReadFile(statPath)
  27. if err != nil {
  28. // TODO(thaJeztah) should we ignore os.IsNotExist() here? ("/proc/<pid>/stat" will be gone if the process exited)
  29. return false, err
  30. }
  31. data := string(dataBytes)
  32. sdata := strings.SplitN(data, " ", 4)
  33. if len(sdata) >= 3 && sdata[2] == "Z" {
  34. return true, nil
  35. }
  36. return false, nil
  37. }