Obtaining PID of command earlier in Pipeline

I’m writing a bash script to use inotifywait to monitor a directory and kick off actions when changes are detected. Something like:

inotifywait -m ... | while read f; do something; done

Since inotifywait doesn’t terminate by itself, this script will not halt.

So my plan was to get the PID of the inotifywait process, save it to a file and have a different process kill it later, say like:

inotifywait -m ... | { echo ??PID?? > pid-file; while ... }

But I don’t know how to get the PID. Is there a simple way to achieve this? Another way is just to save the PID of the shell-script $$ to the file and kill the entire shell-script but I wanted to do some cleanup after the while loop.

I have tried using coproc and I think it will work but it seems like more complication than necessary.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In a pipeline, all processes are started concurrently, there’s not one that is earlier than the others.

You could do:

(echo "$BASHPID" > pid-file; exec inotifywait -m ...) | while IFS= read -r...

Or portably:

sh -c 'echo "$$" > pid-file; exec inotifywait -m ...' | while IFS= read -r...

Also note that when the subshell that runs the while loop terminates, inotifywait would be killed automatically the next time it writes something to stdout.

Method 2

If you need the process ID in the loop, print it first.

sh -c 'echo "$$"; exec inotifywait -m ...' | {
  read inotifywait_pid
  while IFS= read -r f; do
    …
    if …; then kill "$inotifywait_pid"; break;
  done
}

Method 3

This SO answer seems applicable:

inotifywait -m file > >(while read f; do echo f; done) &


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x