Linux/Unix command to determine if process is running?

后端 未结 14 990
忘掉有多难
忘掉有多难 2020-11-28 01:54

I need a platform independent (Linux/Unix|OSX) shell/bash command that will determine if a specific process is running. e.g. mysqld, httpd... What

14条回答
  •  忘掉有多难
    2020-11-28 02:22

    The following shell function, being only based on POSIX standard commands and options should work on most (if not any) Unix and linux system. :

    isPidRunning() {
      cmd=`
        PATH=\`getconf PATH\` export PATH
        ps -e -o pid= -o comm= |
          awk '$2 ~ "^.*/'"$1"'$" || $2 ~ "^'"$1"'$" {print $1,$2}'
      `
      [ -n "$cmd" ] &&
        printf "%s is running\n%s\n\n" "$1" "$cmd" ||
        printf "%s is not running\n\n" $1
      [ -n "$cmd" ]
    }
    

    $ isPidRunning httpd
    httpd is running
    586 /usr/apache/bin/httpd
    588 /usr/apache/bin/httpd
    
    $ isPidRunning ksh
    ksh is running
    5230 ksh
    
    $ isPidRunning bash
    bash is not running
    

    Note that it will choke when passed the dubious "0]" command name and will also fail to identify processes having an embedded space in their names.

    Note too that the most upvoted and accepted solution demands non portable ps options and gratuitously uses a shell that is, despite its popularity, not guaranteed to be present on every Unix/Linux machine (bash)

提交回复
热议问题