0

I would like to detect that a certain process in linux have died. Say that pid of that process is 1234. I can check that its pid is in use by testing the existence of /proc/1234/. Still, it is possible that the process have died and pid was reused. I can check if the inode of some file in proc (say proc/1234/cmdline) is the same and hope that a new process will get a different value.

Is there any better way to reliably detect death of a process?

Maxim
  • 105
  • 1
  • 1
  • 4

3 Answers3

1

You could parse /proc/%d/stat which if the PID currently exists will give you information about the process. This will work on any Linux system but not other unix systems.

To parse the file find the last ) character. It will be followed by a space and the current state of the process. Maybe you don't care about the state, maybe you do care if the state is Z which means the process is dead but the parent process has not yet collected the status.

19 fields further into the data you will find the start time of the process. If the PID has been recycled the start time has changed. Here is an example command line that will print just the start time:

cat /proc/2272/stat | sed -e 's/.*) //' | cut -f20 -d' '
kasperd
  • 30,455
  • 17
  • 76
  • 124
0

if you know what the process is called by name you could just

ps aux | grep <name> | grep -v grep

Not sure if thats what you're looking for, but that is how i've interpreted your question.

0

Actually you can combine the two. If you know the name of the process and the pid that it used originally, pgrep will return a list of pids for a process, and you can check.

#!/bin/bash

PIDS=`pgrep $1`

for PID in ${PIDS[@]}
do
    if [ "$2" == "${PID}" ]
    then
        echo "Still running!"
        exit 1
    fi
done

echo "Not found"
exit 0

Pass the process name as the first argument and the PID as the second argument

r b
  • 61
  • 5