Programing

프로세스가 실행 중인지 확인하는 Linux / Unix 명령?

lottogame 2020. 8. 31. 08:21
반응형

프로세스가 실행 중인지 확인하는 Linux / Unix 명령?


특정 프로세스가 실행 중인지 확인하는 플랫폼 독립적 (Linux / Unix | OSX) 셸 / bash 명령이 필요합니다. mysqld, httpd...이 작업을 수행하는 가장 간단한 방법 / 명령은 무엇입니까?


동안 pidofpgrep실행의 무엇을 결정하기위한 훌륭한 도구, 그들은 불행하게도, 모두 일부 운영 체제에서 사용할 수 없습니다. 확실한 안전 장치는 다음을 사용하는 것입니다.ps cax | grep command

Gentoo Linux의 출력 :

14484? S 0:00 apache2
14667? S 0:00 apache2
19620? SL 0:00 apache2
21132? SS 0:04 apache2

OS X의 출력 :

42582? Z 0 : 00.00 (smbclient)
46529 ?? Z 0 : 00.00 (smbclient)
46539 ?? Z 0 : 00.00 (smbclient)
46547? Z 0 : 00.00 (smbclient)
46586 ?? Z 0 : 00.00 (smbclient)
46594? Z 0 : 00.00 (smbclient)

Linux와 OS X 모두에서 grep은 종료 코드를 반환하므로 프로세스가 발견되었는지 여부를 쉽게 확인할 수 있습니다.

#!/bin/bash
ps cax | grep httpd > /dev/null
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

또한 PID 목록을 원하면 해당 PID도 쉽게 grep 할 수 있습니다.

ps cax | grep httpd | grep -o '^ [] * [0-9] *'

Linux 및 OS X에서 동일한 출력 :

3519 3521 3523 3524

다음의 출력은 빈 문자열로, 실행되지 않는 프로세스에 대해이 접근 방식을 안전하게 만듭니다.

에코 ps cax | grep aasdfasdf | grep -o '^[ ]*[0-9]*'

이 접근 방식은 간단한 빈 문자열 테스트를 작성한 다음 발견 된 PID를 반복하는 데 적합합니다.

#!/bin/bash
PROCESS=$1
PIDS=`ps cax | grep $PROCESS | grep -o '^[ ]*[0-9]*'`
if [ -z "$PIDS" ]; then
  echo "Process not running." 1>&2
  exit 1
else
  for PID in $PIDS; do
    echo $PID
  done
fi

실행 권한 (chmod + x 실행 중)을 사용하여 파일 ( "실행 중"이라고 함)에 저장하고 매개 변수로 실행하여 테스트 할 수 있습니다. ./running "httpd"

#!/bin/bash
ps cax | grep httpd
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

경고!!!

ps axLinux 출력에서 ​​볼 수 있듯이 단순히 출력을 구문 분석하고 있다는 것을 명심하십시오. 이는 Linux 출력에서 ​​볼 수 있듯이 단순히 프로세스에서 일치하는 것이 아니라 해당 프로그램에 전달 된 인수도 일치한다는 것을 의미합니다. 이 방법을 사용할 때 가능한 한 구체적으로 작성하는 것이 좋습니다 (예 : ./running "mysql"'mysqld'프로세스와도 일치). which가능한 경우 전체 경로를 확인 하는 사용 하는 것이 좋습니다 .


참조 :

http://linux.about.com/od/commands/l/blcmdl1_ps.htm

http://linux.about.com/od/commands/l/blcmdl1_grep.htm


PID를 알아야합니다!

프로세스 인수 (예 :)에 대해 일종의 패턴 인식을 시도하여 프로세스를 찾는 것은 pgrep "mysqld"조만간 실패 할 운명의 전략입니다. 두 개의 mysqld가 실행되고 있다면 어떨까요? 그 접근법은 잊어 버리세요. 일시적으로 문제를 해결하고 1 ~ 2 년 동안 작동 할 수 있지만 생각하지 못한 일이 발생합니다.

