Amount of processes

Do I understand correctly that 2 processes are created in the code below? Since one fork () call creates one thread. There are two such calls in the code, therefore, the process is created 2?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <stdio.h>
#include <stdlib.h>

int main() {

    int x,y;
    pid_t pidl, pid2;

    x = 2;
    y = 3;

    printf ("Single process, x=$d\n",x);
    pidl = fork();
    if(pidl == 0) {
      printf ("New, x=%d\n",x);
      exit (0);
    }
    if(pid1 < 0){
       printf("Cannot create");
       exit (1);
    }
    pid2=fork();
    if(pid2 == 0) {
       printf ("New, y=%d\n",y);
       exit (0);
    }
    if(pid2 < 0){
      printf("Cannot create");
      exit (1);
    }
    return 0;
}
There are actually 3 processes (4 if you count the parent). The parent does indeed fork twice, however the first child will also call fork. So you end up with a process tree like:

1
2
3
4
5
parent
  \__ child 1
   |   \__ sub-child 1
   |
    \__ child 2


Also, just as a side note, forking used to be a threading method, but these days (to the best of my knowledge) its not a commonly used model for threading anymore.
Thank
I think it's different. fork() returns 0 to the child and the pid (or error indication) to the parent.

So after line 13, the child executes line 15 and then exits at line 16. The parent continues on to line 18

After line 22, the child executes line 24 and exits at line 25. The parent continues to line 27.

Ideally you should call join() to get the status of the child procs. Otherwise eventually init will get them.
Topic archived. No new replies allowed.