Friday, August 15, 2008

Check if Process is Running [Unix]

If you have a process id (pid), how can you tell if it is still running?

One obvious way to do this is to parse the output of the ps command. For example:

sharfah@starship:~> ps -ef | grep " 1234 " | grep -v grep
sharfah  1234     1  0 10:36:06 pts/65   1:20 java -server
However, a much neater way to do this is to use the kill command to send signal 0 to the process. So kill -0 will not terminate the process and the return status can be used to determine if the process is running. 0 if it is, non-zero otherwise.
sharfah@starship:~> kill -0 1234
sharfah@starship:~> echo $?
0

sharfah@starship:~> kill -0 1234x
bash: kill: 1234x: no such pid
sharfah@starship:~> echo $?
1
For those interested, the kill -l command lists signal numbers and names, but 0 is not listed.
sharfah@starship:~> kill -l
 1) SIGHUP     2) SIGINT      3) SIGQUIT   4) SIGILL
 5) SIGTRAP    6) SIGABRT     7) SIGEMT    8) SIGFPE
 9) SIGKILL   10) SIGBUS     11) SIGSEGV  12) SIGSYS
13) SIGPIPE   14) SIGALRM    15) SIGTERM  16) SIGUSR1
17) SIGUSR2   18) SIGCHLD    19) SIGPWR   20) SIGWINCH
21) SIGURG    22) SIGIO      23) SIGSTOP  24) SIGTSTP
25) SIGCONT   26) SIGTTIN    27) SIGTTOU  28) SIGVTALRM
29) SIGPROF   30) SIGXCPU    31) SIGXFSZ  32) SIGWAITING
33) SIGLWP    34) SIGFREEZE  35) SIGTHAW  36) SIGCANCEL
37) SIGLOST

2 comments:

  1. nick@sync:~$ ps --no-headers -p 6612
    6612 ? 00:00:01 gnome-terminal
    nick@sync:~$ ps --no-headers -p 66125
    nick@sync:~$

    This stuff outputs a line of process' info if this PID is running and silently quits with no output if there's no such process. Very handy to use in scripts.

    And you can also perform query by process' name using -C parameter.

    ReplyDelete
  2. Difficulty is if you are not the process owner, kill -0 will also return a non-zero. Notice init is running, however my user is not the owner.

    $ ps -p 1
    PID TTY TIME CMD
    1 ? 00:00:01 init
    $ kill -0 1; echo $?
    bash: kill: (1) - Operation not permitted
    1

    ReplyDelete