问题
I'm a newbie, trying to really understand systems programming. In the following program, I'm reading a file called 'temp1' (containing 1 2 3 4) and printing its contents to stdout. However, I also wanted to check the value of file descriptor returned by open. If I include the '\n' in printf call on line 5, the output prints value filep first and then contents of file. But if I remove the newline, the contents of file get printed first and then the value of filep. Why would this happen ?
int main(){
char buf[BUFSIZ];
int n, filep;
// Open the file
filep = open("temp1", 'r');
printf("%d\n", filep); // the newline alters program behaviour
while((n=read(filep, buf, BUFSIZ)) > 0)
write(1, buf, n);
return 0;
}
I am using gcc 4.6.3.
回答1:
<stdio.h>
functions like printf
are buffered. Output functions will call the write(2)
syscall only from time to time, usually output functions like printf
etc... are going only into the internal FILE
buffer.
The stdout
is line-buffered when outputting to a terminal (see isatty(3)). So if a printf
format string ends with \n
the write will occur.
You could add a fflush(stdout);
or fflush(NULL);
call before your while
loop.
See fflush(3) and setvbuf(3)
If you don't flush stdout
(either with a \n
in printf format string, or explicitly thru fflush
or fclose
) the buffer is flushed only at the end of main
(thru some implicit atexit(3) ...)
So what is happening to you is that (without the \n
) data stays in the stdout
buffer, and is actually written (by the write(2)
inside stdio
library) only at the exit of your program.
Read advanced linux programming.
来源:https://stackoverflow.com/questions/16494834/c-unix-strange-behaviour-while-using-system-calls-and-printf