Exercising the fork system function

Here's a sample program from a textbook. Note that it is a "fork sandwich" containing 3 slices of ham ( fork( ) ) between two slices of rye ( printf( ) ).


/* forkdemo2.c - shows how child processes pick up at the return
*    from fork() and can execute any code they like,
*    even fork(). Predict number of lines of  "my pid is..." output.
*/

main()
{
printf("my pid is %d\n", getpid() );
fork();
fork();
fork();
printf("my pid is %d\n", getpid() );
}


Put this code into a file named forkdemo2.c. Then compile and run it:

gcc  forkdemo2.c  -o  forkdemo2
./forkdemo2

Answer the question in the comment (number of lines of "my pid is..." output), by observation.

Now make 3 other versions of this sandwich, with 1, 2, and 4 slices of fork( ) between the printf( )'s. See how many lines of output each produces. Make a table to record the results.

Number of fork( ) calls Number of lines of "my pid..." output
1  
2  
3  
4  
n  

Think about why you observed this result. (While counting the lines, look also at the process id numbers they report.)


To turn in:

Tell me the expression in your table's last line giving the number of lines as a function of the number "n" of fork( )'s. Write it, manually or electronically, and upload the expression in a file named "forkdemo2.pdf" or .jpg or .png that will be legible to me.