0726
0726

Reputation: 315

Why execution stops after printing "This is the child process!"?

//Why not execute all the conditions(parent and child)?
#include<stdio.h>
#include<unistd.h>

int main(){
        pid_t pid; //process-id
        printf("This is where we start...\n");
        pid = fork();
//For the child process
        if(pid==0){
                printf("This is the child process!\n");
                return 1;
        }
//This should have been printed
        if(pid>0){
                printf("This is the parent!\n");
        }
//THis may/may not be printed - its ok
        if(pid < 0){ 
                printf("Fork failed!");
        }
        return 0;
}

It was excepted that after returning from the child, the parent should have been executed but this is what i get: $ This is the child process!

What am i missing? why not child as well as the parent block printed?

Upvotes: 0

Views: 238

Answers (1)

Manish M Demblani
Manish M Demblani

Reputation: 910

The program is completely fine. When a fork is performed, a new child process is created. The child process created is independent of the parent and it is completely possible that the parent does not wait for the child to complete its execution.

If you want that the parent execution resumes once the child is complete, you should use the wait() function, that makes sure that a forked child is executed before parent continues.

Try updating your code as follows:

#include<stdio.h>
#include<unistd.h>
#include <sys/wait.h>  //Add this header

int main()
{
        pid_t pid; //process-id
        int status;  //A variable to get the status of the child, i.e. if error or success
        printf("This is where we start...\n");
        pid = fork();
        if(pid==0){
                printf("This is the child process!\n");
                return 1;
        }
        if(pid>0){
                wait(&status);   //Function to wait for child
                printf("This is the parent!\n");
        }
        if(pid < 0){ 
                printf("Fork failed!");
        }
        return 0;
}

For more information check out this link: Forking a Process and Parent-Child execution - Linux : C Programming

Upvotes: 3

Related Questions