Shay
Shay

Reputation: 617

`waitpid` a process that was already `waitpid`ed

I was playing around with fork and signals on a Ubuntu VM. Specifically, I tried forking to spawn a child process and then, from the parent process, send a SIGTSTP to that child. After this point, I tried querying for its status using waitpid twice – to my man-owed understanding, the wait family of functions only reports changes to the status; that is: changes with respect to the last call to a function of that family for this PID. And indeed, the second call to waitpid did not report that the child had stopped (and its return value was 0 instead of the child's PID).

(To clarify: I used waitpid with WUNTRACED and the child's PID, being fork's return value, as the first parameter.)

I was wondering: is there a way for me to query for a child process's status regardless of any previous calls to wait-likes, without invoking external binaries like ps, or would I theoretically have to maintain some kind of state for each child myself?

To rephrase, just in case my phrasing is confusing: let's say I spawn a bunch of child processes, and I want to monitor which of those are still running, which have stopped (via SIGTSTP or SIGSTOP), and which have terminated. I could maintain state myself (for instance using a SIGCHLD handler), but I wanted to try using the OS to do this for me (I had the idea that this was indeed being done due to, for instance, ps displaying the status of each process in the system – so I wanted to access it). The first and last are simple to monitor using a kill(pid, 0) call, but the second – whether a process has stopped – seems to be trickier to query for. How might one go about this?

Upvotes: 0

Views: 65

Answers (1)

thejh
thejh

Reputation: 45578

You can use the same interface that tools like ps would use: Read the contents of the file /proc/[pid]/stat (see the proc.5 manpage). The third field is a single letter indicating the process state - for example, T means "Stopped on a signal" and t means "Tracing stop" (stopped because of ptrace()).

Note that you can normally only monitor the status of a process until the process is "reaped" via a waitpid() call that indicates that the process has been terminated. After that point, the process can disappear, and the PID can be reused by a completely unrelated process.

Upvotes: 1

Related Questions