Chinaunix

标题: 请教 如何关闭输出时的缓存 [打印本页]

作者: hujysh    时间: 2012-04-26 17:37
标题: 请教 如何关闭输出时的缓存
本帖最后由 hujysh 于 2012-04-26 17:38 编辑

本来以为shell中输出的时候没有缓存,直接即时输出的
可是碰到这个例子
  1. #!/bin/sh

  2. (
  3.   echo 1111111111111111111
  4.   echo 2222222222222222222
  5.   echo 3333333333333333333
  6.   echo 4444444444444444444
  7.   echo 5555555555555555555
  8.   echo 6666666666666666666

  9.   sleep 9

  10.   echo DONE
  11.   ) \
  12.     | awk '(!($0 ~ " ABCD ") || $0 ~ "WWWWWWWWWWWW from XXXXXX" || $0 ~ " REM ")' \
  13.     | sed "s/\(^..:..:.. SQL> \).*REM \(.*\)/\1REM \2/" \
  14.     | sed "s/\(^..:..:.. SQL> \).*REM \(.*\)/\1REM \2/"      


  15. exit 0
复制代码

运行时候 等了约9秒才看到输出 1 到6
如果去掉第二句的sed,则很快看到 1到5  但是要约9秒才看到 输出6
如果去掉两句sed,则可以很快看到所有的 1到6

请牛牛们解释一下。

我在一个shell中是有这样类似的几层管道的,又希望即时看到输出,有什么办法吗?


作者: Shell_HAT    时间: 2012-04-26 17:43
sleep 9在实际的代码中有什么用处?
作者: hujysh    时间: 2012-04-26 17:46
sleep 9 实际没有的,是专为测试加的。
因为我的应用中有一块运行时间较长,有多个语句,相当于一段时间后才看到后面的 DONE。 而我的困惑是它在sleep前面的也不即时输出。
回复 2# Shell_HAT


   
作者: hujysh    时间: 2012-04-26 18:01

经过测试,知道了问题来自于 sed , 如果改用awk ,不用sed  可以解决这个问题。

sed在缓存方面的机制 我不明白。好在我的问题可以不用它。
作者: winway1988    时间: 2012-04-26 21:40
  1. #!/bin/sh

  2. (
  3.   echo 1111111111111111111
  4.   echo 2222222222222222222
  5.   echo 3333333333333333333
  6.   echo 4444444444444444444
  7.   echo 5555555555555555555
  8.   echo 6666666666666666666

  9.   sleep 9

  10.   echo DONE
  11.   ) \
  12.     | awk '(!($0 ~ " ABCD ") || $0 ~ "WWWWWWWWWWWW from XXXXXX" || $0 ~ " REM "){print;fflush()}' \
  13.     | sed -u "s/\(^..:..:.. SQL> \).*REM \(.*\)/\1REM \2/" \
  14.     | sed "s/\(^..:..:.. SQL> \).*REM \(.*\)/\1REM \2/"      


  15. exit 0
复制代码
  1. man awk
  2.        fflush([file])        Flush any buffers associated with the open output file or pipe file.   If
  3.                              file  is  missing,  then standard output is flushed.  If file is the null
  4.                              string, then all open output files and pipes have their buffers  flushed.
复制代码
  1. man sed
  2.        -u, --unbuffered

  3.               load minimal amounts of data from the input files and  flush  the  output  buffers  more
  4.               often
复制代码
我的理解,awk和sed串在管道里时,不是行缓冲方式,不会按行冲洗缓存,导致数据再awk积累。最后一个sed之所以不用指定缓冲方式,是因为他是行缓冲方式,遇到换行就会输出。
作者: g_programming    时间: 2012-04-27 09:50
回复 5# winway1988


    你已经把手册看透了啊 呵呵
作者: winway1988    时间: 2012-04-27 11:25
回复 6# g_programming


    呵呵、没有,怀疑是缓冲的方式引起的,才查awk和sed是不是有相关的设置,grep也有类似的情况




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2