Skip to content

Commit 466e447

Browse files
committed
Implement Unix isRunning()
1 parent 2fe2494 commit 466e447

File tree

1 file changed

+51
-3
lines changed

1 file changed

+51
-3
lines changed

src/AsyncTaskStatus.php

Lines changed: 51 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
namespace Vectorial1024\LaravelProcessAsync;
66

77
use InvalidArgumentException;
8+
use loophp\phposinfo\OsInfo;
9+
use RuntimeException;
810

911
/**
1012
* Represents the status of an async task: "running" or "stopped".
@@ -98,7 +100,42 @@ private function proveTaskIsRunning(): bool
98100
*/
99101
private function findTaskRunnerProcess(): bool
100102
{
101-
// todo
103+
if (OsInfo::isWindows()) {
104+
// todo Windows
105+
return false;
106+
}
107+
// assume anything not Windows to be Unix
108+
// find the runner on Unix systems via pgrep
109+
// we might have multiple PIDs, so do store them in an array
110+
$results = [];
111+
$encodedTaskID = $this->getEncodedTaskID();
112+
exec("pgrep -f id='$encodedTaskID'", $results);
113+
// supposedly there should be only 1 entry, but anyway
114+
$expectedCmdName = "artisan async:run";
115+
foreach ($results as $candidatePID) {
116+
$candidatePID = (int) $candidatePID;
117+
// then use ps to see what really is it
118+
$fullCmd = exec("ps -p $candidatePID -o args=");
119+
if ($fullCmd === false) {
120+
throw new RuntimeException("Could not query whether the AsyncTask is still running.");
121+
}
122+
if (!str_contains($fullCmd, $expectedCmdName)) {
123+
// not really
124+
continue;
125+
}
126+
$executable = exec("ps -p $candidatePID -o comm=");
127+
if ($executable === false) {
128+
throw new RuntimeException("Could not query whether the AsyncTask is still running.");
129+
}
130+
if ($executable !== "php") {
131+
// not really
132+
// note: we currently hard-code "php" as the executable name
133+
continue;
134+
}
135+
// this is it!
136+
$this->lastKnownPID = $candidatePID;
137+
return true;
138+
}
102139
return false;
103140
}
104141

@@ -108,7 +145,18 @@ private function findTaskRunnerProcess(): bool
108145
*/
109146
private function observeTaskRunnerProcess(): bool
110147
{
111-
// todo
112-
return false;
148+
if (OsInfo::isWindows()) {
149+
// todo Windows
150+
return false;
151+
}
152+
// assume anything not Windows to be Unix
153+
// since we should have remembered the PID, we can just query whether it still exists
154+
// supposedly, the PID has not rolled over yet, right...?
155+
$echoedPid = exec("ps -p {$this->lastKnownPID} -o pid=");
156+
if ($echoedPid === false) {
157+
throw new RuntimeException("Could not query whether the AsyncTask is still running.");
158+
}
159+
$echoedPid = (int) $echoedPid;
160+
return $this->lastKnownPID === $echoedPid;
113161
}
114162
}

0 commit comments

Comments
 (0)