I'm learning fork() function under linux recently. I wrote a program.
#include<stdio.h>
int main(){
int p1, p2;
while((p1 = fork()) == -1);
if(p1 == 0)
printf("b");
else{
while((p2 = fork()) == -1);
if(p2 == 0)
printf("c");
else
printf("a");
}
}
After I compiled and run it, I got a unexpected percent sign.
But if I add \n after those letters, the percent sign disappears.
Is there anyone knows the reason?
And I have another question. Every time I reran the program, I got the same answer. It always shows "acb". The order is always the same. Why?
Your shell (zsh) added it to indicate the output did not end with a newline character.
To get rid of it, just end your output with a \n
.
As to the other question, it's not deterministic. If you ran it elsewhere or enough times you might get different results. But it's an illustration of why synchronization problems can be so hard to find, because things can seem to run the same (almost) all the time.