PHP pcntl_fork不能在web服务器中使用的变通方法

    使用PHP扩展pcntl_fork可以进行多进程编程。编写好的程序可以在linux命令行中执行,但是如果把该程序作为apache web服务器的动态网页文件通过浏览器访问,则执行到pcntl_fork()函数时程序不再往下执行。原因是pcntl_fork()不能在apache的web方式下正常工作[1]。

    一种变通的解决办法是,把含有pcntl_fork的程序作为shell脚本来运行。(1)先在shell命令行方式下调试好含有pcntl_fork的程序.(2)编写一个网页文件,该网页的表单(form)中只包含一个文本输入框用于接收程序运行时的参数,form的methon方式为"post"。(3)提交表单后,form标签的action中指定的后台php程序接收文本框中的文本做为参数,用system/passthru函数调用含有pcntl_fork的程序。示例如下。

fectchpage2.php 多进程方式抓取指定网页文件及该文件上的图片文件,输入参数为指定网页文件的网址url

fetchpage.php 网页文件,显示文本输入框,输入内容为url,提交表单后如果url非空,调用passthru函数执行fetchpage2.php


fetchpage.php代码如下:

<?
$url = $_POST['url'];
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body >
<form name="myform" actiion="fetchpage.php" method="post">
    网址: <input type="text" name="url" size=100 value="" >
    <input type="submit" name="submit" value="提交" >
</form>
<?
if ($url!="") {
    echo "\n\n<pre>";
    passthru("/usr/bin/php fetchpage2.php \"$url\"");
    echo "</pre>";
}
?>
</body>
</html>


fetchpage2.php开头代码片段:

<?
if ($argc!=2) {
    echo "Please input a url<p>\n";
    exit(0);
}
$url = $argv[1];
if (strstr($url,"//")===false) {
    echo "\n\n$url 不是一个有效的网址。<p>\n";
    exit(0);
}
......    //后续程序代码


参考资料:

[1] 【教训】php pcntl_fork无法在web服务器环境下使用 http://www.cnblogs.com/bourneli/archive/2012/07/06/2579804.html


你可能感兴趣的:(PHP,Web,apche)