How to check whether specified PID is currently running without invoking ps from PHP?

好久不见. 提交于 2019-11-28 22:32:09

If you are on Linux, try this :

if (file_exists( "/proc/$pid" )){
    //process with a pid = $pid is running
}

posix_getpgid($pid); will return false when a process is not running

Steel Brain

If you want to have a function for it then:

$running = posix_kill($pid,0);

Send the signal sig to the process with the process identifier pid.

Calling posix_kill with the 0 kill signal will return true if the process is running, false otherwise.

I would call a bash script using shell_exec

$pid = 23818;
if (shell_exec("ps aux | grep " . $pid . " | wc -l") > 0)
{
    // do something
}

I think posix_kill(posix_getpgrp(), 0) is the best way to check if PID is running, it's only not available on Windows platforms.

It's the same to kill -0 PID on shell, and shell_exec('kill -0 PID') on PHP but NO ERROR output when pid is not exists.

In forked child process, the posix_getpgid return parent's pid always even if parent was terminated.

<?php

$pid = pcntl_fork();

if ($pid === -1) {
    exit(-1);
} elseif ($pid === 0) {
    echo "in child\n";
    while (true) {
        $pid = posix_getpid();
        $pgid = posix_getpgid($pid);
        echo "pid: $pid\tpgid: $pgid\n";
        sleep(5);
    }
} else {
    $pid = posix_getpid();
    echo "parent process pid: $pid\n";
    exit("parent process exit.\n");
}

i have done a script for this, which im using in wordpress to show game-server status, but this will work with all running process on the server

<?php
//##########################################
// desc: Diese PHP Script zeig euch ob ein Prozess läuft oder nicht
// autor: seevenup
// version: 0.2
//##########################################

if (!function_exists('server_status')) {
        function server_status($string,$name) {
                $pid=exec("pidof $name");
                exec("ps -p $pid", $output);

                if (count($output) > 1) {
                        echo "$string: <font color='green'><b>RUNNING</b></font><br>";
                }
                else {
                        echo "$string: <font color='red'><b>DOWN</b></font><br>";
                }
        }
}

//Beispiel "Text zum anzeigen", "Prozess Name auf dem Server"
server_status("Running With Rifles","rwr_server");
server_status("Starbound","starbound_server");
server_status("Minecraft","minecarf");
?>

more information here http://umbru.ch/?p=328

//For Linux
$pid='475678';
exec('ps -C php -o pid', $a);
if(in_array($pid, $a)){
    // do something...
}

Here is how we do it:

if (`ps -p {$pid} -o comm,args=ARGS | grep php`) {

  //process with pid=$pid is running;
}
$pid = 12345;
if (shell_exec("ps ax | grep " . $pid . " | grep -v grep | wc -l") > 0)
{
    // do something
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!