PHP呼叫系统()和写入命名管道不会阻塞

问题描述:

我有一些PHP代码: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 &"; 

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

编辑:

我的最终目标是在5秒钟后写入到可能永远不会被读取一个FIFO和超时写。所以,如果我能设法得到这个命令不阻止php的执行,我可以睡5秒,然后cat/tmp/myfifo>/dev/null 2> & 1来解除原始写入。

任何人都可以想到一个更好的方式来让我的写作不会无限期地挂起(在背景或前景中)吗?

+0

你的实际目标是什么?这听起来很糟糕。 – Xeoncross 2012-02-07 20:06:32

+0

我的实际目标是写入由服务器进程读取的fifo。如果服务器进程没有运行,fifo将不会被读取,但我不希望强制php挂起,或者留下一堆挂起的后台进程。 – Snitse 2012-02-07 20:09:02

+0

你不能只使用PHP的流和文件函数来写入或附加到该文件?任何你使用'system()'调用的原因? – Xeoncross 2012-02-07 21:05:35

如果你需要写一个文件(并防止其他进程写,直到你完成),那么就使用。

<?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); 
+0

直到fifo管道被读取,这仍然阻塞。有没有超时的操作或任何东西? – Snitse 2012-02-07 21:42:21

+0

你是什么意思它“阻塞,直到fifo管道读取”?该代码应打开(或创建如果丢失)该文件,写入增加的值,然后关闭它。最多只需要几百ms,你还在做什么?其他进程是否将大量数据写入此文件?如果不需要,可以删除'| LOCK_EX'。 – Xeoncross 2012-02-07 22:15:49

+0

我确实删除了它,尽管如此是写入文件的唯一过程,我的php文件的全部内容是在打开和关闭标记之间的'file_put_contents('/ tmp/myfifo',“1”,FILE_APPEND)'当我尝试打开页面时一个浏览器,浏览器坐在那里加载,并且永远不会停止,除非在终端中执行'cat的/ tmp/myfifo'。 – Snitse 2012-02-07 23:13:35

你可以使用nohup在后台启动一个进程:

$ nohup binary arguments 
$ man nohup 
+0

我试过'$ cmd =“nohup echo'1'>/tmp/myfifo 2>​​system($ cmd);'但是它仍然阻塞了php – Snitse 2012-02-07 19:57:41

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