Get all associated pids

im looking for a portable way to get the PID of the script that is running, and to get every other PIDs that are spawned from it.

and by ever other PIDs, i presume, that would be "child processes".

however, i want to shy away from using any command that is not available on every single unix system thats out there. so the preferred solution would be one that can be used everywhere.

so, here's what im attempting:

#!/bin/sh
myscriptpid=$$
ps -ef | awk -v myscriptpid="${myscriptpid}" '$2 ~ / $$ / || $3 ~ / $$ / '{print $0}''

can the above be beefed up to spit out the entire line of every single PID that is spawned from my script or related to my script???

First, single quotes don't work that way in awk or in the shell. Single quotes can't be included in a single-quoted string.

Second, note that / $$ / in awk is a regular expression that will NEVER match anything (if it isn't flagged as an error). It asks awk to look for a <space> character followed by the end of the string being matched followed by the end of the string being matched followed by another <space> character. And, since your field separator in this awk script is a string of one or more <space> and/or <tab> characters, there can never be a <space> character in the 2nd or 3rd field in your input. But, whether or not there could be a <space> character in a field to be matched, a <space> following the end of the string being matched can NEVER occur.

Third, the default action in awk is {print $0} , so it does not need to be specified.

To fix those problems, change:

#!/bin/sh
myscriptpid=$$
ps -ef | awk -v myscriptpid="${myscriptpid}" '$2 ~ / $$ / || $3 ~ / $$ / '{print $0}''

to:

#!/bin/sh
myscriptpid=$$
ps -ef | awk -v myscriptpid="${myscriptpid}" '$2 == myscriptpid || $3 == myscriptpid'

Fourth, note that your definition of "get every other PIDs that are spawned from it" is not at all clear. What you are doing will try to catch the PID of the process and its direct children; it will not catch any offspring of its direct children. If you are looking for all of the processes that have the current process as an ancestor, you would need to do a search like what you already have to find the current process' children and then look for their children recursively until the search for children of a generation of children does not find any more children. But, this does not necessarily find all of your process' offspring. If a child exits without waiting for its children, those children will be inherited by PID #1 (on most systems) and their relationship to your process will be lost.

And, fifth, ps -ef or ps -Af should get you information about all active processes and print their PIDs in field 2 and their parent's PIDs in field 3 on systems that have a ps that conforms to POSIX requirements. But, I can't promise that all systems provide a ps that conforms to POSIX requirements.

1 Like