There is no way to enumerate all the children of a process, except by enumerating all the processes of the system and checking their PPID. (Of course, from the parent itself, you can just keep track of what you fork.) There is no way at all to enumerate all the descendants of a process: if P forks Q forks R then Q dies, there is no more information to relate P with R.
The portable way to obtain information about processes is to call the ps
utility and parse its output.
If you want to limit the number of descendants of a process, you can do it easily by using a dedicated user to run that process, and starting the ancestor with the desired limit on processes per user (setrlimit(RLIMIT_NRPROC, …)
).
You can also use a shared resource of some kind; this will work as long as the descendant processes don't close that resource. For example, you can open a file (without the O_CLOEXEC
flag), if the descendants don't call fcntl
with the FD_CLOEXEC
flag on that file nor just go and close it. I think that on OSX you'll need to fork fuser
or lsof
(either will work on Linux too) to find out how many processes have the file open, I don't know of a way to do that without forking on OSX. You might investigate other mechanisms such as shared memory (shm_open
and friends) or memory mappings (mmap
and friends), but for these I don't know of a way to get the use count without forking either.