프로세스 ID (pid) 만 진정으로 고유합니다.

백그라운드에서 무언가를 시작할 때 항상 pid를 저장하십시오. Bash에서는 Bash $!변수를 사용하여 수행 할 수 있습니다 . 그렇게함으로써 많은 문제를 해결할 수 있습니다.

프로세스가 실행 중인지 확인하는 방법 (pid로)

이제 질문은 pid가 실행 중인지 아는 방법이됩니다.

간단하게 :

ps -o pid = -p <pid>

이것은 POSIX이므로 이식 가능합니다. 프로세스가 실행 중이면 pid 자체를 반환하고 프로세스가 실행 중이 아니면 아무것도 반환하지 않습니다. 엄밀히 말하면이 명령은 단일 열인을 반환 pid하지만 빈 제목 헤더 (등호 바로 앞의 항목)를 지정했기 때문에 요청 된 유일한 열이므로 ps 명령은 헤더를 전혀 사용하지 않습니다. 파싱이 더 쉬워지기 때문에 우리가 원하는 것입니다.

이것은 Linux, BSD, Solaris 등에서 작동합니다.

또 다른 전략은 위 ps명령 의 종료 값을 테스트하는 것 입니다. 프로세스가 실행 중이면 0이고 그렇지 않으면 0이 아닙니다. POSIX 사양에 따르면 ps오류가 발생하면> 0을 종료해야하지만 '오류'를 구성하는 것이 무엇인지 명확하지 않습니다. 따라서 모든 유닉스 / 리눅스 플랫폼에서 잘 작동 할 것이라고 확신하지만 개인적으로이 전략을 사용하지는 않습니다.


대부분의 Linux 배포에서는 pidof(8)을 사용할 수 있습니다 .

지정된 프로세스의 실행중인 모든 인스턴스의 프로세스 ID를 인쇄하거나 실행중인 인스턴스가 없으면 아무것도 인쇄하지 않습니다.

예를 들어, 내 시스템에서 (4 개의 인스턴스 bash와 1 개의 remmina실행 인스턴스가 있음 ) :

$ pidof bash remmina
6148 6147 6144 5603 21598

다른 Unices에서 pgrep또는 psand 의 조합은 grep다른 사람들이 정당하게 지적했듯이 동일한 것을 달성합니다.


이것은 대부분의 Unix, BSD 및 Linux에서 작동합니다.

PATH=/usr/ucb:${PATH} ps aux | grep httpd | grep -v grep

테스트 대상 :

  • SunOS 5.10 [따라서 PATH=...]
  • Linux 2.6.32 (CentOS)
  • Linux 3.0.0 (Ubuntu)
  • 다윈 11.2.0
  • FreeBSD 9.0- 안정
  • Red Hat Enterprise Linux ES 릴리스 4
  • Red Hat Enterprise Linux Server 릴리스 5

가장 간단한 방법은 ps 및 grep을 사용하는 것입니다.

command="httpd"
running=`ps ax | grep -v grep | grep $command | wc -l`
if [ running -gt 0 ]; then
    echo "Command is running"
else
    echo "Command is not running"
fi

명령에 일부 명령 인수가있는 경우 'grep $ command'뒤에 'grep cmd_arg1'을 추가하여 관심이없는 다른 가능한 프로세스를 필터링 할 수도 있습니다.

예 : 제공된 인수가있는 Java 프로세스가있는 경우 표시 :

-Djava.util.logging.config.file = logging.properties

실행 중

ps ax | grep -v grep | grep java | grep java.util.logging.config.file=logging.properties | wc -l

Just a minor addition: if you add the -c flag to ps, you don't need to remove the line containing the grep process with grep -v afterwards. I.e.

ps acux | grep cron

is all the typing you'll need on a bsd-ish system (this includes MacOSX) You can leave the -u away if you need less information.

On a system where the genetics of the native ps command point back to SysV, you'd use

ps -e |grep cron

or

