0

fork() is used to create a child process...and you see this call appear in the child process as well. I don't understand what it means when they say that 'calls to fork actually return twice'.

And what does this mean...

if (fork() == 0)
/* the child process's thread executes here*/

else 
/*the parent process's thread executes here*/

Is the above code part of parent or child. Can you explain in plain English what's going on?

Also, why use a fork()? It says all processes in unix run by this system call? How do you fork() so other programs can run? Do you specify the name of the program?

Naz
  • 67
  • 1
  • 1
  • 3

2 Answers2

1

What the mean when they say it returns twice is that the call returns once in the parent process (which called it), and once in the child process (which didn't, although you could probably argue that the child inherited the act of calling fork from the parent just like it inherited so much else).

The code snippet takes advantage of the fact that get a different return value from fork depending on whether you're the parent process or the child process.

The child process gets zero and the parent process gets the non-zero process ID of the child.

You can also get back -1 if the fork fails for some reason, in which case the child won't be running. That's something you should probably check as well.

And, while fork is used to create new processes, it's the exec family of calls which load new programs into those processes: fork on its own cannot do that.

A good overview of the process can be found here.

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

It's a bit like this:

Process 1               Process 2

int main() {
  ...
  int x = goo();
  ...
  int y = fork();
  // fork() returns...    // ... but also here!

  // here y = 123         // here y = 0
  if (y) {                if (y) {
    // this happens         // false
  } else {                } else {
    // false                // this happens
  }                       }

  int z = baz();          int z = baz();
  ...                     ...
  return 0;               return 0;
}                       }

When Process 2 comes to life, the program exists twice, and the second process starts with the return of fork(). Since the program is the same in both processes, the only way to distinguish which process you're in is by the return value of fork().

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084