[英]AWK pipe output from TTY to PHP
I have a tty device (/dev/ttyUSB0), which occasionally outputs a string in the form of Cycle 1: 30662 ms, 117.41 W
. 我有一个tty设备(/ dev / ttyUSB0),偶尔会以
Cycle 1: 30662 ms, 117.41 W
的形式输出一个字符串Cycle 1: 30662 ms, 117.41 W
I'm using a simple bash script to process it: 我正在使用一个简单的bash脚本来处理它:
#!/bin/sh
stty -F /dev/ttyUSB0 57600
cd /home/pi
while true; do
cat /dev/ttyUSB0 | awk '{ print $0 > "/dev/stderr"; if (/^Cycle/) { print "update kWh.rrd N:" $5 } }' | php5 test.php
sleep 1
done
The test.php script looks like this: test.php脚本如下所示:
<?php
stream_set_blocking(STDIN, 0);
$line = trim(fgets(STDIN));
$file = 'kwhoutput.txt';
$current = file_get_contents($file);
$current .= $line;
file_put_contents($file, $current);
?>
however, the kwhoutput.txt remains empty. 但是,kwhoutput.txt保持为空。 Why is this not working?
为什么这不起作用?
awk
is buffering your data. awk
正在缓冲您的数据。 Use fflush()
to flush the buffers after each output line: 使用
fflush()
在每条输出行之后刷新缓冲区:
awk '{
print $0 > "/dev/stderr";
if (/^Cycle/) {
print "update kWh.rrd N:" $5;
fflush();
}
}' < /dev/ttyUSB0 | php5 test.php
Also make sure that /dev/ttyUSB0
actually outputs a line (terminated by \\n
), and not just a string of data. 还要确保
/dev/ttyUSB0
实际上输出一行(以\\n
终止),而不仅仅是输出数据字符串。
You should also fix up your php script to: 您还应该将您的PHP脚本修复为:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.