Question

I have to use fork() recursively, but limit the number of forked processes (including children and descendants) to (for example) 100. Considering this code snippet:

void recursive(int n) {
    for(int i=0; i<n; i++) {
        if(number_of_processes() < 100) {
            if(fork() == 0) {
                 number_of_processes_minus_one();
                 recursive(i);
                 exit(0);
            }
        }
        else
            recursive(i);
     }
}

How to implement number_of_processes() and number_of_processes_minus_one()? Do I have to use IPC? I tried to pre-create a file, write PROC_MAX into it and lock-read-write-unlock it in number_of_processes() but it still eat all my pids.

Was it helpful?

Solution

I suspect that the simplest thing to do is to use a pipe. Before you fork anything create a pipe, write 100 bytes into the write side, and close the write side. Then, try to read one byte from the pipe whenever you want to fork. If you are able to read a byte, then fork. If not, then don't. Trying to track the number of total forks with a global variable will fail if children are allowed to fork, but the pipe will persist across all descendants.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top