user2971971
user2971971

Reputation: 183

Count number of processes created using fork in a for loop

I am trying to find a way to count the number of processes created in a for loop of length 10 with a fork() call. It is easy to see that the result is 2^n for n calls, but I need a way to compute it in the program.

I have found an almost identical question in here. However, when I tested the second solution given here, it works ok for a number of forks less than 10. For 10, it yelds 256. Why is that? And is there another solution to this problem? (apart from using pipes). Here is the actual code:

for(i=1; i<=10; i++) {
    fork();
    printf("The process with the PID=%d\n", getpid());
}

Upvotes: 1

Views: 4613

Answers (3)

Richard Conto
Richard Conto

Reputation: 78

I answered an awfully similar question posted on QUORA here: http://www.quora.com/For-I-0-I-3-I++-fork-how-can-I-make-an-algorithm-to-count-the-number-of-processes-and-display-it-only-once/answer/Richard-Conto

By not checking the result of fork(), you're indicating that you haven't checked the documentation for this system call. Please make some effort at understanding fork() first.

Upvotes: 0

John Bollinger
John Bollinger

Reputation: 180201

There is only one byte for the exit status of a process. Therefore, you cannot count higher than 255 via process exit codes. Furthermore, it is a quirk of the specific algorithm you tried that it happens to produce exactly the maximum possible exit status (to which the parent process adds 1 to get 256). The exit() function just uses the least significant 8 bits of its argument (and returning x from main() has the same effect as calling exit(x)).

To count higher, you need a different approach. You could establish a counter in shared memory, and have each child process increment it (with appropriate synchronization). That runs cleanly, but shared memory is not trivial to work with. You could also have each process append to a file to leave a record; the parent process could then read the file to count how many processes left such a record.

Upvotes: 2

QuestionC
QuestionC

Reputation: 10064

Something may be limiting the program to 256 processes. Check the return value of fork(), don't just assume it succeeds each time.

What happens when you run ulimit -u on the command line?

Upvotes: 0

Related Questions