Home  >  Article  >  Backend Development  >  php 读取shell管道传输过来的内容_php技巧

php 读取shell管道传输过来的内容_php技巧

WBOY
WBOYOriginal
2016-05-17 09:27:44894browse

暮夏,您好!
rainbird给您发了短消息:
已经写了不少后台运行的deamon了.用的挺顺手的,但是我现在想获取管道传过来的内容,不知道咋实现,类似echo "aaaa" |a.php,a.php怎么获得echo的内容,不知道您有什么高见.
今天收到一条消息,解决的方法给大家分享一下:
实际上,shell 的 | 实际上表示的是 前一个的 标准输出 作为后一个的标准输入。虽然实现是通过pipe来实现的,
但是你写php代码的时候不需要知道底层的运作。你直接作为标准输入读取就可以了:
下面是一个实验代码:

复制代码 代码如下:

$fp = fopen("php://stdin", "r");
$s = '';
while (!feof($fp))
{
$s .= fgets($fp, 128);
}
var_dump($s);
fclose($fp);
?>

测试方法:
复制代码 代码如下:

ls -lh | php php_read_pipe.php

Rainbird 还给出更加简单的代码:
file_get_contents('php://stdin')
如果是有很多数据要传输过来,一般来说,是每4K传输一次。
直到传输完成。那可能不能简单的使用:
file_get_contents('php://stdin')。这样的话,一直会在等待。
分开处理的话,能够,读取一定的量后处理一部分。然后释放掉一部分的内存。
比如我要遍历所有的文件。可以这样处理
find / | php php php_read_pipe.php
大家根据具体情况具体分析。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn