如果我有一个进程的PID,是os.FindProcess足以测试流程的存在吗?我的意思是如果它返回 err
我可以假设它已被终止(或被杀死)吗?
编辑:
我刚刚围绕 kill -s 0
(旧式 bash 进程测试)编写了一个包装函数。这没有任何问题,但如果有其他解决方案(使用 go 库完成)来解决这个问题,我仍然很高兴。:
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)
:
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
关于process - 检查进程是否存在于 go way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15204162/