我的目的是这样的。
我的client.html通过ajax调用一个php脚本check.php。我希望check.php检查是否另一个脚本task.php已经在运行。如果是,我什么都不做。如果不是,我需要在后台运行它。
我知道我想做什么,但不确定怎么做。
第一部分:我知道如何通过ajax调用check.php。
在check.php中,我可能需要运行task.php。我想我需要这样的内容:$PID = shell_exec("php task.php > /dev/null & echo $!");
我认为">/dev/null &"位告诉它在后台运行,但我不确定"$!"是做什么的。
Part C.我需要的$PID作为进程的标记。我需要将这个数字(或其他什么)写入同一目录下的文件,并且需要在每次调用check.php时读取它。我想不出该怎么做。有人能给我一个链接,如何读/写一个文件与一个单一的数字在同一目录?
然后检查最后启动的task.php是否仍在运行,我将使用函数:function is_process_running($PID)
{
exec("ps $PID", $ProcessState);
return(count($ProcessState) >= 2);
}
我认为这是我需要的所有位,但正如你所看到的,我不确定如何做一些
我将使用基于flock()
的机制来确保task.php
只运行一次。
使用如下代码:
<?php
$fd = fopen('lock.file', 'w+');
// try to get an exclusive lock. LOCK_NB let the operation not blocking
// if a process instance is already running. In this case, the else
// block will being entered.
if(flock($fd, LOCK_EX | LOCK_NB )) {
// run your code
sleep(10);
// ...
flock($fd, LOCK_UN);
} else {
echo 'already running';
}
fclose($fd);
还请注意,正如PHP文档所指出的那样,flock()
可以在所有支持的操作系统上移植。
!$
给出bash中最后执行的程序的pid。这样的:
command &
pid=$!
echo pid
请注意,您必须确保php代码在支持bash的系统上运行。(而不是windows)
更新(在打开器注释之后)。
flock()
将在所有操作系统上工作(正如我提到的)。在使用windows时,我在代码中看到的问题是!$
(正如我提到的;).
要获得task.php的pid,您应该使用proc_open()
启动task.php。我准备了两个示例脚本:
task.php
$fd = fopen('lock.file', 'w+');
// try to get an exclusive lock. LOCK_NB let the operation not blocking
// if a process instance is already running. In this case, the else
// block will being entered.
if(flock($fd, LOCK_EX | LOCK_NB )) {
// your task's code comes here
sleep(10);
// ...
flock($fd, LOCK_UN);
echo 'success';
$exitcode = 0;
} else {
echo 'already running';
// return 2 to let check.php know about that
// task.php is already running
$exitcode = 2;
}
fclose($fd);
exit($exitcode);
check.php
$cmd = 'php task.php';
$descriptorspec = array(
0 => array('pipe', 'r'), // STDIN
1 => array('pipe', 'w'), // STDOUT
2 => array('pipe', 'w') // STDERR
);
$pipes = array(); // will be set by proc_open()
// start task.php
$process = proc_open($cmd, $descriptorspec, $pipes);
if(!is_resource($process)) {
die('failed to start task.php');
}
// get output (stdout and stderr)
$output = stream_get_contents($pipes[1]);
$errors = stream_get_contents($pipes[2]);
do {
// get the pid of the child process and it's exit code
$status = proc_get_status($process);
} while($status['running'] !== FALSE);
// close the process
proc_close($process);
// get pid and exitcode
$pid = $status['pid'];
$exitcode = $status['exitcode'];
// handle exit code
switch($exitcode) {
case 0:
echo 'Task.php has been executed with PID: ' . $pid
. '. The output was: ' . $output;
break;
case 1:
echo 'Task.php has been executed with errors: ' . $output;
break;
case 2:
echo 'Cannot execute task.php. Another instance is running';
break;
default:
echo 'Unknown error: ' . $stdout;
}
你问我为什么我的羊群()解决方案是最好的。这只是因为另一个答案将不可靠地确保task.php
运行一次。这是因为我在下面的评论中提到的竞争条件回答了这个问题。
您可以使用锁文件:
if(is_file(__DIR__.'/work.lock'))
{
die('Script already run.');
}
else
{
file_put_contents(__DIR__.'/work.lock', '');
// YOUR CODE
unlink(__DIR__.'/work.lock');
}
可惜在它被接受之前我没有看到。
我已经写了一个类来做这个。(使用文件锁定)和PID,进程ID检查,在windows和Linux上。
https://github.com/ArtisticPhoenix/MISC/blob/master/ProcLock.php我认为你们在所有的流程和背景调查方面确实做得过头了。如果您运行PHP
脚本without a session
,那么您实际上已经在后台运行它了。因为它不会阻止来自用户的任何其他请求。所以确保你没有调用session_start();
那么下一步就是即使用户取消请求也要运行它,这是PHP
中的一个基本功能。ignore_user_abort
最后一个检查是确保它只运行一次,这可以很容易地通过创建一个文件来完成,因为PHP
没有一个简单的应用范围。
:
<?php
// Ignore user aborts and allow the script
// to run forever
ignore_user_abort(true);
set_time_limit(0);
$checkfile = "./runningtask.tmp";
//LOCK_EX basicaly uses flock() to prevents racecondition in regards to a regular file open.
if(file_put_contents($checkfile, "running", LOCK_EX)===false) {
exit();
}
function Cleanup() {
global $checkfile;
unlink($checkfile);
}
/*
actual code for task.php
*/
//run cleanup when your done, make sure you also call it if you exit the code anywhere else
Cleanup();
?>
在你的javascript中,你现在可以直接调用task.php,并在与服务器建立连接后取消请求。
<script>
function Request(url){
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else{
return false;
}
httpRequest.onreadystatechange = function(){
if (httpRequest.readyState == 1) {
//task started, exit
httpRequest.abort();
}
};
httpRequest.open('GET', url, true);
httpRequest.send(null);
}
//call Request("task.php"); whenever you want.
</script>
额外提示:您可以让task.php的实际代码偶尔对$checkfile
进行更新,以了解发生了什么。然后可以让另一个ajax文件读取内容并向用户显示状态。
让我们把从B到D的整个过程简单化。
步骤罪犯:
$rslt =array(); // output from first exec
$output = array(); // output of task.php execution
//Check if any process by the name 'task.php' is running
exec("ps -auxf | grep 'task.php' | grep -v 'grep'",$rslt);
if(count($rslt)==0) // if none,
exec('php task.php',$output); // run the task,
解释:
ps -auxf --> gets all running processes with details
grep 'task.php' --> filter the process by 'task.php' keyword
grep -v 'grep' --> filters the grep process out
注:
-
也建议将相同的检查放在task.php文件中。
如果通过httpd (webserver)直接执行task.php,它将只显示为httpd进程,不能通过'ps'命令
识别在负载均衡的环境下无法工作。(编辑:17 jul17)
您可以在脚本运行期间获得脚本本身的排他锁
一旦lock()函数被调用,任何其他尝试运行它的操作都将结束。
//try to set a global exclusive lock on the file invoking this function and die if not successful
function lock(){
$file = isset($_SERVER['SCRIPT_FILENAME'])?
realpath($_SERVER['SCRIPT_FILENAME']):
(isset($_SERVER['PHP_SELF'])?realpath($_SERVER['PHP_SELF']):false);
if($file && file_exists($file)){
//global handle stays alive for the duration if this script running
global $$file;
if(!isset($$file)){$$file = fopen($file,'r');}
if(!flock($$file, LOCK_EX|LOCK_NB)){
echo 'This script is already running.'."'n";
die;
}
}
}
测试在一个shell中运行此命令,并在等待输入时尝试在另一个shell中运行。
lock();
//this will pause execution until an you press enter
echo '...continue? [enter]';
$handle = fopen("php://stdin","r");
$line = fgets($handle);
fclose($handle);