os.FindProcess 足以验证进程是否存在吗?
在已知进程 PID 的情况下,您可能想知道是否使用os.FindProcess 本身就足以确定进程的存在。本文深入研究了这一特定场景,并提供了一种利用操作系统原理的替代方法。
os.FindProcess 限制
使用kill -s 0的替代方法
import ( "log" "os/exec" "strconv" ) 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 }
改进的进程存在检测
结论
虽然 os.FindProcess 提供了进程存在的初始指示,但使用kill -s 0 拥抱传统的 Unix 方法提供了更全面的验证和对流程所有权的见解。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3