I want to find the best universal way to check if a process exist and is running on any linux.
In Unix / BSD I am available to do this via kqueue thanks to the syscall.Kqueue()
using EVFILT_PROC / NOTE_EXIT
it doesn't' matter if is a mac os X, netbsd, freebsd, etc the code will just work and help to monitor the status of a PID.
Trying to achieve the same on linux, I came with the idea to check periodically for the existence of the /proc/[pid]/stat
file, instead of sending a signal 0, kill -s 0
like suggested here: https://stackoverflow.com/a/15210305/1135424 mainly to simplify the logic due that non-nil error could be returned for existing processes.
Probably using something like:
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)
}
But wondering if in all linux /proc/[pid]/stat
is always available or if by sending signal 0 kill -0 $PID
is basically doing exactly the same thing.
At the end I can always fallback to kill -O $PID
but just wondering what posible solutions could be used (probably inotify) with the intention to avoid having to sleep on the loop mainly for not consuming to much CPU resources.