/* PROCESS FORKING In Linux we have multiple processes executing at the same time. This program illustrates the fork() system call which creates a new child process of the calling process. Go through the comments carefully before you compile and execute the program. */ #include #include /* You must include this file for all activities related to creation and interprocess communication. IPC stands for Inter-Process Communication */ /* When the program begins executing from main(), it is a single process having a single process identifier (PID). When the fork() call is executed, a new process with a new PID is created. THE CODE OF THE NEW PROCESS IS IDENTICAL TO THE PARENT PROCESS, AND THE VALUES OF ALL VARIABLES IS A COPY OF THE VALUES OF THE VARIABLES OF THE PARENT AT THE TIME OF THE fork() CALL. The PIDs of the currently executing processes and the PIDs of their parents can be seen by using the "ps -ef" command from the command prompt. */ main() { int i; printf("Now there is a single process\n"); printf("Observe what happens when we fork\n"); printf("You can stop by pressing Control-c\n"); printf("Press Enter to continue... \n"); getchar(); /* For the parent process, the fork() system call returns the PID of the newly created child process. On the other hand the newly created child process, whose execution starts from the fork() statement (that is, its control flow starts from the fork() statement) receives the value 0 as return value from the fork() statement. */ if (fork() == 0) { /* We are here only if fork() returned zero. Therefore, this part of the code is executed only by the child process. */ while (1) { for (i=0; i<100000; i++) ; /* Spending time */ printf("\t\t\t Child executing\n "); } } else { /* We are here only if fork() returned a non-zero value. Therefore this part of the code is executed only by the original (or parent) process. */ while (1) { for (i=0; i<100000; i++) ; /* Spending time */ printf("Parent executing\n"); } } }