gpt4 book ai didi

linux - 所有 Linux 发行版中的/proc/[pid]/stat 是否始终可用?

转载 作者:IT王子 更新时间:2023-10-29 02:23:03 28 4
gpt4 key购买 nike

我想找到最好的通用方法来检查进程是否存在并在任何 Linux 上运行。

在 Unix/BSD 中,我可以通过 kqueue 执行此操作感谢使用 EVFILT_PROC/NOTE_EXITsyscall.Kqueue() 如果是 mac os X、netbsd、freebsd 等代码将正常工作并不重要帮助监控 PID 的状态。

试图在 linux 上实现相同的目的,我想定期检查 /proc/[pid]/stat 文件是否存在,而不是发送信号 0,kill -s 0 就像这里建议的那样:https://stackoverflow.com/a/15210305/1135424主要是为了简化逻辑,因为可以为现有进程返回非零错误。

可能使用类似的东西:

initialStat, err := os.Stat(fmt.Sprintf("/proc/%d/stat", self.pid)                                                                                                                                                           
if err != nil {
return
}

for {
stat, err := os.Stat(fmt.Sprintf("/proc/%d/stat", self.pid)
if err != nil {
return err
}

if stat.Size() != initialStat.Size() || stat.ModTime() != initialStat.ModTime() {
return nil
}
// wondering how to avoid sleeping here
time.Sleep(time.Second)
}

但想知道在所有 linux 中 /proc/[pid]/stat 是否始终可用,或者通过发送信号 0 kill -0 $PID 是否基本上完全正确一样。

最后,我总是可以回退到 kill -O $PID 但只是想知道可以使用哪些可能的解决方案(可能是 inotify),目的是避免不得不在循环中休眠,主要是因为没有占用大量 CPU 资源。

最佳答案

对于子进程,你应该使用waitpid

有一个用于处理事件的 netlink API ( http://netsplit.com/the-proc-connector-and-socket-filters ),可能对您的情况有用:

http://godoc.org/github.com/cloudfoundry/gosigar/psnotify#PROC_EVENT_EXIT

import "github.com/cloudfoundry/gosigar/psnotify"

func waitpid(pid int) error {
watcher, err := psnotify.NewWatcher()
if err != nil {
return err
}

if err := watcher.Watch(pid, psnotify.PROC_EVENT_EXIT); err != nil {
return err
}

defer watcher.Close()

// At this point, you should probably syscall.Kill(pid, 0) to check that the process is still running.

for {
select {
case ev := <-watcher.Error:
// TODO..
return ev
case <-watcher.Exit:
return nil
}
}
}

关于linux - 所有 Linux 发行版中的/proc/[pid]/stat 是否始终可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38446796/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com