awk没有打印到文件

zor*_*b76 3 awk

awk newbie here ..我正在尝试这个:

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

但'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" }'
Run Code Online (Sandbox Code Playgroud)

但它仍然无法正常工作......打印到stdout工作正常.

我究竟做错了什么?

sar*_*old 8

你等待数据有多长时间了?

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

棘手的部分是C标准IO例程将根据特定的文件描述符更改其"足够"的定义 - 如果文件描述符是文件,那么IO是块缓冲的,您必须等待某个到达的数据量.(检查stat asdf.logIO 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.
Run Code Online (Sandbox Code Playgroud)

修改您的脚本如下所示:

top -b | awk 'BEGIN { OFS = ","; print "Timestamp,CPU,Memory"}
/bash/ { print strftime("%H:%M:%S"), $9, $10; fflush() }' > /tmp/foo
Run Code Online (Sandbox Code Playgroud)

fflush()部队输出马上.性能不佳,但更适合实时查看系统状态.