2009-09-19 102 views
6

PHP脚本如何启动另一个PHP脚本,然后退出,让其他脚本运行?PHP脚本能否启动另一个PHP脚本并退出?

另外,有没有什么办法让第二个脚本在到达特定行时通知PHP脚本?

+0

卷曲可以帮助吗?任何想法如何? –

+0

卷毛?可能只是一个“头”的请求,但我很怀疑 –

+0

- 如果第一个脚本终止,第二个脚本如何通知第一个脚本? - 这是一个网页或控制台脚本? –

回答

7

下面介绍如何操作。您告诉浏览器读取输出的前N个字符,然后关闭连接,而脚本一直运行直到完成。

<?php 
ob_end_clean(); 
header("Connection: close"); 
ignore_user_abort(); // optional 
ob_start(); 
echo ('Text the user will see'); 
$size = ob_get_length(); 
header("Content-Length: $size"); 
ob_end_flush();  // Will not work 
flush();   // Unless both are called ! 

// At this point, the browser has closed connection to the web server 

// Do processing here 
include('other_script.php'); 

echo('Text user will never see'); 
?> 
+1

你能解释一下你的代码吗?例如,冲洗诱使浏览器认为HTTP请求已结束? –

+0

是的,它的工作原理!请同时发布这个问题的答案 - http://stackoverflow.com/questions/1436575/can-a-php-script-trick-the-browser-into-thinking-the-http-request-is-over –

+0

我编辑了答案来解释一点。 –

1

这是黑暗中的镜头:您可以尝试使用php的操作系统执行功能&

exec("./somescript.php &"); 

此外,如果不工作,你可以尝试

exec("nohup ./somescript.php &"); 

编辑:nohup is a POSIX command to ignore the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. The HUP (hangup) signal is by convention the way a terminal warns depending processes of logout.

+0

'nohup'?这是做什么的? –

3

您可以通过forking然后调用includerequire有效实现此目的。

parent.php:

<?php 

    $pid = pcntl_fork(); 
    if ($pid == -1) { 
     die("couldn't fork"); 
    } else if ($pid) { // parent script 
     echo "Parent waiting at " . date("H:i:s") . "\n"; 
     pcntl_wait($status); 
     echo "Parent done at " . date("H:i:s") . "\n"; 
    } else { 
     // child script 
     echo "Sleeper started at " . date("H:i:s") . "\n"; 
     include('sleeper.php'); 
     echo "Sleeper done at " . date("H:i:s") . "\n"; 
    } 

?> 

sleeper.php:

<?php 
sleep(3); 
?> 

输出:

 
$ php parent.php 
Sleeper started at 01:22:02 
Parent waiting at 01:22:02 
Sleeper done at 01:22:05 
Parent done at 01:22:05 

然而,分叉本身并没有允许任何进程间通信,所以你你必须找到其他方式告诉父母,孩子已经到达特定线路,就像你在第四节中提到的那样问题。

+0

+1我不认为这正是他想要的,但仍然非常有用 –

+0

您可以通过套接字方法提供双边沟通(请参阅http://www.php.net/manual/en/ref.sockets.php) 。 –

0

如果您不想构建pcntl扩展,那么一个很好的选择是使用proc_open()。

http://www.php.net/manual/en/function.proc-open.php

使用与stream_select在一起(),所以你的PHP程序可以睡觉,直到有事跟你创建子进程。

这将有效地在后台创建一个进程,而不会阻止父PHP进程。你的PHP可以读写STDIN,STDOUT,STDERR。

为了使浏览器完成加载(停止加载进度指示器),那么你可以使用米兰Babuškov提到的。

使浏览器认为HTTP请求完成的关键是发送它的内容长度。要做到这一点,您可以开始缓冲请求,然后在发送Content-Length标头后将其刷新。

如:

<?php 

ob_start(); 

// render the HTML page and/or process stuff 

header('Content-Length: '.ob_get_length()); 
ob_flush(); 
flush(); 

// can do more processing 

?> 
0

您可以创建一个请求,并关闭它完成后立即被写入连接。

检出http://drupal.org/project/httprl中的代码,可以这样做(非阻塞请求)。一旦我把它更加打磨,我打算把这个lib推给github;可以在Drupal之外运行的东西。这应该做你想要的。

相关问题