与popen平行的过程

时间:2017-04-06 15:23:01

标签: php popen

我需要从许多网络服务器下载文件然后做一些事情。有些文件很大。每个下载它都独立于另一个,所以我想并行完成。

所以我编写了以下脚本:

test.php的

$urls = [
    'url1', 'url2', 'url3'
];

foreach($urls as $url){
    popen("php download.php --url=" . $url, "w");
}

的download.php

$options = getopt(null, ["url:"]);
$url = $options["url"];
// do somethings - This loop is just for testing purposes
for($i = 0; $i <= 1000000000; $i++){
    $i;
}
print parse_url($url)["host"];

当我运行php test.php控制台时,向我显示一个顺序输出。我做错了什么?

2 个答案:

答案 0 :(得分:0)

如果你想让它们在异步中运行,请使用它,在后台运行每个。

popen("php download.php --url=" . $url . " &", "w");

演示:

<?php
$urls = ['www.baidu.com', 'github.com', 'stackoverflow.com'];
foreach($urls as $url)
{
  var_dump(popen("ping -c4 " . $url . " &", "w"));
  echo "dddd\n";
}

输出:

ei@localhost:~$ php test.php
resource(4) of type (stream)
dddd
resource(5) of type (stream)
dddd
resource(6) of type (stream)
dddd
ei@localhost:~$ PING www.a.shifen.com (61.135.169.121) 56(84) bytes of data.
PING github.com (192.30.255.112) 56(84) bytes of data.
PING stackoverflow.com (151.101.193.69) 56(84) bytes of data.
64 bytes from 61.135.169.121: icmp_seq=1 ttl=56 time=5.53 ms
64 bytes from 151.101.193.69: icmp_seq=1 ttl=53 time=75.1 ms
64 bytes from 192.30.255.112: icmp_seq=1 ttl=47 time=262 ms
64 bytes from 61.135.169.121: icmp_seq=2 ttl=56 time=5.24 ms
64 bytes from 151.101.193.69: icmp_seq=2 ttl=53 time=74.7 ms
64 bytes from 192.30.255.112: icmp_seq=2 ttl=47 time=262 ms
64 bytes from 61.135.169.121: icmp_seq=3 ttl=56 time=30.4 ms
64 bytes from 151.101.193.69: icmp_seq=3 ttl=53 time=107 ms
64 bytes from 192.30.255.112: icmp_seq=3 ttl=47 time=260 ms
64 bytes from 61.135.169.121: icmp_seq=4 ttl=56 time=20.0 ms

--- www.a.shifen.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3003ms
rtt min/avg/max/mdev = 5.244/15.311/30.413/10.578 ms
64 bytes from 151.101.193.69: icmp_seq=4 ttl=53 time=95.3 ms

--- stackoverflow.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3005ms
rtt min/avg/max/mdev = 74.732/88.154/107.341/13.857 ms
64 bytes from 192.30.255.112: icmp_seq=4 ttl=47 time=256 ms

--- github.com ping statistics ---
4 packets transmitted, 4 received, 0% packet loss, time 3003ms
rtt min/avg/max/mdev = 256.064/260.310/262.474/2.606 ms

答案 1 :(得分:0)

最后,我找到了最佳解决方案。

Pool满足了我的所有要求。 Pool-worker是一种软件设计模式,这种Pool是一个容器,有许多Worker(进程等待任务)。任务被添加到池中,然后每个工作人员执行一个任务来执行。

另一方面,我认为Python's implementation比PHP实现Pool-worker模式更好。