Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in c system() executes before printf() even when printf come first [duplicate]

Tags:

c

linux

gcc

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?

like image 996
Blue Avatar asked Nov 21 '25 11:11

Blue


1 Answers

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'.

like image 178
PSkocik Avatar answered Nov 23 '25 00:11

PSkocik