Reputation: 41
I have a code as below
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("a\n");
fork();
printf("b\n");
if(fork() == 0) {
printf("c\n");
exit(0);
}
printf("d\n");
return 0;
}
Output :
a
b
d
a
b
c
a
b
d
a
b
c
I don't know why the output duplicated many times.
Upvotes: 3
Views: 778
Reputation: 844
When you call fork()
it gets a copy of output buffer of the calling process. Buffering is enabled by default, so you get this behavior.
You can use
fflush(stdout);
before a call to fork(). Or, you can also disable buffering using
setbuf(stdout, NULL);
You can read more about fork here. Let me know if you need any more help.
Upvotes: 4
Reputation: 71
The answer is already in the comments. You are calling fork()
twice. So the solution is to just call it once and save the result in a variable like this int pid = fork()
. Also, you should check if the fork-call failed (if it does, it returns a negative value).
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("a\n");
int pid = fork();
if (pid < 0)
{
fprintf(stderr, "Can't fork!");
exit(1);
}
printf("b\n");
if(pid == 0)
{
printf("c\n");
}
else
{
printf("d\n");
}
return 0;
}
Upvotes: 1
Reputation: 24738
I don't know why the output duplicated many times
Because printf()
is buffered.
When a process calls fork()
, the resulting child process obtains a copy of the parent's output buffer.
You can empty this output buffer by placing fflush(stdout)
just before each call to fork()
. In that case output should be:
a
b
b
d
c
d
c
Note that if the output refered to a terminal, it would be line-buffered by default, i.e.: the buffer would be dumped every time a \n
is sent to the output. Not so if you are redirecting the output to a file.
Upvotes: 8