4

小心grep 的buffer -- Linux -- IT技术博客大学习 -- 共学习 共进步!

 2 years ago
source link: https://blogread.cn/it/article/4827?f=hot1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

小心grep 的buffer

浏览:2652次  出处信息

在统计mysql查询次数时,有如下命令:

while :; do sleep 1;  mysql -u user -ppass -h phpor.net -P 3306 -e 'show status like "Questions";'; done |grep Ques | awk '{print $2 - old; old = $2; }'

几秒钟后都看不到结果,怀疑是awk的buffer造成的,于是改写为:
 while :; do sleep 1;  mysql -u user -ppass -h phpor.net -P 3306 -e  'show status like "Questions";'; done |grep Ques | awk  '{print $2 - old; old = $2; fflush();}'

依然不行,于是,把该命令推到后台,使用strace跟踪了一下awk,发现awk没有读到内容,很自然地,跟踪grep吧,发现grep read到内容了,但是总是不write,开始怀疑我的 Ques写错了,仔细比对,也没有问题呀,突然,屏幕上打印出了很多信息,于是,我恍然大悟,应该是grep的buffer搞的鬼,于是man了一下grep,果然有这方面的选项,再次修改如下:

while :; do sleep 1;  mysql -u user -ppass -h phpor.net -P 3306 -e  'show status like "Questions";'; done |grep --line-buffered Ques | awk  '{print $2 - old; old = $2; fflush();}'

终于OK了


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK