Skip to content

Commit

Permalink
Merge pull request #34 from mateusjunges/cleanup-terminated-processes
Browse files Browse the repository at this point in the history
Do not track terminated proccesses
  • Loading branch information
aarondfrancis authored Dec 1, 2024
2 parents 755cf23 + b6c6ef5 commit 8357ed7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/Console/Commands/Monitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use AaronFrancis\Solo\Support\ProcessTracker;
use Illuminate\Console\Command;
use Illuminate\Support\Carbon;

class Monitor extends Command
{
Expand All @@ -24,6 +25,11 @@ public function handle()
...ProcessTracker::children($parent)
]);

// Every 10 seconds cull the children that are no longer running.
if (Carbon::now()->second % 10 === 0) {
$children = ProcessTracker::running($children);
}

sleep(1);

if (ProcessTracker::isRunning($parent)) {
Expand Down
35 changes: 35 additions & 0 deletions src/Support/ProcessTracker.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,41 @@ public static function isRunning($pid)
return count($output) > 0;
}


/**
* Return all the PIDs that are running.
*
* @param array $pids Array of PIDs to check.
* @return array Associative array with PIDs as keys and boolean as values indicating if they are running.
*/
public static function running(array $pids): array
{
$pids = array_filter($pids, 'is_numeric');

if (empty($pids)) {
return [];
}

$pids = array_unique($pids);
$pids = array_map('intval', $pids);

// Construct the ps command to check multiple PIDs at once
// -p specifies the PIDs to check
// -o pid= outputs only the PID without headers
exec("ps -p " . implode(',', $pids) . " -o pid=", $output, $returnCode);

// Handle potential errors in executing the ps command
if ($returnCode !== 0 && !empty($output)) {
throw new RuntimeException("Error executing ps command: " . implode("\n", $output));
}

// Trim whitespace and filter out any non-numeric entries from the output
$runningPids = array_filter(array_map('trim', $output), 'is_numeric');

// Convert running PIDs to integers for accurate comparison
return array_map('intval', $runningPids);
}

public static function getProcessList()
{
$output = [];
Expand Down

0 comments on commit 8357ed7

Please sign in to comment.