0

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;
}
Jay
  • 111
  • 10
  • 5
    There is no such function `pid_t wait(void)`. Look at man wait: `pid_t wait(int *wstatus)`. – 273K Jan 24 '21 at 17:20
  • 1
    And you have to include `` to get it. – Nate Eldredge Jan 24 '21 at 17:38
  • Probably not the issue, but `fork()` returns `pid_t`, not `int`. You'll then have to adjust the `printf` accordingly, see https://stackoverflow.com/questions/20533606/what-is-the-correct-printf-specifier-for-printing-pid-t. – Nate Eldredge Jan 24 '21 at 18:00
  • @NateEldredge it was a combination of and passing the right parameters to the wait function as S.M showed – Jay Jan 24 '21 at 18:13

1 Answers1

2

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
273K
  • 29,503
  • 10
  • 41
  • 64