0

So, I'm learning gcc and I was doing a few tests, the first thing i noticed is that this code:

int pid = getpid();
printf("\nPid iniziale %d",pid);
pid = fork();

outputs:

Pid iniziale 1572Pid iniziale 1572

instead of:

Pid iniziale 1572

Why is that? Also it doesn't even calculate the \n I need to do that for homework but I can't even get past that, because of that double output, I have some written code after but it changes nothing and i did those tests without comments.

epiclol
  • 9
  • 1

1 Answers1

1

The child process is getting forked with the "\nPid iniziale %d" still in the buffer since there is no newline at the end of it, causing this behavior, as both child and parent will print this at some point when they decide to flush their buffers themselves

    int pid = getpid();
    printf("\nPid iniziale %d",pid);
    fflush(stdout); 
    pid = fork();

or simply

    int pid = getpid();
    printf("\nPid iniziale %d\n",pid);
    pid = fork();

solves your issue

  • 1
    Note that the latter only works if stdout is line-buffered, which is generally not the case if it has been redirected to a file. Safer to always explicitly fflush before a fork – Chris Dodd Oct 13 '21 at 17:59