-
Notifications
You must be signed in to change notification settings - Fork 7
/
background_process.php
282 lines (267 loc) · 8.78 KB
/
background_process.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
<?php
error_reporting(E_ALL);
class BackgroundProcess{
const OS_WINDOWS = 1;
const OS_NIX = 2;
const OS_OTHER = 3;
private $command;
private $pid;
protected $serverOS;
private $CurrentDirectory;
public function __construct($command = null,$dir=''){
$this->command = $command;
$this->serverOS = $this->getOS();
$this->CurrentDirectory =$dir ;
}
public function set_command($command){
$this->command = $command;
}
public function set_CurrentDirectory($dir){
$this->CurrentDirectory = $dir;
}
/**
* @param string $outputFile File to write the output of the process to; defaults to /dev/null
* currently $outputFile has no effect when used in conjunction with a Windows server
* @param bool $append - set to true if output should be appended to $outputfile
*/
public function run($outputFile = '/dev/null', $append = false){
if($this->command === null) {
return;
}
switch ($this->getOS()) {
case self::OS_WINDOWS:
//$cmd = 'wmic process call create "C:/xampp/php/php.exe -f /path/to/htdocs/test.php" | find "ProcessId"';
$cmd = 'wmic process call create "'.$this->command.'" | find "ProcessId"';
$handle = popen("start /B ". $cmd, "r");
$read = fread($handle, 200); //Read the output
//echo $read; //Store the info//ProcessId = 8156;
$pid=substr($read,strpos($read,'=')+1);
$pid=substr($pid,0,strpos($pid,';') );
//echo 'ProcessId : ' . $pid;
$this->pid = (int)$pid;
pclose($handle); //Close
break;
case self::OS_NIX:
$this->pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $this->command, ($append) ? '>>' : '>', $outputFile));
break;
default:
throw new RuntimeException(sprintf(
'Could not execute command "%s" because operating system "%s" is not supported by '.
'Cocur\BackgroundProcess.',
$this->command,
PHP_OS
));
}
}
public function isRunning(){
try {
switch ($this->getOS()) {
case self::OS_WINDOWS:
//tasklist /FI "PID eq 6480"
$result = shell_exec('tasklist /FI "PID eq '.$this->pid.'"' );
if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
return true;
}
break;
case self::OS_NIX:
//pstree to list all process
$result = shell_exec(sprintf('ps %d 2>&1', $this->pid));
if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
return true;
}
break;
}
} catch (Exception $e) {
}
return false;
}
public function stop(){
try {
switch ($this->getOS()) {
case self::OS_WINDOWS:
//taskkill /PID 9444
$result = shell_exec('taskkill /PID '.$this->pid );
if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
return true;
}
break;
case self::OS_NIX:
$result = shell_exec(sprintf('kill %d 2>&1', $this->pid));
if (!preg_match('/No such process/', $result)) {
return true;
}
break;
}
} catch (Exception $e) {
}
return false;
}
public function getPid(){
return $this->pid;
}
//protected function setPid($pid){
public function setPid($pid){
//$this->checkSupportingOS('Cocur\BackgroundProcess can only return the PID of a process on *nix-based systems, '.
// 'such as Unix, Linux or Mac OS X. You are running "%s".');
$this->pid = $pid;
}
protected function getOS(){
$os = strtoupper(PHP_OS);
if (substr($os, 0, 3) === 'WIN') {
return self::OS_WINDOWS;
} else if ($os === 'LINUX' || $os === 'FREEBSD' || $os === 'DARWIN') {
return self::OS_NIX;
}
return self::OS_OTHER;
}
protected function checkSupportingOS($message){
if ($this->getOS() !== self::OS_NIX) {
throw new RuntimeException(sprintf($message, PHP_OS));
}
}
static public function createFromPID($pid) {
$process = new self();
$process->setPid($pid);
return $process;
}
}
//$process = new BackgroundProcess('sleep 5');
// $process->run();
// echo 'Crunching numbers in process '. $process->getPid() ;
// sleep(1);
// while ($process->isRunning()) {
// echo '.' ;
// sleep(1);
// }
//echo "\nDone.\n"
function run_process($cmd,$outputFile = '/dev/null', $append = false){
$pid=0;
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
$cmd = 'wmic process call create "'.$cmd.'" | find "ProcessId"';
$handle = popen("start /B ". $cmd, "r");
$read = fread($handle, 200); //Read the output
$pid=substr($read,strpos($read,'=')+1);
$pid=substr($pid,0,strpos($pid,';') );
$pid = (int)$pid;
pclose($handle); //Close
}else{
$pid = (int)shell_exec(sprintf('%s %s %s 2>&1 & echo $!', $cmd, ($append) ? '>>' : '>', $outputFile));
}
return $pid;
}
function is_process_running($pid){
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
//tasklist /FI "PID eq 6480"
$result = shell_exec('tasklist /FI "PID eq '.$pid.'"' );
if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
return true;
}
}else{
$result = shell_exec(sprintf('ps %d 2>&1', $pid));
if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
return true;
}
}
return false;
}
function stop_process($pid){
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
$result = shell_exec('taskkill /PID '.$pid );
if (count(preg_split("/\n/", $result)) > 0 && !preg_match('/No tasks/', $result)) {
return true;
}
}else{
$result = shell_exec(sprintf('kill %d 2>&1', $pid));
if (!preg_match('/No such process/', $result)) {
return true;
}
}
}
$cmd='';
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {//'This is a server using Windows!';
$cmd= $php_path.'\php.exe '.$path.'\long_process.php' ;
}else{
$cmd='/usr/bin/php -f /var/www/example.com/public/long_process.php';
}
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_REQUEST['head']) ){
switch($_REQUEST['head']){
case 'start':
//$process->run();
//echo $process->getPid();
echo run_process($cmd);
break;
case 'check':
$pid=isset($_REQUEST['pid'])?intval($_REQUEST['pid']):0;
if($pid!=0){
//$process->setPid($pid);
//if($process->isRunning()) {
if(is_process_running($pid)){
echo 'Process running';
}else{
echo 'Process not running';
}
}
break;
case 'stop':
$pid=isset($_REQUEST['pid'])?intval($_REQUEST['pid']):0;
if($pid!=0){
//$process->setPid($pid);
//if($process->isRunning()) {
// $process->stop();
if(is_process_running($pid)){
stop_process($pid);
echo 'Process stopped';
}else{
echo 'Process not running';
}
}
break;
}
exit;
}
function isSSL() { return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || $_SERVER['SERVER_PORT'] == 443; }
//$url=$_SERVER['REQUEST_URI'];
//$url=$_SERVER['QUERY_STRING'];
//print_r($_SERVER);
//echo $_SERVER['REQUEST_URI'];
$url=(isSSL()?'https://': 'http://') . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$url=str_replace('?'.$_SERVER['QUERY_STRING'],'',$url);
?>
<html>
<head>
<title>Background Process</title>
<script src="jquery-1.11.1.min.js"></script>
</head>
<body >
<h3>Background Process Test</h3>
<button onclick="start()">Start</button>
<button onclick="check()">Check</button>
<button onclick="stop()">Stop</button>
<script>
var url="<?php echo $url; ?>";
var pid='';
function start(){
$.ajax({url: url,data:{head:'start'},type:'post', dataType: "text", success: function(data){
pid=data;
alert('Process id : ' + pid);
}, error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
}
function check(){
$.ajax({url: url,data:{head:'check' ,pid:pid},type:'post', dataType: "text", success: function(data){
alert(data);
}, error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
}
function stop(){
$.ajax({url: url,data:{head:'stop' ,pid:pid},type:'post', dataType: "text", success: function(data){
alert(data);
}, error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
}
</script>
</body>
</html>