Will this succeed in forking 10 times?

timeToFork = 10;

for(int i = 0; i < timesToFork; ++i) {
pid = fork();

if(pid == -1) {
perror("Failed to fork.");
exit();
}
}

After 10 times will I reside in the 10th process?
It generates 2^10 process, so it forks 2^10-1 times.

> After 10 times will I reside in the 10th process?
Yes, also in the 1st, the 2nd, the 3th, ... the 1024th
- The for loop will run 9 times, given pid is never equal to -1.

- I don't understand what your (fork) function does, so i really can't say more than that.
$ man fork
The fork() function shall create a new process. The new process (child process) shall be an exact copy of the calling process (parent process) except (...)


@thejman250: in the first process, the loop will run `timeToFork' times, so 10
So in total will I have ten process or will each new process create a process as well? How can I end up with exactly ten processes?
@thejman250: in the first process, the loop will run `timeToFork' times, so 10


- I'm pretty sure it's nine, unless the fork function affects "i" somehow.

- ++i is quite different from i++
> will each new process create a process as well?
Yep

> How can I end up with exactly ten processes?
¿you are creating for the heck of it?


> ++i is quite different from i++
As long as you don't use the returned value, they are equivalent.
As long as you don't use the returned value, they are equivalent.


- They are not equivalent at all. one updates before the loop starts, and one after.

- They are completely different in this case, as "i" is being used in order to continue the for loop.
To spawn exactly 10 child processes, determine parent process PID and break the loop if you are in the child, like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
timeToFork = 10;

int mypid = getpid();
for(int i = 0; i < timesToFork; ++i) {
if (getpid() != mypid)
    break; // we are the child, abort


pid = fork();

if(pid == -1) {
perror("Failed to fork.");
exit();
}
}
Last edited on
if `pid' is 0, then you are in the child.

@thejman250: http://cplusplus.com/doc/tutorial/control/
So I could say if(pid == 0) break?
Topic archived. No new replies allowed.