如果我具有流程的PID,则os.FindProcess是否足以测试该流程的存在?我的意思是,如果返回err,我是否可以认为它已终止(或被杀死)?
err
编辑:
我刚刚写了一个包装函数kill -s 0(旧式bash流程测试)。这可以正常工作,但是如果有其他解决方案(使用go库完成),我仍然很高兴。
kill -s 0
func checkPid(pid int) bool { out, err := exec.Command("kill", "-s", "0", strconv.Itoa(pid)).CombinedOutput() if err != nil { log.Println(err) } if string(out) == "" { return true // pid exist } return false }
这是查看进程是否处于活动状态的传统的Unix方式-向其发送0信号(就像您对bash示例所做的一样)。
来自kill(2):
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.
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.
并翻译成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) } } }
当您运行它时,您将得到此消息,表明进程123已死,进程1处于活动状态,但不属于您,进程12606处于活动状态,由您拥有。
$ ./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