phpsignals

get signal name from signal number in PHP


Lets say I have a signal number, let's say it is 15, how can I get that back to a signal name? (on Linux, 15 is SIGTERM, so in this case if running on Linux, I would like the string "SIGTERM")


Solution

  • Linux has char *strsignal(int sig), unfortunately seems like PHP doesn't, but with get_defined_constants(true), one could probably implement something similar, here is my attempt:

    function strsignal(int $signo): ?string
    {
        foreach (get_defined_constants(true)['pcntl'] as $name => $num) {
            // the _ is to ignore SIG_IGN and SIG_DFL and SIG_ERR and SIG_BLOCK and SIG_UNBLOCK and SIG_SETMARK, and maybe more, who knows
            if ($num === $signo && strncmp($name, "SIG", 3) === 0 && $name[3] !== "_") {
                return $name;
            }
        }
        return null;
    }
    

    and var_dump(strsignal(15)); returns string(7) "SIGTERM"

    :)