C/Unix 使用系统调用和 printf 时的奇怪行为 [英] C/Unix Strange behaviour while using system calls and printf

查看:26
本文介绍了C/Unix 使用系统调用和 printf 时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手,试图真正了解系统编程.在下面的程序中,我正在读取一个名为temp1"的文件(包含 1 2 3 4)并将其内容打印到标准输出.但是,我还想检查 open 返回的文件描述符的值.如果我在第 5 行的 printf 调用中包含 '\n',则输出首先打印值 filep,然后打印文件的内容.但是如果我删除换行符,文件的内容会先打印,然后是 filep 的值.为什么会发生这种情况?

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;
    }

我使用的是 gcc 4.6.3.

I am using gcc 4.6.3.

推荐答案

printf 这样的函数被 缓冲.输出函数将不时调用 write(2) 系统调用,通常输出函数如 printf 等...只会进入内部 FILE 缓冲区.

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

stdout 在输出到终端时是行缓冲的(参见 isatty(3)).因此,如果 printf 格式字符串以 \n 结尾,则会发生写入.

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.

您可以在 while 循环之前添加 fflush(stdout);fflush(NULL); 调用.

You could add a fflush(stdout); or fflush(NULL); call before your while loop.

参见 fflush(3)setvbuf(3)

如果您不刷新 stdout(使用 printf 格式字符串中的 \n,或明确通过 fflushfclose) 缓冲区仅在 main 的末尾刷新(通过一些隐式的 atexit(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) ...)

所以发生在你身上的是(没有 \n)数据留在 stdout 缓冲区中,并且实际上被写入(由 write(2) stdio 库中)仅在程序退出时.

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.

阅读高级 linux 编程.

这篇关于C/Unix 使用系统调用和 printf 时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