Check if a process exists in go way

后端 未结 7 1841
甜味超标
甜味超标 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:57

    Here is the traditional unix way to see if a process is alive - send it a signal of 0 (like you did with your bash example).

    From kill(2):

       If  sig  is 0, then no signal is sent, but error checking is still per‐
       formed; this can be used to check for the existence of a process ID  or
       process group ID.
    

    And translated into Go

    package main
    
    import (
        "fmt"
        "log"
        "os"
        "strconv"
        "syscall"
    )
    
    func main() {
        for _, p := range os.Args[1:] {
            pid, err := strconv.ParseInt(p, 10, 64)
            if err != nil {
                log.Fatal(err)
            }
            process, err := os.FindProcess(int(pid))
            if err != nil {
                fmt.Printf("Failed to find process: %s\n", err)
            } else {
                err := process.Signal(syscall.Signal(0))
                fmt.Printf("process.Signal on pid %d returned: %v\n", pid, err)
            }
    
        }
    }
    

    When you run it you get this, showing that process 123 is dead, process 1 is alive but not owned by you and process 12606 is alive and owned by you.

    $ ./kill 1 $$ 123
    process.Signal on pid 1 returned: operation not permitted
    process.Signal on pid 12606 returned: <nil>
    process.Signal on pid 123 returned: no such process
    
    0 讨论(0)
提交回复
热议问题