It's unexplainable...

Matthew E Cross profesor at wpi.WPI.EDU
Thu Jan 31 23:13:42 AEST 1991


In article <peterj.665303644 at zeus> peterj at swanee.ee.uwa.oz.au (Peter Jones) writes:
>In <1991Jan30.203605.14481 at bronze.ucs.indiana.edu>
>    speelmo at bronze.ucs.indiana.edu (Lance Speelmon - UCS) writes:
>
>>Would anyone please explain to me why my output is not what I am expecting...  
>>% cat foo.c
>>#include <stdio.h>
>
>>void main(void){
>>  printf("The date is: ");
>>  system("date");
>>  printf("\n");
>>}
>>% a.out
>>Wed Jan 30 15:16:17 EST 1991
>>The date is: 
>
>There are two processes running here, one is the "foo" program and the
>other is the "date" program.  It will depend on the scheduling what actually
>happens - I guess.  It would need "foo" to either flush its output buffer
>or to do an input or to write to "stderr" (& not be buffered).

No, no, no. Well, OK, there are two processes, but nothing depends on
the scheduling.  "foo" will run, start the subprocess "date", which
runs and finishes, then "foo" will continue.

What causes this is the line buffering of the stdio functions.
Whenever you print anything, it goes into a buffer, until you send a
'\n' character, when the routines receive a '\n' character, they flush
the output buffer.  (this is also why 'getchar()' won't to anything
until you hit a return, it waits to flush the buffer).  Also, the
"date" program prints a newline before it prints the date.

To avoid the line buffering, you would have to use 'setbuf()' or
something like it.

-- 
+-------------------------------------+---------------------------------------+
| "The letter U has a lot of uses ... |       profesor at wpi.wpi.edu            |
|  I like to play it like a guitar!"  +---------------------------------------+
|          -Sesame Street             |       Make love, not War..            |



More information about the Comp.lang.c mailing list