Check if a process is running on Linux with PHP

Check if a process is running on a Linux system such as Ubuntu by using PHP. This is done by using pgrep and checking if its response is empty.

pgrep looks through the currently running processes for a match to the search criteria, the search criteria is what comes after pgrep.

To check for FFmpeg running you would do pgrep FFmpeg and it would return all the process id’s (PID) for instances of FFmpeg running.

echo shell_exec("pgrep youtube-dl");

The above command is if youtube-dl has at least one instance running then the process id/s will be returned.

Now for a check to simply return yes or no upon the process running:

if (empty(trim(shell_exec("pgrep youtube-dl")))) {
    echo "No";
} else {
    echo "Yes";
}

If youtube-dl was not running then the shell_exec would be empty because it is not returning a PID, it returns No in this case.

Here it is put into a function that can be re-used fro different process names i.e FFmpeg, Wget, PHP etc:

function processRunning(string $process): bool
{
    if (empty(trim(shell_exec("pgrep $process")))) {
        return false;
    } else {
        return true;
    }
}