Search code examples
cforkwait

fork() not waiting for child


I thought wait paused the main execution untill child process finished.


The following is what I was expecting to see in the console.

I am the parent with id 12833 <- parent

I'm calling first with id 0 <- child

I'm calling first with id 12833 <- parent after wait()


Instead I see this... #console output

I am the parent with id 12833

I'm calling first with id 12833

I'm calling first with id 0


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char* argv[])
{

    int id = fork();

    if(id!=0){
        //
        printf("I am the parent with id %d\n",id);
        wait(); //my code has no respect for wait()
    }

    printf("I'm calling first with id %d\n",id);


    return 0;
}

Solution

  • My output is

    I'm calling first with id 0
    I am the parent with id 29807
    I'm calling first with id 29807
    

    You should not rely on buffered outputs. Check returned values of wait.

    int main(int argc, char* argv[])
    {
        int id = fork();
    
        if(id!=0){
            printf("I am the parent with id %d\n", id);
            int wstatus = 0;
            if (wait(&wstatus) != -1) //my code has no respect for wait()
                printf("I am the parent with id %d and my child exited\n", id);
        }
        else
        {
            printf("I'm child\n");
        }
    
        return 0;
    }
    

    The output is again is not what you would expect due to buffered outputs.

    I'm child
    I am the parent with id 18057
    I am the parent with id 18057 and my child exited
    

    If you flush the output buffers, you get the desired output:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <unistd.h>
    
    int main(int argc, char* argv[])
    {
        int id = fork();
    
        if(id!=0){
            printf("I am the parent with id %d\n", id);
            fflush(stdout);
            int wstatus = 0;
            if (wait(&wstatus) != -1) //my code has no respect for wait()
            {
                printf("I am the parent with id %d and my child exited\n", id);
                fflush(stdout);
            }
        }
        else
        {
            printf("I'm child\n");
            fflush(stdout);
        }
    
        return 0;
    }
    

    Outputs

    I am the parent with id 21487
    I'm child
    I am the parent with id 21487 and my child exited