As a way to build a poor-man\'s watchdog and make sure an application is restarted in case it crashes (until I figure out why), I need to write a PHP CLI script that will be
<?php
function check_if_process_is_running($process)
{
exec("/bin/pidof $process",$response);
if ($response)
{
return true;
} else
{
return false;
}
}
if (check_if_process_is_running("mysqld"))
{
echo "MySQL is running";
} else
{
echo "Mysql stopped";
}
?>
To check whether process is running by its name, you can use pgrep
, e.g.
$is_running = shell_exec("pgrep -f lighttpd");
or:
exec("pgrep lighttpd", $output, $return);
if ($return == 0) {
echo "Ok, process is running\n";
}
as per this post.
If you know the PID of the process, you can use one the following functions:
/**
* Checks whether the process is running.
*
* @param int $pid Process PID.
* @return bool
*/
public static function isProcessRunning($pid) {
// Calling with 0 kill signal will return true if process is running.
return posix_kill((int) $pid, 0);
}
/**
* Get the command of the process.
* For example apache2 in case that's the Apache process.
*
* @param int $pid Process PID.
* @return string
*/
public static function getProcessCommand($pid) {
$pid = (int) $pid;
return trim(shell_exec("ps o comm= $pid"));
}
Related: How to check whether specified PID is currently running without invoking ps from PHP?
i have a function to get the pid of a process...
function getRunningPid($processName) {
$pid = 0;
$processes = array();
$command = 'ps ax | grep '.$processName;
exec($command, $processes);
foreach ($processes as $processString) {
$processArr = explode(' ', trim($processString));
if (
(intval($processArr[0]) != getmypid())&&
(strpos($processString, 'grep '.$processName) === false)
) {
$pid = intval($processArr[0]);
}
}
return $pid;
}