ps -el |grep cron 

for a listing containing more than just pid and process name. Of course you could select the specific fields to print out using the -o <field,field,...> option.


Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:

kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"

kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:

$ mysql &
$ echo $! > pid_stored

then in the script:

kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"

I use pgrep -l httpd but not sure it is present on any platform...
Who can confirm on OSX?


You should know the PID of your process.

When you launch it, its PID will be recorded in the $! variable. Save this PID into a file.

Then you will need to check if this PID corresponds to a running process. Here's a complete skeleton script:

FILE="/tmp/myapp.pid"

if [ -f $FILE ];
then
   PID=$(cat $FILE)
else
   PID=1
fi

ps -o pid= -p $PID
if [ $? -eq 0 ]; then
  echo "Process already running."  
else
  echo "Starting process."
  run_my_app &
  echo $! > $FILE
fi

Based on the answer of peterh. The trick for knowing if a given PID is running is in the ps -o pid= -p $PID instruction.


This approach can be used in case commands 'ps', 'pidof' and rest are not available. I personally use procfs very frequently in my tools/scripts/programs.

   egrep -m1  "mysqld$|httpd$" /proc/[0-9]*/status | cut -d'/' -f3

Little explanation what is going on:

  1. -m1 - stop process on first match
  2. "mysqld$|httpd$" - grep will match lines which ended on mysqld OR httpd
  3. /proc/[0-9]* - bash will match line which started with any number
  4. cut - just split the output by delimiter '/' and extract field 3

This prints the number of processes whose basename is "chromium-browser":

ps -e -o args= | awk 'BEGIN{c=0}{
 if(!match($1,/^\[.*\]$/)){sub(".*/","",$1)} # Do not strip process names enclosed by square brackets.
 if($1==cmd){c++}
}END{print c}' cmd="chromium-browser"

If this prints "0", the process is not running. The command assumes process path does not contain breaking space. I have not tested this with suspended processes or zombie processes.

Tested using gwak as the awk alternative in Linux.

Here is a more versatile solution with some example usage:

#!/bin/sh
isProcessRunning() {
if [ "${1-}" = "-q" ]; then
 local quiet=1;
 shift
else
 local quiet=0;
fi
ps -e -o pid,args= | awk 'BEGIN{status=1}{
 name=$2
 if(name !~ /^\[.*\]$/){sub(".*/","",name)} # strip dirname, if process name is not enclosed by square brackets.
 if(name==cmd){status=0; if(q){exit}else{print $0}}
}END{exit status}' cmd="$1" q=$quiet
}

process='chromium-browser'

printf "Process \"${process}\" is "
if isProcessRunning -q "$process" 
 then printf "running.\n"
 else printf "not running.\n"; fi

printf "Listing of matching processes (PID and process name with command line arguments):\n"
isProcessRunning "$process"

Here is my version. Features:

  • checks for exact program name (first argument of the function). search for "mysql" will not match running "mysqld"
  • searches program arguments (second argument of the function)

script:

#!/bin/bash

# $1 - cmd
# $2 - args
# return: 0 - no error, running; 1 - error, not running
function isRunning() {
    for i in $(pidof $1); do
        cat /proc/$i/cmdline | tr '\000' ' ' | grep -F -e "$2" 1>&2> /dev/null
        if [ $? -eq 0 ]; then
            return 0
        fi
    done
    return 1
}

isRunning java "-Djava.util.logging.config.file=logging.properties"
if [ $? -ne 0 ]; then
    echo "not running, starting..."
fi

None of the answers worked for me, so heres mine:

process="$(pidof YOURPROCESSHERE|tr -d '\n')"
if [[ -z "${process// }" ]]; then
  echo "Process is not running."
else
  echo "Process is running."
fi

Explanation:

|tr -d '\n'

This removes the carriage return created by the terminal. The rest can be explained by this post.


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)

참고URL : https://stackoverflow.com/questions/9117507/linux-unix-command-to-determine-if-process-is-running

반응형