C program to demonstrate use of fork and wait system call in linux
/*Here we read a number from parent process send it to the child process and then child process calculates factorial of that number and returns to the parent process which then prints the final answer*/#include <sys/wait.h>#include <stdlib.h>#include <unistd.h>#include <stdio.h>main( ){int num;int fact=1;int pid, w=1;int status;printf("Enter any number....nn");scanf("%d",&num);printf("n");pid = fork();if (pid == -1) {printf("nError Occured in Forking a Process..n");exit(0);}if (pid==0) { /* Code executed by child */printf("nnChild PID is %ldnn", (long) getpid());/* Wait for signals */int i=0;if(num==0||num==1){fact=1;exit(fact);}else{for(i=1;i<=num;i++){fact = fact * i;//printf("fact= %d",fact);}printf("n Child Execution Completed...n");exit(fact);}}else {/* Code executed by parent */wait(&w);printf("n W= %d",w);int f=WEXITSTATUS(w);printf("nNow in parentnn");printf("nn Factorial of %d is %d ",num,f);}}
Output :
dell@linuxmint ~/practicals $ gcc shubham.c
dell@linuxmint ~/practicals $ ./a.out
Enter any number….3
Child PID is 3686
Child Execution Completed…
W= 1536
Now in parent
Comments
Post a Comment