Skip to content

Instantly share code, notes, and snippets.

@Garciat
Created February 20, 2025 19:21
Show Gist options
  • Save Garciat/48ca4c3394e26642b746f5861faca2d1 to your computer and use it in GitHub Desktop.
Save Garciat/48ca4c3394e26642b746f5861faca2d1 to your computer and use it in GitHub Desktop.
Manage your VS Code Remote Tunnel with PHP.
<?php
function println($s)
{
echo "$s\n";
}
function shell_exec_trim($cmd, $nonzero_throw = true)
{
$lines = array();
if (exec($cmd, $lines, $code) === false) {
throw new Exception("exec() failure");
}
if ($code !== 0 && $nonzero_throw) {
throw new Exception("`$cmd` exited with non-zero code: $code");
}
return trim(implode("\n", $lines));
}
function pchildren($p)
{
$t = shell_exec_trim("pgrep -P $p", nonzero_throw: false);
if (!$t) return array();
return explode("\n", $t);
}
function pall($p)
{
if (!$p) return array();
$ps = array($p);
foreach (pchildren($p) as $c) {
array_push($ps, ...pall($c));
}
return $ps;
}
function main()
{
$cmd = "/home/garciat/vscode/code tunnel";
$pid = shell_exec_trim("pgrep -f '$cmd'", nonzero_throw: false);
println("<pre>");
if ($pid) {
println("Running: $pid");
} else {
println("Not running");
}
$all_pids = pall($pid);
foreach ($all_pids as $p) {
println(shell_exec_trim("ps -o pid=,command= -p $p"));
}
if (isset($_GET["kill"])) {
if (!$pid) {
exit;
}
foreach ($all_pids as $p) {
println("Killing $p");
shell_exec_trim("kill -TERM $p");
}
} else {
if ($pid) {
exit;
}
println("Starting");
shell_exec_trim("$cmd 2>/dev/null >/dev/null &");
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment