Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output on a fork call in C [duplicate]

Tags:

c

fork

I encountered this in my school work and it didn't produce what I thought it should:

int main() {
    printf("c");
    fork();
    printf("d");
}

I know there are several things that aren't good about this code (i.e. no parameters in main, no variable for the return value from fork, no return statement at the end, etc.), but this is how it was presented and it's not relevant to my question anyway.

This code produces the output:

cdcd

It was my understanding that when fork is called, both parent and child would resume/begin on the line after the fork call. Based on that, I would have expected the output to be:

cdd

Assuming, of course, that the fork call is successful. Can anyone explain to me why that "c" is printed a second time even though it's on the line before the fork call?

Thanks! M_MN

like image 823
M_MN Avatar asked Nov 19 '25 00:11

M_MN


1 Answers

You forked your program before flushing stdout (i.e.: data was still in the output buffer). Just call fflush(stdout) to fix it:

❯ cat test.c
#include <stdio.h>
#include <unistd.h>

int main() {
    printf("c");
    fflush(stdout);
    fork();
    printf("d");
}

[22:14:01]~/devel
❯ clang test.c -o test
[22:14:07]~/devel
❯ ./test
cdd[22:14:09]~/devel
like image 164
JuanR Avatar answered Nov 20 '25 14:11

JuanR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!