Create A Child Process Using Fork()
Create A Child Process Using Fork() Source Code: #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> int main() { int status,i; pid_t pid; pid=fork(); if(pid<0) { printf("Fork failed "); } else if(pid==0) // for child process { for(i=0;i<=5;i++) { printf("\nChild %d",i); sleep(2); } printf("\nChild terminated \n"); } else { for(i=0;i<=5;i++) { printf("\nparent %d",i); sleep(1); } printf("\nParent terminated \n"); waitpid(pid,&status,0); // parent process wait for the child with pid to complete } return 0; } OUTPUT: [cmsa4@localhost ~]$ cc forking.c -o i [cmsa4@localhost ~]$ ./i parent 0 Child 0 parent 1 parent 2 Child 1 parent 3 parent 4 Child 2 parent 5 Parent terminated Child 3 Child 4 Child 5 Child terminated ------------------------------------------------------------- Now,if we delete the line "waitpid(pid,&status,0)" from the parent part of the program,then the output will be something like this: [cmsa4@localhost ~]$ cc forking.c -o i [cmsa4@localhost ~]$ ./i parent 0 Child 0 parent 1 parent 2 Child 1 parent 3 parent 4 Child 2 parent 5 Parent terminated [cmsa4@localhost ~]$ Child 3 Child 4 Child 5 Child terminated this example illustrates that after the parent process terminates, bash shell returns. Bur still,the child process works under 'init' and completes execution. Thus, if parent process terminates,child process may execute..
Tags:
Shell Script
0 comments