首页 > Linux上read()的奇怪问题。

Linux上read()的奇怪问题。

这段代码只是一个测试用例中得一个代码段,我把它提取出来了。如下:

 #include    <stdio.h>
 #include    <unistd.h>
 #include    <fcntl.h>
 #include    <string.h>
 int main()
  {
     char buffer[1024];
     int nchars;
     while( 1 )
     {
        printf( "input the message:" );
        nchars = read( 0, buffer, 1023 );
        buffer[nchars] = '\0';
        if(( strncmp( buffer, "quit", 4)) == 0)
            break;
        else
            printf( "%s\n", buffer );
     }
      return 0;
 }

按理说,程序进入循环过后,就会首先打印出:"input the message:"
但是,并不是入期望那样,而是这样:

开始就提示用户输入信息。
谁能给个解释吗?
thx in advance :D


这个你可以搜下: 行缓冲, 全缓冲, 不缓冲, 通常命令行程序是行缓冲.

行缓冲的意思是说输出内容在程序退出或遇到\n时才真正打印出来.

你的程序显示输出input the message:, 但由于其中没有\n字符, 所以内容实际还在缓冲区没有打印;
当你输入hello后并将其打印时有个\n字符, 所以这时候你才看到input the message:hello.

另外, 比较是否是quit应该是if (strncmp(buffer, "quit", 4) == 0)吧!

【热门文章】
【热门文章】