1

I have a small problem with this:

{
  printf ("abc");
  execl("./prog","prog",NULL);
}

All works fine, but why does execl just run before printf? Could someone help me?

alk
  • 69,737
  • 10
  • 105
  • 255
wienio
  • 13
  • 4
  • 3
    Try `printf ("abc"); fflush(stdout);` – Marian May 28 '16 at 15:36
  • OT: It should be `execl(..., (char*) NULL);`. – alk May 28 '16 at 15:39
  • 1
    Line buffering: the output from `printf()` is not forced out unless you turn on no-buffering (add a newline and it would usually appear; pipe the output of the program and even a newline won't help, but `fflush()` will). The functions in the [`execl()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/execl.html) family of functions do _not_ flush the standard I/O buffers of the invoking program. – Jonathan Leffler May 28 '16 at 15:42
  • The question [`printf()` anomaly after `fork()`](https://stackoverflow.com/questions/2530663/printf-anomaly-after-fork) covers most of the ground you need to know about in a slightly different context. – Jonathan Leffler May 28 '16 at 15:47

1 Answers1

6

The printf actually does run first, however it's output is buffered.

You can flush the buffer either by adding a newline (\n) to the end of the string or by calling fflush(stdout):

 printf("abc\n");

Or:

printf("abc");
fflush(stdout);
dbush
  • 205,898
  • 23
  • 218
  • 273