awk没有打印到文件

时间:2011-11-09 00:09:18

标签: awk

awk新手在这里.. 我正在尝试这个:

top -b -p 30259 | awk 'BEGIN { OFS = ","; print "Timestamp,CPU,Memory"} /tomcat/ { print strftime("%H:%M:%S"), $9, $10 }' > asdf.log

但'asdf.log'始终保持空白。我尝试从脚本中重定向到文件:

top -b -p 30259 | awk 'BEGIN { OFS = ","; print "Timestamp,CPU,Memory" > "asdf.log"} /tomcat/ { print strftime("%H:%M:%S"), $9, $10 > "asdf.log" }'

但它仍然不起作用......打印到stdout工作正常。

我做错了什么?

1 个答案:

答案 0 :(得分:8)

您还等待数据到达多长时间?

当程序使用标准C库写入文件(fopen(3)和函数族)时,C库会向流中添加一些缓冲以提高性能。如果每个读取或写入一个字符实际上都启动了系统调用,那么常见程序的性能将非常糟糕。因此,当缓冲区“足够”时,C标准输入例程将提交IO的

棘手的部分是C标准IO例程将根据特定文件描述符更改其“足够”的定义 - 如果文件描述符是文件,那么IO是阻止缓冲,您必须等待一定数量的数据到达。 (检查stat asdf.log的{​​{1}}条目以查看最可能的大小。)但是,如果文件描述符用于IO Block ,则它指的是终端设备,输出行缓冲 - 一旦打印换行符,输出就会被发送到终端。

也许stdout联机帮助页可以比我更好地解释:

setvbuf(3)

修改您的脚本如下所示:

   The three types of buffering available are unbuffered, block
   buffered, and line buffered.  When an output stream is
   unbuffered, information appears on the destination file or
   terminal as soon as written; when it is block buffered many
   characters are saved up and written as a block; when it is
   line buffered characters are saved up until a newline is
   output or input is read from any stream attached to a
   terminal device (typically stdin).  The function fflush(3)
   may be used to force the block out early.  (See fclose(3).)
   Normally all files are block buffered.  When the first I/O
   operation occurs on a file, malloc(3) is called, and a buffer
   is obtained.  If a stream refers to a terminal (as stdout
   normally does) it is line buffered.  The standard error
   stream stderr is always unbuffered by default.

top -b | awk 'BEGIN { OFS = ","; print "Timestamp,CPU,Memory"} /bash/ { print strftime("%H:%M:%S"), $9, $10; fflush() }' > /tmp/foo 强制立即输出 。性能不佳,但更适合实时查看系统状态。