这是查看进程是否处于活动状态的传统的Unix方式-向其发送0信号(就像您对bash示例所做的一样)。
来自
kill(2):
If sig is 0, then no signal is sent, but error checking is stillper‐
formed; this can be used to check for the existence of a process ID
or
process group ID.
并翻译成Go
package mainimport ( "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: %sn", err) } else { err := process.Signal(syscall.Signal(0)) fmt.Printf("process.Signal on pid %d returned: %vn", pid, err) } }}当您运行它时,您将得到此消息,表明进程123已死,进程1处于活动状态,但不属于您,进程12606处于活动状态,由您拥有。
$ ./kill 1 $$ 123process.Signal on pid 1 returned: operation not permittedprocess.Signal on pid 12606 returned: <nil>process.Signal on pid 123 returned: no such process



