orpqK
orpqK

Reputation: 2785

forks and its functionality?

I have the following code and am asked to how many times "A", "B", "C", "D", "E" will be printed

fun() {
  printf("A");
  fork();
  printf("B");
  if (fork() != 0) {
     printf("C");
     fork();
     printf("D");
  }
  printf("E");
}

so it should be:

A
A 
B
E

im not sure if my answer above is correct? and what the line if(fork() !=0 ) do?

Upvotes: 3

Views: 113

Answers (3)

xaxxon
xaxxon

Reputation: 19761

1 thread prints a, 2 threads print b. each of the 2 forks, but only the 2 parents go into the if statement and print c. Each of those two fork and all 4 procs print d. Then, each of the 6 procs (two children from if-fork and 4 threads coming out of if print e.

You can't determine the order, but the number of each letter is:

A x1

b x2

c x2

d x4

e x6

Upvotes: 4

theabraham
theabraham

Reputation: 16370

The line if (fork() != 0) { ... } is checking to make sure the current process is not a child of the original forking process. Only the parent process will execute the code in this block.

This works because fork() returns a PID in the parent process, a 0 in the child process, and -1 on error.

Upvotes: 2

koopajah
koopajah

Reputation: 25552

From the documentation:

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

Upvotes: 6

Related Questions