и то верно, вот накидал пример
index.html<!DOCTYPE html>
<html>
<head>
<title>Background task testing</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
var timer;
$(function () {
$('#start').click(function(){
$('#status').html('Request send...');
$.get('ajax.php?cmd=start', function() {});
timer = setInterval(function() {
$('#response').load('ajax.php?cmd=status');
}, 1000)
});
$('#stop').click(function() {
clearInterval(timer);
$('#status').html('Stopping task...');
$('#response').load('ajax.php?cmd=stop');
});
$('#response').load('ajax.php?cmd=status');
})
</script>
</head>
<body>
<h1>Background task testing</h1>
<div id="status"></div>
<pre id="response"></pre>
<input type="button" id="start" value="Run task">
<input type="button" id="stop" value="Stop task">
</body>
</html>
ajax.php<?php
if(empty($_GET['cmd']))
die('Bad request');
$pipe_name = 'bgtask.php.pipe';
$pid_file = 'bgtask.php.pid';
$pid = file_exists($pid_file) ? file_get_contents($pid_file) : 0;
switch ($_GET['cmd']) {
case 'start':
start();
break;
case 'stop':
stop();
break;
case 'status':
status();
break;
default:
echo 'Bad command';
break;
}
function start() {
global $pid;
if($pid) {
echo 'Task already started';
return;
}
system('php -f bgtask.php >/dev/null 2>&1 &');
usleep(500);
echo 'Task started';
}
function stop() {
global $pid;
if(!$pid) {
echo "Task was not started, no pid file found";
return;
}
system("kill -TERM $pid");
echo 'Task was stopped';
}
function status() {
global $pid, $pipe_name;
if(!$pid) {
echo "Task not started, no pid file found";
return;
}
system("kill -USR1 $pid");
usleep(10);
system("cat $pipe_name");
}
bgtask.php
<?php
PHP_SAPI == 'cli' or die('Error script must be run in CLI mode only');
declare(ticks=1);
function sig_handler($signal) {
global $pipe_name, $pid, $i, $start_time, $run;
$signals = array(
SIGUSR1 => 'SIGUSR1',
SIGHUP => 'SIGHUP',
SIGTERM => 'SIGTERM',
SIGINT => 'SIGINT'
);
$fh = fopen($pipe_name, 'w');
if($signal == SIGUSR1) {
$time = $start_time->diff(new DateTime());
$time = $time->format('%H:%I:%S');
fwrite($fh, "Task processing: $i iteration\nElapsed time: $time\nProcess pid: $pid");
}
if(in_array($signal, array(SIGTERM, SIGINT))) {
fwrite($fh, 'Process shutting down...');
$run = false;
}
fclose($fh);
}
pcntl_signal(SIGUSR1, 'sig_handler');
pcntl_signal(SIGHUP, 'sig_handler');
pcntl_signal(SIGTERM, 'sig_handler');
pcntl_signal(SIGINT, 'sig_handler');
$run = true;
$i = 0;
$start_time = new DateTime();
$pipe_name = 'bgtask.php.pipe';
$pid_file = 'bgtask.php.pid';
$pid = file_exists($pid_file) ? file_get_contents($pid_file) : 0;
if(!file_exists($pipe_name));
system("mkfifo $pipe_name");
if($pid) {
echo 'Task already started';
exit(1);
}
$pid = getmypid();
file_put_contents($pid_file, $pid);
while($run) {
$i++;
echo $i;
usleep(300);
}
unlink($pid_file);
unlink($pipe_name);