-1

I have exercise in university.

Create a program that declares a variable n, forks a new process and prints “Hello from parent [PID - n]” and “Hello from child [PID - n]” from parent and child processes respectively. Run it 10 times and explain the output

I wrote this code

#include <stdio.h>
#include <sys/types.h>

void main()
{
    pid_t n = getpid();
    printf("Hello from parent [PID - %d], n);
    fork();
    n = getpid();
    printf("Hello from child [PID - %d], n);
}

But after compilation and execution i get this

Hello from parent [PID - 10135]Hello from child [PID - 10135]Hello from parent [PID - 10135]Hello from child [PID - 10136]

The "Hello from parent ..." printed twice. But if i will change code printf statements a little

#include <stdio.h>
#include <sys/types.h>

void main()
{
    pid_t n = getpid();
    printf("Hello from parent [PID - %d]\n, n);
    fork();
    n = getpid();
    printf("Hello from child [PID - %d]\n, n);
}

(I've just added '\n' to each string) i would get

Hello from parent [PID - 10223]
Hello from child [PID - 10223]
Hello from child [PID - 10224]

And it works as it should. I've tried cc and gcc with -std=c99 flag but result stays the same.

I think that problem somewhere in printf function)

So, please explain me what happened, and why this works like this.

1 Answers1

1

This is because stdout is buffering the data, and flushing it only when newline is reached. so when you did not add a newline to the parent first print, it was not actually printed, but was buffered by the process. then buffer was flushed when the process (parent or child) exited.

see Why does printf not flush after the call unless a newline is in the format string?

for more details.

Eliyahu Machluf
  • 1,053
  • 7
  • 15