Small fork program in c (\n not clear for me)

med89med

New Member
Joined
Apr 4, 2021
Messages
5
Reaction score
3
Credits
62
Hello ,
im using this easy script :

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

void main(void) {
printf("Bonjour1 ");
int pid = fork();
printf("pid %d.\n", pid);
if (pid == 0) {
printf("I am the child.%d.\n", getpid());
}
if (pid > 0) {
printf("I am the parent, %d.\n", getpid());
}
if (pid < 0) {
perror("In fork():");
}
exit(0);

}
The result is :

Bonjour1 pid 5447.
I am the parent, 5446.
Bonjour1 pid 0.
I am the child.5447.

All its OK. but i wanted to insert a line break after the world "bonjour" by using (\n)
so when i replace printf("Bonjour1 "); by printf("Bonjour1 \n"); i have this result :

Bonjour1
pid 5503.
I am the parent, 5502.
pid 0.
I am the child.5503.

I dont have the second "bonjour" of children process.

Can you explain to me why ?

thanks
 


JasKinasis

Well-Known Member
Joined
Apr 25, 2017
Messages
1,318
Reaction score
1,870
Credits
8,314
When you create a child process using fork, it uses the same variables and registers as the parent process.
Without the \n newline in the first printf, the stdout buffer contains the unterminated string "Bonjour1".
So the stdout buffer in the child process also contains the unterminated "Bonjour1".

When you added the newline, that string is terminated and so stdout is pointing to the next line and is empty. Which is why the parent process displays "Bonjour1", but the child process does not.

Basically that string was terminated in the parent process before the child process was created.

To get the output how you want it, you’d need to make the fork call before the first printf.
 
$100 Digital Ocean Credit
Get a free VM to test out Linux!

Members online


Top