In: Computer Science
How many times should the following C code print "Example" and draw a process graph
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void try()
{
fork();
printf("Example\n");
fork();
return;
}
int main()
{
try(); fork();
printf("Example\n");
exit(0);
}
Fork calls help in creating new processes which we call as child process.
It runs simultaneously with the process making fork call. Once the child process is created than both processes will execute the next instruction following the fork call.
It takes no parameters and returns integer value.
Three values that are returned by fork() as as follows: .
The above mentioned program returns " Example" 2 times.
No. of times ‘example’ is printed equal to the no. of process created.
Total Number of Processes = 2n, where n is no. of fork system calls therefore, 21 = 2.
Explanation:
fork() methods in the try() will not return anything since the return type of the try() is void. So the fork() methods present in the main() will run and it will create a child process and run.
Process Graph:
P0 ( Main Process )
|
P1 ( Process Created by Fork())