Chris Jefferson
Chris Jefferson

Reputation: 7157

How to find number of children of a process in C?

I am doing quite a lot of forking in a process (and the children of that process are further forking), and I want to keep an acceptable limit on the total number of processes I create.

Is there a (preferably efficient) way of finding the total number of children of a process (including children of children, children of children of children, etc.) from C?

I would like my code to work on both linux and mac, so no /proc I'm afraid!

Upvotes: 1

Views: 2777

Answers (4)

Phil Miller
Phil Miller

Reputation: 38118

You could open up a pipe or socket in the root process, and have each child write to it when they're created and when they exit. If you want to limit the total number of descendant processes, you could have children check with the root process before they fork, rather than notifying it after.

Upvotes: 0

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.

Upvotes: 1

datenwolf
datenwolf

Reputation: 162164

There is no portable API to do, what you're asking for. C itself doesn't even define the concept of processes and the process management APIs of an operating system are very specific and usually not portable.

Either you find a portable abstraction library for what you want to do, or you implement it yourself.

Upvotes: 1

LearningC
LearningC

Reputation: 3162

check this. if you can create a variable shared between all processes then you can moniter the number of processes based on that shared counter value.
even this answer can help you in creating a shared variable.

Upvotes: 0

Related Questions