Suppose the specific process is a long-running background process A. I wanted to execute a bash script command/script hooks for process A right after process A is started, for example getting its pid and doing something with it. The problem with my use case is that I don't have control over when/how process A is started, and I can't alter process A to generate pidfile; hence the hook idea.
Currently, process A can be run multiple times so there can be multiple pids associated to process A. The script hook should be run on every instance of process A, not just the first run.
I have tried using cron and pgrep to get all the instances of process A. However, there's 60-second latency with this approach since it is the shortest polling interval time with cron.
My questions:
- What are my options for near real-time notification (< 5-sec latency is acceptable, the lower the better) whenever new process A is started AND execute the bash hook for process A reliably?
- Is running an infinite while loop + pgrep in the bg with lower latency (eg: 1-5 secs sleep) a safe option?
- Since inotify exists for file events, is there any similar mechanism for listening (+ running cmd hook) to a specific process event (eg: started/killed/proc status change)?
Thanks!