process_unix.go 1.1 KB

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