How can I query if a service (dnsmasq) is running, in C?
+2
A:
According to the dnsmasq man page, by default it writes a pid file to /var/run/dnsmasq.pid
. This file will be a text file that contains an integer representing the process ID. Open the file, read the integer, and call kill(pid, 0)
to see whether the process is alive at that pid. (Although checking for PID existence isn't guaranteed to not find some other process running at that PID, it's usually good enough.)
Greg Hewgill
2010-10-04 03:36:52
+1 for the `kill(pid,0)` trick :-)
jweyrich
2010-10-04 03:38:23
If I do `kill(pid, 0);` once I've read the pid, would the result be `0` for it existing, and `-1` for it not?
Delan Azabani
2010-10-04 03:53:04
@Delan Azabani: That's correct.
Greg Hewgill
2010-10-04 04:21:57
Interestingly, though that's true, my experience is different. This is because I'm not root. As expected, if it's not running, calling `kill(pid, 0)` returns `-1` and `errno` is `ESRCH`. However, if it is running, it still returns `-1`, and `errno` is `EPERM`. When as root, a running dnsmasq returns `0` as per your answer when a blank signal is sent.
Delan Azabani
2010-10-04 04:42:53