Check if a process exists in go way

后端 未结 7 1921
甜味超标
甜味超标 2020-12-31 02:29

If I have the PID of a process, is os.FindProcess enough to test for the existing of the process? I mean if it returns err can I assume that it\'s terminated (o

7条回答
  •  误落风尘
    2020-12-31 02:51

    All the answers so far are incomplete implementations. See https://github.com/shirou/gopsutil/blob/c141152a7b8f59b63e060fa8450f5cd5e7196dfb/process/process_posix.go#L73 for a more complete implementation (copied inline)

        func PidExists(pid int32) (bool, error) {
            if pid <= 0 {
                return false, fmt.Errorf("invalid pid %v", pid)
            }
            proc, err := os.FindProcess(int(pid))
            if err != nil {
                return false, err
            }
            err = proc.Signal(syscall.Signal(0))
            if err == nil {
                return true, nil
            }
            if err.Error() == "os: process already finished" {
                return false, nil
            }
            errno, ok := err.(syscall.Errno)
            if !ok {
                return false, err
            }
            switch errno {
            case syscall.ESRCH:
                return false, nil
            case syscall.EPERM:
                return true, nil
            }
            return false, err
        }
    

提交回复
热议问题