Fork ( ) system call for execution of parent and child process
#include<stdio.h>#include<sys/types.h>
#include<unistd.h>
int main()
{
// make two process which run same
// program after this instruction
fork();
printf("Hello world!\n");
return 0;
}
OUTPUT
Here we can see same program & code for both parent and child processes . in this program fork ( ) is the parent process that create a new child process . After new process is created both parent and child follow the next instruction exactly following the fork ( ) statement which is here " printf("Hello world!\n"); ".
This is the reason we got same output twice each for a process .
Now let's try another program for more clear understanding of the concept of Fork ( ) system call and child process creations.
Count no of times hello is printed
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
fork();
fork();
fork();
printf("hello \n");
return 0;
}
#include<sys/types.h>
#include<unistd.h>
int main()
{
fork();
fork();
fork();
printf("hello \n");
return 0;
}
OUTPUT
fork ( ) system call (Same program & different code for parent and child)
#include<stdio.h>
#include <sys/types.h>
#include<unistd.h>
void forkexample( )
{
// child process because return value zero
if (fork()==0)
printf("Hello from Child!\n");
// parent process because return value non-zero.
else
printf("Hello from Parent!\n");
}
int main()
{
forkexample();
return 0;
}
OUTPUT :
0 Comments