PHP使用pcntl_fork实现多进程下载图片的方法
这篇文章主要介绍了PHP使用pcntl_fork实现多进程下载图片的方法,较为详细的分析了pcntl_fork的原理与用法,以及使用pcntl_fork实现多进程下载图片的方法,非常具有
本文实例讲述了PHP使用pcntl_fork实现多进程下载图片的方法。分享给大家供大家参考。具体分析如下:
PHP pcntl_fork — 在当前进程当前位置产生分支,子进程,译注:fork是创建了一个子进程,父进程和子进程 都从fork的位置开始向下继续执行,不同的是父进程执行过程中,得到的fork返回值为子进程号,而子进程得到的是0.
注意:PHP有个pcntl_fork的函数可以实现多进程,但要加载pcntl拓展,而且只有在linux下才能编译这个拓展.
1.首先在ubuntu下编译pcntl.so,我的ubuntu下找不到pcntl的包,于是创建一个文件夹下载了整个PHP包,在里面找到了pcntl包运行如下命令,代码如下:
复制代码 代码如下:
# mkdir php
# cd php
# apt-get source php5
# cd php5-(WHATEVER_RELEASE)/ext/pcntl
# phpize
# ./configure (注一)
# make
# make install phpize 命令是用来准备 PHP 外挂模块的编译环境的
成功的安装将建立 extname.so 并放置于 PHP 的外挂模块目录中(预设存放于 /usr/lib/php/modules/ 内),需要调整 php.ini,加入 extension=extname.so 这一行之后才能使用此外挂模块.
例:
复制代码 代码如下:
void pcntl_exec(string $path [,array $args [,array $envs ]])
pcntl_exec — 在当前进程空间执行指定程序,代码如下:
复制代码 代码如下:
$cmds=array(
array('/home/jerry/projects/www/test2.php'),
array('/home/jerry/projects/www/test3.php')
);
foreach($cmds as $cmd){
$pid=pcntl_fork();
if($pid==-1){
//进程创建失败
echo '创建子进程失败时返回-1';
exit(-1);
}
else if($pid){
//父进程会得到子进程号,,所以这里是父进程执行的逻辑
pcntl_wait($status,WNOHANG);
}
else{
//子进程处理逻辑
sleep(5);
pcntl_exec('/usr/bin/php',$cmd);
exit(0);
}
}
例,实例多图片同步下载,代码如下:
复制代码 代码如下:
#!/usr/bin/php
// 需要抓取的网页地址
$url = 'http://www.jb51.net';
$content = file_get_contents($url);
preg_match_all('/
echo "已发现".count($matches)."张图片n";
list($sm, $ss) = explode(" ", microtime());
foreach ($matches as $k => $val)
{
$pid[$k] = pcntl_fork();
if(!$pid[$k])
{
download($url, $val);
// 子进程要exit否则会进行递归多进程,父进程不要exit否则终止多进程
exit(0);
}
if ($pid[$k])
{
// pcntl_waitpid($pid[$k], $status, WUNTRACED);
}
}
echo "下载完成n";
list($em, $es) = explode(" ", microtime());
echo "用时:",($es+$em) - ($ss + $sm),"n";
/**
* 抓取网页图片
*
*/
function download($url, $val)
{
$pic_url = $val[1];
if (strpos($val[1], '//') !== false)
{
;
}
elseif (preg_match('@^(.*?)/@', $val[1], $inner_matches) == 0)
{
$pic_url = $url.$val[1];
}
elseif (preg_match('@[:.]@', $inner_matches[1], $tmp_matches) == 0)
{
$pic_url = $url.$val[1];
}
$pic = file_get_contents($pic_url);
if ($pic === false)
{
return;
}
preg_match('@/([^/]+)$@', $pic_url, $tmp_matches);
// 可使用assert处理异常
$pic_file_name = $tmp_matches[1];
$f = fopen("tmp/".$pic_file_name, "wb"); #
fwrite($f, $pic);
fclose($f);
}
/* End of file pcntl_fork.php */
?>
希望本文所述对大家的PHP程序设计有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.
