PID of Command fed into While Loop

A nasty issue I never got around to solve.

If I feed the result from a command into the tail of a while loop, how do I reliably get the pid read also.
It is clear to me that the PID needs to be read exactly at time of executing the command as shown below in the code.

Although VarA does contain the result of Command1, there is no way I can find to have the PID associated with Command1 to be fed into the while loop and stored in VarB…
It must be possible as there is no other reliable way I can think of to get the PID of command1 in this case fed into a while loop.

You cannot calculate the PID from the parent pid which I see too often online… That is a recipe for disaster due to cycling and due to pid skipping of existing PIDs in use. You dont want to kill the wrong process, which is always possible doing that method.

So how do I get the loop below to read the pid associated with Command1 accurately.

    while read  VarA  VarB
    do
    <Some Stuff>
    done < <( Command1   &&   echo $! )

The above code is just an example of what I want to achieve, obviously ( Command1 && echo $! ) doesnt work and have to be changed but it explainst the intention well of p[assing both program output and PID.

I solved it for my purposes and has to be adapted I guess for different programs which you need the pid for.

what i did was to replace the feed to:

done < <(Command1 & (echo $!) )

What this does is to feed the result of (echo $!) which is the pid as the first thing the while loop sees and after that never again.
You then use an if loop inside while just to catch the PID once.

This is rocksolid and any PID loop issues and PID empty skips cannot interfere. It is Rocksolid. I tested it with several scenarios of PID loop skips and PID loop wraparound and it never failed.

For the record Command1 is a program that continuously feed data into the while loop. The only way I can demonstrate something similar to my program that now works great with this procedure that manages a data feed, is to use keypress which continuously enters keyboard presses to the while loop as demonstration.

I will post a working procedure to demonstrate later so that this post is of use for everyone.
At the moment Command1 is my own program so I will have to rework it for a system program.

1 Like

Linux sysadmin blog - Linux/Unix Howtos and Tutorials - Linux bash shell scripting wiki