3

I just started using the system() function in c, and I thought of starting the same executable from within it self using the system function, so I wrote the following program

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

int main()
{
    printf("some string");
    system("./a.out");
}

-I used gcc to compile it-

when I ran the program it did not print anything, it just kept going until I used the shortcut ctrl-c to stop the execution,then it started printing the output(it did not print anything until I stopped it)

I believe the statements should execute sequentially, why did it not print anything until I stopped it?

Blue
  • 33
  • 3
  • 4
    `system` is using `fork` under the hood. And the output of `printf` is buffered and can get flushed at any moment - before or after executing the child. Flush it explicitly by adding `\n` or usng `fflush(stdout)` if the order is important.. – Eugene Sh. Mar 22 '19 at 14:03
  • 1
    The output stream is buffered, so the text you print may not appear until you flush the stream or the process exits. – Krzysiek Karbowiak Mar 22 '19 at 14:05
  • ty for the explanation. – Blue Mar 22 '19 at 14:09
  • [printf anomaly after "fork()"](https://stackoverflow.com/q/2530663/995714), [why does "printf" not work?](https://stackoverflow.com/q/39180642/995714) – phuclv Mar 22 '19 at 15:20

1 Answers1

6

By default, when stdoutis connected to a terminal, it is line-buffered.

printf("some string");

doesn't have a '\n' in it and you aren't calling fflush(stdout); after it either, so all this printf("some string"); does is copy "some string" into your stdout's output buffer.

The buffer is flushed as the end of main.

printf("some string\n"); would flush the buffer immediately, provided stdout is connected to a terminal and you didn't change stdout's buffering.

printf("some string"); fflush(stdout); will flush the buffer immediately regardless of context and without the need for the '\n'.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • I think it is important to explain why the output reordering it is happening with `system` but not with some other functions. – Eugene Sh. Mar 22 '19 at 14:22