php调用system()并写入命名管道而不阻塞

时间:2012-02-07 04:08:01

标签: php apache bash asynchronous pipe

我有一些PHP代码:

<?
$cmd="mkfifo /tmp/myfifo;";
system($cmd);
$cmd="echo 1 > /tmp/myfifo 2>&1 &";
system($cmd);
?>

在Apache服务器上。我想让第二个命令不阻止。根据系统的信息页面:

If a program is started with this function, in order for it to continue running 
in the background, the output of the program must be redirected to a file or 
another output stream. Failing to do so will cause PHP to hang until the execution 
of the program ends.

但我不知道如何应用这种情况。我试过了

$cmd="echo 1 > /tmp/myfifo > /dev/null 2>&1 &";

但说实话,这似乎是荒谬的。

编辑:

我的最终目标是写入一个可能永远无法读取的fifo,并在5秒后超时写入。所以,如果我能设法让这个命令不阻止php执行,我可以睡5秒然后cat / tmp / myfifo&gt; / dev / null 2&gt;&amp; 1取消阻止原始写入。

任何人都可以想到一种更好的方法让我的写作无限期地挂起(无论是背景还是前景)?

3 个答案:

答案 0 :(得分:2)

如果system()创建的环境是bash 4.x或更高版本,我相信您可以使用“coproc”来防止它被阻止?这适用于shell脚本。 (或者,如果它没有直接在bash中执行,你可以让它调用“bash -c ...”)

答案 1 :(得分:1)

如果您需要写入文件(并在完成之前阻止其他进程写入),那么只需使用file_put_contents

<?php
// The new person to add to the file
$person = "John Smith\n";

// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents('/tmp/myfifo', $person, FILE_APPEND | LOCK_EX);

答案 2 :(得分:0)

您可以使用nohup在后​​台启动流程:

$ nohup binary arguments
$ man nohup
相关问题