I have this C code sequence:
printf("\nThe PID of this (main) process is: %d\n", getpid());
if(fork() != -1) { // #1
printf("\n\nParent 1 PID: %d\n", getpid());
for(int i = 0; i < 10; i++) {
printf("\n%d", i);
}
if(fork() != -1) { // #2
//sleep(1);
printf("\n\nParent 2 PID: %d\n", getpid());
for(char i = 'a'; i != 'f'; i++) {
printf("\n%c", i);
}
}
else { // #3
sleep(3);
printf("\n\nChild 2 PID: %d\n", getpid());
for(char i = 'F'; i != 'J'; i++) {
printf("\n%c", i);
}
}
}
else { // #4
sleep(4);
printf("\n\nChild 1 PID: %d\n", getpid());
for(int i = 10; i < 20; i++) {
printf("\n%d", i);
}
}
I expect that I will have 4 processes: two parents and two childs.
At line #1 I call fork()
for first time, and everything from line #1 to line #4 will be executed in first parent process.
In the parent process (1) I call fork()
one more time, so from line #2 to line #3 I will have the parent 2 process, and from line #3 to #4 child 2 process.
What I expect to be printed:
Parent 1 PID: ....
0
1
2
3
4
5
6
7
8
9
Parent 2 PID: ....
a
b
c
d
e
Child 2 PID: ....
F
G
H
I
Child 1 PID: ....
10
11
12
13
14
15
16
17
18
19
What I actually got:
Parent 1 PID: 3877
0
1
2
3
4
5
6
7
8
Parent 1 PID: 3878
0
1
2
3
4
5
6
7
8
9
Parent 2 PID: 3877
a
b
c
d
e9
Parent 2 PID: 3878
9
a
b
c
d
Parent 2 PID: 3879
a
b
c
d
e9
eParent 2 PID: 3880
a
b
c
d
e
What I do wrong?
This line isn't doing what you think:
if(fork() != -1) { // #1
That will succeed for both the parent and the child (as long as fork
is possible, which is almost always the case). You mean to test against 0 here. The parent will get 0, the child will get >0. -1 is an error.
In your case, what you've marked as the "child" legs should never be executed unless there are errors. I don't think that's what you meant. What you're seeing are the initial 2 (parent and child) forks plus 4 (parent+child * 2) second forks. That's 6 forks, which is what the output indicates.