簡體   English   中英

從TTY到PHP的AWK管道輸出

[英]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腳本修復為:

  1. 閱讀多行並逐行附加(否則,腳本將跳過每隔一行)。
  2. 了解如何在php中附加文件。 讀取整個文件,在內存中串聯一個字符串,然后寫入整個文件並不是解決之道。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM