Categories: Development

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;
    }
}

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago