Francesco Bonizzi
Francesco Bonizzi

Reputation: 5302

What happen with this code about process creation in C with fork()

I was trying to create 5 processes with fork(), to do some tests in order to understand that function. I have done:

int f0, f1, f2, f3, f4;

  switch (f0 = fork()) {
  case (0):
    foo(f0);

    exit(0);

  case (-1):
    printf("\nError!");
    exit(-1);

  default:
    wait();
  }

  switch (f1 = fork()) {
  case (0):
    foo(f1);

    exit(0);

  case (-1):
    printf("\nError!");
    exit(-1);

  default:
    wait();
  }

  //...same for f2,f3,f4

I don't really understand processes here. What's happening? Processes are really created one time each? Everytime I use fork() a new process is created and it begins from the beginning of the code as a copy of the father?

Also, my mind suggest me that it maybe instead something like:

if (f0 = fork() != -1)
  foo(f0);
else if (f1 = fork() != -1)
  foo(f1);
...

But I don't really understand the differences.

Upvotes: 0

Views: 61

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

This piece of code is troublesome:

if (f0 = fork() != -1)
  foo(f0);
else if (f1 = fork() != -1)
  foo(f1);

The reason, except the forking problems, is because of the operator precedence of C, which says that the comparison is done before the assignment, which means that f0, f1 etc is assigned the value of the comparison and not the new process id.

You need to use parentheses, like this:

if ((f0 = fork()) != -1)
  foo(f0);
else if ((f1 = fork()) != -1)
  foo(f1);

Upvotes: 1

NPE
NPE

Reputation: 500157

Everytime I use fork() a new process is created and it begins from the beginning of the code

No, both the parent and the child process continue execution from exactly where the parent left off (but receive different return values from fork()). In other words, they both execute the statement that immediately follows the fork().

As to your other suggestion:

if (f0 = fork() != -1)
  foo(f0);
else if (f1 = fork() != -1)
  foo(f1);
...

There are two problems:

  1. There are three cases: (1) I'm the parent; (2) I'm the child; (3) there's been an error. Your if statements only handle two of those cases.
  2. The original code calls wait() so that the parent waits for the child to terminate. Your version does not do that.

Upvotes: 2

Related Questions