This repository was archived by the owner on Feb 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.php
More file actions
73 lines (64 loc) · 1.45 KB
/
task.php
File metadata and controls
73 lines (64 loc) · 1.45 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
<?php
namespace Task;
/**
* Function to fork a task from the main thread, execute its task and return the pid
* @param callable $taskClosure
* @param array $arguments
* @return mixed
*/
function forkTask(
callable $taskClosure,
array $arguments = [],
callable $signalHandler = null
) {
// allow signal passing
pcntl_signal_dispatch();
$processId = pcntl_fork();
if ($processId === -1) {
throw new Exception('The task could not be forked off.');
}
// ingore child termination event
if ($signalHandler !== null) {
pcntl_signal(SIGTERM, $signalHandler);
pcntl_signal(SIGCHLD, $signalHandler);
}
if ($processId === 0) {
call_user_func_array($taskClosure, $arguments);
exit(0);
}
if (
$processId !== -1
&& $processId !== 0
) {
return $processId;
}
}
/**
* Function to check the status of a process by process id
* @param int $processId
* @param int $status
* @return int|null
*/
function getProcessStatus($processId = null, &$status = null) {
if ($processId === null) {
return null;
}
return pcntl_waitpid($processId, $status, WNOHANG);
}
/**
* Function to check if a process succeeded
* @param int|null $processId
* @return bool
*/
function checkSuccess($processId = null): bool {
$state = getProcessStatus($processId);
return $state > 0;
}
/**
* Function to close a fork by process id
* @param int $processId
* @return bool
*/
function closeTask(int $processId): bool {
return posix_kill($processId, SIGQUIT);
}