gopkg.in/docker/docker.v20@v20.10.27/pkg/system/process_unix.go (about)

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