[英]AWK pipe output from TTY to PHP
我有一個tty設備(/ dev / ttyUSB0),偶爾會以Cycle 1: 30662 ms, 117.41 W
的形式輸出一個字符串Cycle 1: 30662 ms, 117.41 W
我正在使用一個簡單的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
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);
?>
但是,kwhoutput.txt保持為空。 為什么這不起作用?
awk
正在緩沖您的數據。 使用fflush()
在每條輸出行之后刷新緩沖區:
awk '{
print $0 > "/dev/stderr";
if (/^Cycle/) {
print "update kWh.rrd N:" $5;
fflush();
}
}' < /dev/ttyUSB0 | php5 test.php
還要確保/dev/ttyUSB0
實際上輸出一行(以\\n
終止),而不僅僅是輸出數據字符串。
您還應該將您的PHP腳本修復為:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.