简体   繁体   English

如何从PHP写入命名的Linux管道?

[英]How to write to named Linux pipe from PHP?

I have the following bash script: 我有以下bash脚本:

server_control_pipe="/var/custom_pipe_file_name"
init_script="/usr/sbin/service [somedaemon]"

mkfifo -m 666 "$server_control_pipe"

while read line <"$server_control_pipe"
 do
  echo "Received $line"
  if [[ "$line" == 'stop' ]]; then
    $init_script stop
  elif [[ "$line" == 'start' ]]; then
    $init_script start
  elif [[ "$line" == 'stoppipe' ]]; then
    break
  fi
  echo "Waiting..."
done

echo "END"

...and the following PHP script: ...以及以下PHP脚本:

<?php
define('SERVER_CONTROL_PIPE', "/var/custom_pipe_file_name");

if(false === file_put_contents(SERVER_CONTROL_PIPE, "start\n", FILE_APPEND))
    throw new Exception("Could not write to server control pipe");

When running the PHP script, the loop in the bash script seems to terminate and the bash script simply outputs END. 运行PHP脚本时,bash脚本中的循环似乎终止了,bash脚本仅输出END。

To try to find out why it does that, I replaced my PHP script with this code: 为了找出原因,我用以下代码替换了PHP脚本:

<?php
define('SERVER_CONTROL_PIPE', "/var/custom_pipe_file_name");

$f = fopen(SERVER_CONTROL_PIPE, 'w');
if(false === $f)
    throw new Exception("Could not open server control pipe");

$ret = fwrite($f, 'start\n');
if(false === $ret)
    throw new Exception("Could not write to server control pipe");

fclose($f);

I found out that the bash script loop terminates whenever fopen is called. 我发现,无论何时调用fopen ,bash脚本循环都会终止。

So my question boils down to: How do I have to open the pipe in PHP in order to not break the bash script loop? 因此,我的问题可以归结为:为了不破坏bash脚本循环,我如何在PHP中打开管道?

If you want the script to run all the time then you should have while true instead of while read line, eg: 如果您希望脚本一直运行,那么您应该使用while为true而不是while读取行,例如:

while :
do
    echo "Press [CTRL+C] to stop.."
    sleep 1
done

If you do read line you will read file contents of the file at that state and finish execution. 如果您确实读取了行,则将在该状态下读取文件的文件内容并完成执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM