c - Can someone please explain how stdio buffering works? -
i don't understand buffer doing , how it's used. (also, if can explain buffer does) in particular, why need fflush in example?
int main(int argc, char **argv) { int pid, status; int newfd; /* new file descriptor */ if (argc != 2) { fprintf(stderr, "usage: %s output_file\n", argv[0]); exit(1); } if ((newfd = open(argv[1], o_creat|o_trunc|o_wronly, 0644)) < 0) { perror(argv[1]); /* open failed */ exit(1); } printf("this goes standard output.\n"); printf("now standard output go \"%s\".\n", argv[1]); fflush(stdout); /* new file become standard output */ /* standard output file descriptor 1, use dup2 */ /* copy new file descriptor onto file descriptor 1 */ /* dup2 close current standard output */ dup2(newfd, 1); printf("this goes standard output too.\n"); exit(0); }
in unix system stdout buffering happens improve i/o performance. expensive i/o every time.
if don't want buffer there's options:
disable buffering calling setvbuf http://www.cplusplus.com/reference/cstdio/setvbuf/
call flush when want flush buffer
output stderr (that's unbuffered default)
here you've more details: http://www.turnkeylinux.org/blog/unix-buffering
i/o expensive operation, reduce number of i/o operations system store information in temporary memory location, , delay i/o operation moment when has amount of data.
this way you've smaller number of i/o operations, means, faster application.
Comments
Post a Comment