Showing posts with label kill. Show all posts
Showing posts with label kill. Show all posts

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