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.