(a) Give the syntax of fork() system call including return values on success and failure. (b) Write a complete C-function void creatree(int n); that create a process tree with main process at level 0 and all children at level 1. You can use pause() system call if needed.
(a) Fork() system call can be simply used like in the example given below -
int main(){ //code fork(); //code }
Fork() takes no parameters and returns an integer value. negative value - child creation was unsuccessful zero - it is returned to the child process positive value - returned to the parent. Contais the pid of newly created child.
(b) The following example will take n as an input from the user and will create n child processes which will have main function as their parent process.
#include<stdio.h>
void creatree(int n)
{
for(int i=0;i<n;i++)
{
if(fork() == 0)
{
printf("[son] pid %d from [parent] pid
%d\n",getpid(),getppid());
exit(0);
}
}
}
int main()
{
int n;
printf("Enter the number of child processes to be created");
scanf("%d",&n);
creatree(n);
for(int i=0;i<5;i++)
wait(NULL);
}
Get Answers For Free
Most questions answered within 1 hours.