Linux 检查进程是否仍在运行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3111406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 20:10:06  来源:igfitidea点击:

Checking if process still running?

phplinuxprocessexec

提问by Gulbahar

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 run by cron every 5mn to check whether the process is still running.

作为构建穷人看门狗并确保应用程序在崩溃时重新启动(直到我弄清楚原因)的一种方法,我需要编写一个 PHP CLI 脚本,该脚本将由 cron 每 500 万次运行一次以检查进程是否仍在运行。

Based on this page, I tried the following code, but it always returns True even if I call it with bogus data:

基于此页面,我尝试了以下代码,但即使我使用虚假数据调用它,它也始终返回 True:

function processExists($file = false) {
    $exists= false;
    $file= $file ? $file : __FILE__;

    // Check if file is in process list
    exec("ps -C $file -o pid=", $pids);
    if (count($pids) > 1) {
    $exists = true;
    }
    return $exists;
}

#if(processExists("lighttpd"))
if(processExists("dummy"))
    print("Exists\n")
else
    print("Doesn't exist\n");

Next, I tried this code...

接下来,我尝试了这段代码......

(exec("ps -A | grep -i 'lighttpd -D' | grep -v grep", $output);)
print $output;

... but don't get what I expect:

......但没有得到我的期望:

/tmp> ./mycron.phpcli 
Arrayroot:/tmp> 

FWIW, this script is run with the CLI version of PHP 5.2.5, and the OS is uClinux 2.6.19.3.

FWIW,此脚本使用 PHP 5.2.5 的 CLI 版本运行,操作系统为 uClinux 2.6.19.3。

Thank you for any hint.

谢谢你的任何提示。



Edit: This seems to work fine

编辑:这似乎工作正常

exec("ps aux | grep -i 'lighttpd -D' | grep -v grep", $pids);
if(empty($pids)) {
        print "Lighttpd not running!\n";
} else {
        print "Lighttpd OK\n";
}

采纳答案by mmattax

I'd use pgrepto do this (caution, untested code):

我习惯pgrep这样做(注意,未经测试的代码):


exec("pgrep lighttpd", $pids);
if(empty($pids)) {

    // lighttpd is not running!
}

I have a bash script that does something similar (but with SSH tunnels):

我有一个执行类似操作的 bash 脚本(但使用 SSH 隧道):


#!/bin/sh

MYSQL_TUNNEL="ssh -f -N -L 33060:127.0.0.1:3306 tunnel@db"
RSYNC_TUNNEL="ssh -f -N -L 8730:127.0.0.1:873 tunnel@db"

# MYSQL
if [ -z `pgrep -f -x "$MYSQL_TUNNEL"` ] 
then
    echo Creating tunnel for MySQL.
    $MYSQL_TUNNEL
fi

# RSYNC
if [ -z `pgrep -f -x "$RSYNC_TUNNEL"` ]
then
    echo Creating tunnel for rsync.
    $RSYNC_TUNNEL
fi


You could alter this script with the commands that you want to monitor.

您可以使用要监视的命令更改此脚本。

回答by John Lawrence

You can try this, which combines bits of those two approaches:

你可以试试这个,它结合了这两种方法的一部分:

function processExists($processName) {
    $exists= false;
    exec("ps -A | grep -i $processName | grep -v grep", $pids);
    if (count($pids) > 0) {
        $exists = true;
    }
    return $exists;
}

If that doesn't work, you may want to just try running the ps command on your system and seeing what output it gives.

如果这不起作用,您可能只想尝试在您的系统上运行 ps 命令并查看它给出的输出。

回答by Sergey Eremin

i have a function to get the pid of a process...

我有一个函数来获取进程的pid...

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

回答by ircmaxell

If you're doing it in php, why not use php code:

如果您是在 php 中执行此操作,为什么不使用 php 代码:

In the running program:

在运行程序中:

define('PIDFILE', '/var/run/myfile.pid');

file_put_contents(PIDFILE, posix_getpid());
function removePidFile() {
    unlink(PIDFILE);
}
register_shutdown_function('removePidFile');   

Then, in the watchdog program, all you need to do is:

然后,在看门狗程序中,你需要做的就是:

function isProcessRunning($pidFile = '/var/run/myfile.pid') {
    if (!file_exists($pidFile) || !is_file($pidFile)) return false;
    $pid = file_get_contents($pidFile);
    return posix_kill($pid, 0);
}

Basically, posix_killhas a special signal 0that doesn't actually send a signal to the process, but it does check to see if a signal can be sent (the process is actually running).

基本上,posix_kill有一个特殊的信号0,它实际上并不向进程发送信号,但它会检查是否可以发送信号(进程实际上正在运行)。

And yes, I do use this quite often when I need long running (or at least watchable) php processes. Typically I write init scripts to start the PHP program, and then have a cron watchdog to check hourly to see if it's running (and if not restart it)...

是的,当我需要长时间运行(或至少是可观察的)php 进程时,我确实经常使用它。通常我编写 init 脚本来启动 PHP 程序,然后有一个 cron 看门狗每小时检查一次,看看它是否正在运行(如果没有重新启动它)...

回答by Softmixt

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

?>

回答by Anatoly Rugalev

Try this one

试试这个

function processExists ($pid) {
    return file_exists("/proc/{$pid}");
}

Function checks whether process file is exists in /proc/root directory. Works for Linux only

函数检查进程文件是否存在于/proc/根目录中。仅适用于 Linux

回答by Destreyf

I didn't see this mentioned here, but here's another approach taking the second grep out of the equation, i use this with alot of my PHP scripts and should work universally

我没有看到这里提到的,但这是另一种方法,将第二个 grep 排除在等式之外,我将它与我的很多 PHP 脚本一起使用,并且应该普遍适用

exec("ps aux | grep -i '[l]ighttpd -D'", $pids);
if(empty($pids)) {
        print "Lighttpd not running!\n";
} else {
        print "Lighttpd OK\n";
}

Enjoy.

享受。

回答by Sven Lauber

The main problem is the if you run a php script, the exec command will be run as the web-servers user (www-data); this user can't see pid's from other users, unless you use "pidof"

主要问题是如果你运行一个 php 脚本,exec 命令将作为 web-servers 用户(www-data)运行;此用户无法看到其他用户的 pid,除非您使用“pidof”

<?php
//##########################################
// desc: Diese PHP Script zeig euch ob ein Prozess l?uft oder nicht
// autor: seevenup
// version: 1.3
// info: Da das exec kommando als apache user (www-data) ausgefuert
//       wird, muss pidof benutzt werden da es prozesse von
//       anderen usern anzeigen kann
//##########################################

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 about the script here http://umbru.ch/?p=328

有关此处脚本的更多信息http://umbru.ch/?p=328

回答by kenorb

To check whether process is running by its name, you can use pgrep, e.g.

要检查进程是否按其名称运行,您可以使用pgrep,例如

$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:

如果您知道进程的 PID,则可以使用以下函数之一:

  /**
   * 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?

相关:如何在不从 PHP 调用 ps 的情况下检查指定的 PID 当前是否正在运行?