How many lines will the following codes print out, and why?

main() {

fork();

printf ("Hello!\n")

fork();

printf("Good Bye!\n");

} // main

What's the fork() doing here? Does it change the number of lines that will be output?

The purpose of fork() system call is to create a new process, which becomes the child process of caller, after which both, the parent and child processes, will execute the code following the fork() system call. Hence, it is important to distinguish between parent and child process. This can be done by testing the return value of fork() system call.

I'm not yet understanding how to apply that to the example above. So unds like it would be 4 lines.

And another example:

How will the following code fragment affect stdin, stdout and stderr? Can somebody please explain to me what's behind this?

int fda, fdb;
fda = open("alpha", O_RDWR | O_CREAT, 0640);
fdb = open("beta" , O_RDWR | O_CREAT, 0640);
close (2);
dup(fda);
close(0);
dup(fdb);

Help is appreciated!

You can consider fork as creating an exact mirror of the executing process. That is, everything that is happening after the fork will also be happening in the created process (unless control flow logic is introduced). Consider the following diagram of your code sample:

// Assume process id is 1 when main is entered 
// and increases by 1 on each fork call

  (call main)
       1
       |        (call fork)
   +---+---+
  (1)     (2)
   |       |    (call printf - 2x)
   |       |    (call fork)
 +-+-+   +-+-+
(1) (3) (2) (4)
 |   |   |   |  (call printf - 4x)

Each vertical line represents a path of execution through the main code. As each printf is reached it is executed by each vertical line that passes through that point in the code.

This article has been dead for over six months. Start a new discussion instead.