-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcess.php
More file actions
453 lines (365 loc) · 12.2 KB
/
Process.php
File metadata and controls
453 lines (365 loc) · 12.2 KB
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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
<?PHP
/**
* qcEvents - Asyncronous Process/Application I/O
* Copyright (C) 2012 Bernd Holzmueller <bernd@quarxconnect.de>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**/
require_once ('qcEvents/IOStream.php');
/**
* Process
* -------
* Spawns a command (uni- or bi-directional) and waits for input
*
* @class qcEvents_Process
* @extends qcEvents_IOStream
* @package qcEvents
* @revision 02
**/
class qcEvents_Process extends qcEvents_IOStream {
const READ_BUFFER = 40960;
/* Internal method to spawn a command */
const MODE_PROCOPEN = 1;
const MODE_POPEN = 2;
const MODE_FORKED = 3;
private $Mode = qcEvents_Process::MODE_PROCOPEN;
/* Internal process-handle */
private $Process = null;
/* Exit-Code to process */
private $exitCode = null;
/* Callback after process finished */
private $Callback = null;
private $Private = null;
/* PID of our child */
private $childPID = 0;
/* Path to child-fifos */
private $childReadPath = '';
private $childWritePath = '';
private $hasRead = false;
// {{{ __construct
/**
* Create an Event-Handler and spawn a process
*
* @param qcEvents_Base $Base (optional)
* @param string $Command (optional)
* @param mixed $Params (optional)
*
* @access friendly
* @return void
**/
function __construct (qcEvents_Base $Base = null, $Command = null, $Params = null, callable $Callback = null, $Private = null) {
// Don't do anything withour an events-base
if ($Base === null)
return;
// Set our handler
$this->setEventBase ($Base);
// Spawn the command if requested
if ($Command !== null)
$this->spawnCommand ($Command, $Params, $Callback, $Private);
}
// }}}
// {{{ toCommandline
/**
* Create a full commandline from separated args
*
* @param string $Command
* @param mixed $Params
*
* @access private
* @return string
**/
private function toCommandline ($Command, $Params = null) {
// Create the command-line
$cmdline = escapeshellcmd ($Command);
// Append parameters
if (is_array ($Params))
foreach ($Params as $P)
$cmdline .= ' ' . escapeshellarg ($P);
elseif (is_string ($Params))
$cmdline .= ' ' . escapeshellarg ($Params);
return $cmdline;
}
// }}}
// {{{ spawnCommand
/**
* Execute the command
*
* @param string $Command
* @param array $Params (optional)
* @param callable $Callback (optional)
* @param mixed $Private (optional)
*
* @access public
* @return bool
**/
public function spawnCommand ($Command, $Params = null, callable $Callback = null, $Private = null) {
// Spawn using proc_open
if (function_exists ('proc_open')) {
// Try to spawn the command
$Descriptors = array (
0 => array ('pipe', 'r'),
1 => array ('pipe', 'w'),
2 => STDERR,
);
if (!is_resource ($this->Process = proc_open ($this->toCommandline ($Command, $Params), $Descriptors, $Pipes))) {
trigger_error ('Could not spawn command');
return false;
}
$this->Mode = self::MODE_PROCOPEN;
$this->exitCode = null;
$this->Callback = $Callback;
$this->Private = $Private;
// Register FDs
if (!$this->setStreamFDs ($Pipes [1], $Pipes [0]))
return false;
// Spawn using popen
} elseif (function_exists ('popen')) {
// Start the command
if (!is_resource ($fd = popen ($this->toCommandline ($Command, $Params), 'r')))
return false;
$this->Mode = self::MODE_POPEN;
$this->exitCode = null;
// Register FDs
if (!$this->setStreamFD ($fd))
return false;
// Try to spawn forked
} elseif (!$this->spawnCommandForked ($Command, $Params))
return false;
return true;
}
// }}}
// {{{ spawnCommandForked
/**
* Execute a command using fork()
*
* @param string $Command
* @param array $Params (optional)
*
* @access private
* @return bool
**/
private function spawnCommandForked ($Command, $Params = null) {
// Check if we are able to fork
if (!function_exists ('pcntl_fork'))
return false;
// Setup FIFOs
# TODO: Don't hardcode /tmp here
$fifo_in = tempnam ('/tmp', 'qcEventProcess');
$fifo_out = tempnam ('/tmp', 'qcEventProcess');
if (function_exists ('posix_mkfifo')) {
posix_mkfifo ($fifo_in, 600);
posix_mkfifo ($fifo_out, 600);
}
if (!is_resource ($fd_in = @fopen ($fifo_in, 'r')) ||
!is_resource ($fd_out = @fopen ($fifo_out, 'w'))) {
@unlink ($fifo_in);
@unlink ($fifo_out);
return false;
}
// Do the fork
if (($pid = pcntl_fork ()) < 0) {
fclose ($fd_in);
fclose ($fd_out);
@unlink ($fifo_in);
@unlink ($fifo_out);
return false;
}
// We are the child
if ($pid == 0) {
$rc = 0;
// Redirect the output
global $STDOUT, $STDIN;
fclose ($fd_in);
fclose ($fd_out);
fclose (STDOUT);
fclose (STDIN);
if (!is_resource ($STDOUT = fopen ($fifo_in, 'w')))
exit (1);
if (!is_resource ($STDIN = fopen ($fifo_out, 'r')))
exit (1);
// Spawn the process
if (function_exists ('pcntl_exec')) {
pcntl_exec ($Command, $Params);
$rc = 1; // If we get here pcntl_exec failed!
} elseif (function_exists ('passthru'))
passthru ($this->toCommandline ($Command, $Params), $rc);
elseif (function_exists ('system'))
system ($this->toCommandline ($Command, $Params), $rc);
exit ($rc);
}
// Setup the parent
$this->Mode = self::MODE_FORKED;
if (!$this->setStreamFDs ($fd_in, $fd_out)) {
fclose ($fd_in);
fclose ($fd_out);
@unlink ($fifo_in);
@unlink ($fifo_out);
return false;
}
$this->childPID = $pid;
$this->childReadPath = $fifo_in;
$this->childWritePath = $fifo_out;
return true;
}
// }}}
// {{{ finishConsume
/**
* Stop being piped from somewhere and "exit"
*
* @access public
* @return void
**/
public function finishConsume () {
$this->addHook ('eventDrained', function () {
$this->closeWriter ();
}, null, true);
}
// }}}
// {{{ ___read
/**
* Read from the underlying stream
*
* @param int $Length (optional)
*
* @access protected
* @return string
**/
protected function ___read ($Length = null) {
// Determine how many bytes to read
if ($Length === null)
$Length = $this::DEFAULT_READ_LENGTH;
// Try to access our read-fd
if (!is_resource ($fd = $this->getReadFD ()))
return false;
// Try to read from process
if (is_string ($Data = fread ($fd, $Length)) && (strlen ($Data) == 0) && feof ($fd))
return $this->close ();
// Return the read data
$this->hasRead = true;
return $Data;
}
// }}}
// {{{ ___write
/**
* Forward data for writing to our socket
*
* @param string $Data
*
* @access private
* @return int Number of bytes written
**/
protected function ___write ($Data) {
return fwrite ($this->getWriteFD (), $Data);
}
// }}}
public function closeWriter () {
if (is_resource ($fd = $this->getWriteFD (true)))
fclose ($fd);
$this->setStreamFD ($this->getReadFD ());
}
// {{{ ___close
/**
* Close the stream at the handler
*
* @access protected
* @return bool
**/
protected function ___close () {
if ($this->Mode == self::MODE_PROCOPEN) {
// Close our pipes first
if (is_resource ($fd = $this->getReadFD ()))
fclose ($fd);
if (is_resource ($fd = $this->getWriteFD ()))
fclose ($fd);
// Try to terminate normally
proc_terminate ($this->Process);
// Wait for the process to exit
# TODO: Make this async
for ($i = 0; $i < 1000; $i++) {
// Retrive the status of the process
$status = proc_get_status ($this->Process);
// Try to remember an exit-code for this process
if ($status ['exitcode'] >= 0)
$this->exitCode = $status ['exitcode'];
// Check if the process is still running
if (!$status ['running'])
break;
// Spend a little time waiting
usleep (2000);
}
// Check if the process is still running
if ($status ['running']) {
proc_terminate ($this->Process, SIGKILL);
// Try to get an exit-code
$status = proc_get_status ($this->Process);
if ($status ['exitcode'] >= 0)
$this->exitCode = $status ['exitcode'];
}
if ($this->Callback)
call_user_func ($this->Callback, $this, $this->exitCode, $this->Private);
return true;
}
if ($this->Mode == self::MODE_POPEN) {
$this->exitCode = pclose ($this->getReadFD ());
if ($this->Callback)
call_user_func ($this->Callback, $this, $this->exitCode, $this->Private);
return ($this->exitCode >= 0);
}
if ($this->Mode == self::MODE_FORKED) {
if (($this->childPID > 0) && function_exists ('posix_kill'))
posix_kill ($this->childPID);
// Close our pipes first
if (is_resource ($fd = $this->getReadFD ()))
fclose ($fd);
if (is_resource ($fd = $this->getWriteFD ()))
fclose ($fd);
@unlink ($this->childReadPath);
@unlink ($this->childWritePath);
}
return true;
}
// }}}
// {{{ raiseRead
/**
* Callback: The Event-Loop detected a read-event
*
* @access public
* @return void
**/
public function raiseRead () {
// Check if we can detect a finished process
if ($this->Mode == self::MODE_PROCOPEN) {
$Status = proc_get_status ($this->Process);
// Exit if the process is not running anymore
if (!$Status ['running']) {
// Store exit-code if there is a valid one
if ($Status ['exitcode'] >= 0)
$this->exitCode = $Status ['exitcode'];
// Make sure the read-buffer is empty
$this->hasRead = false;
parent::raiseRead ();
// Don't close if the emited event triggered a read()
// The read()-Handler will trigger a close on its own when no data is available any more
if ($this->hasRead)
return;
// Close if nothing was read
return $this->close ();
}
}
// Inherit to our parent (and emit events)
parent::raiseRead ();
}
// }}}
}
?>