TL;DR
posix_getpgid($pid)
を使うのがオススメ
PHPでPIDがあるか確認する方法はいくつかあるが、最速を検討する
<?php
// cf. https://stackoverflow.com/questions/9874331/how-to-check-whether-specified-pid-is-currently-running-without-invoking-ps-from
$pid_max = file_get_contents('/proc/sys/kernel/pid_max');
$pids = array_map(fn()=>random_int(1, $pid_max), range(1,2**20));
$start = microtime(true);
foreach ($pids as $pid) {
file_exists("/proc/$pid");
}
echo "file_exists:\t" . microtime(true) - $start . PHP_EOL;
$start = microtime(true);
foreach ($pids as $pid) {
is_dir("/proc/$pid");
}
echo "is_dir:\t\t" . microtime(true) - $start . PHP_EOL;
$start = microtime(true);
foreach ($pids as $pid) {
posix_getpgid($pid);
}
echo "posix_getpgid:\t" . microtime(true) - $start . PHP_EOL;
$start = microtime(true);
foreach ($pids as $pid) {
posix_kill($pid, 0);
}
echo "posix_kill:\t" . microtime(true) - $start . PHP_EOL;
結果
$ seq 10 | xargs -n1 php pid_perf.php
file_exists: 2.1520388126373
is_dir: 1.6568348407745
posix_getpgid: 0.12570405006409
posix_kill: 0.14235901832581
file_exists: 2.1547100543976
is_dir: 1.6315920352936
posix_getpgid: 0.12148284912109
posix_kill: 0.14736986160278
file_exists: 2.121838092804
is_dir: 1.6587860584259
posix_getpgid: 0.12204599380493
posix_kill: 0.13927102088928
file_exists: 2.1496820449829
is_dir: 1.6658518314362
posix_getpgid: 0.12524199485779
posix_kill: 0.14765810966492
file_exists: 2.1388080120087
is_dir: 1.6538898944855
posix_getpgid: 0.12666511535645
posix_kill: 0.14308190345764
file_exists: 2.0925102233887
is_dir: 1.7037389278412
posix_getpgid: 0.12445998191833
posix_kill: 0.13687419891357
file_exists: 2.0917370319366
is_dir: 1.6500859260559
posix_getpgid: 0.1252658367157
posix_kill: 0.14215397834778
file_exists: 2.0797710418701
is_dir: 1.6966879367828
posix_getpgid: 0.12555503845215
posix_kill: 0.14388394355774
file_exists: 2.099790096283
is_dir: 1.6563739776611
posix_getpgid: 0.12412095069885
posix_kill: 0.14297080039978
file_exists: 2.0959348678589
is_dir: 1.6471560001373
posix_getpgid: 0.12421989440918
posix_kill: 0.13587403297424
https://docs.google.com/spreadsheets/d/1eBSfgY25oLwCth579y-LXDclXpoeNCx4crK9x8ypazE/edit?usp=sharing