'Wait for a program (non-child) to finish and execute a command

I have a program running on a remote computer which shouldn't be stopped. I need to track when this program is stopped and immediately execute a command. PID is known. How can I do that?



Solution 1:[1]

Code like this can do the work (to be run on remote computer)

while true 
do
if [ "$(ps -efl|grep $PIDN|grep -v grep|wc -l)" -lt 1 ]
then <exec code>; break
fi
sleep 5
done

It expect the variable PIDN to contain the PID.

P.S. I know the code is ugly and power hungry

EDIT: it is possible to use -p in ps to avoid one grep

while true 
do
if [ "$(ps -p $PIDN|wc -l)" -lt 2 ]
then <exec code>; break
fi
sleep 5
done

Solution 2:[2]

Here's a fairly simple way to wait for a process to terminate using the ps -p PID strategy:

if ps -p "$PID" >/dev/null 2>&1; then
    echo "Process $PID is running ..."
    while ps -p "$PID" >/dev/null 2>&1; do
        sleep 5
    done
    echo "Process $PID is not running anymore."
fi

Checking for a process by PID

In general, to check for process ownership or permission to kill (send signals to) a proccess, you can use a combination of ps -p PID and kill -0:

if ps -p "$PID" >/dev/null 2>&1; then
    echo "Process $PID exists!"

    if kill -0 "$PID" >/dev/null 2>&1; then
        echo "You can send signals to process $PID, e.g. with 'kill $PID'"
    else
        echo "You do not have permission to send signals to process $PID"
    fi
else
    echo "Process $PID does not exist."
fi

Solution 3:[3]

You can use exitsnoop to achieve this.

The bcc toolkit implements many excellent monitoring capabilities based on eBPF. Among them, exitsnoop traces process termination, showing the command name and reason for termination, either an exit or a fatal signal.

   It catches processes of all users, processes in containers,  as  well  as  processes  that
   become zombie.

   This  works by tracing the kernel sched_process_exit() function using dynamic tracing, and
   will need updating to match any changes to this function.

   Since this uses BPF, only the root user can use this tool.

exitsnoop examples:

   Trace all process termination
          # exitsnoop

   Trace all process termination, and include timestamps:
          # exitsnoop -t

   Exclude successful exits, only include non-zero exit codes and fatal signals:
          # exitsnoop -x

   Trace PID 181 only:
          # exitsnoop -p 181

   Label each output line with 'EXIT':
          # exitsnoop --label EXIT

You can get more information about this tool from the link below?


Another option

use this project: https://github.com/stormc/waitforpid

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 traal
Solution 3 hxysayhi