[NCLUG] Bashing lost children

Tkil tkil at scrye.com
Wed Apr 10 12:01:11 MDT 2002


>>>>> "Michael" == Michael Dwyer <mdwyer at sixthdimension.com> writes:

Michael> Well... except in a case like this:

Michael>   sleep 30 | logger &
Michael>   echo $! >/var/run/sleep.pid

Michael> it stores the PID of 'logger' instead of sleep...  Argh.

the first solution that comes to mind is something like this:

| $ perl -we 'open(PID, ">/var/run/$ARGV[0].pid") && 
|             print(PID "$$\n") &&
|             close(PID) &&
|             exec(@ARGV);' sleep 20 | logger &

you can do all that in a C wrapper, instead, of course.  there might
be a way to do something similar with file descriptor numbers, instead
of opening a new file as i did above.  my sh-fu isn't quite up to it,
however.

hm... the exec trick might work for subshells, too:

| $ ( echo $$ > /var/run/sleep.pid && exec sleep 20 ) | logger &

maybe?  no, not really, since $$ always evaluates to the top-level
invoking shell.  how annoying.  well, if you can figure out the
process id of the subshell, that version seems to do about the right
thing.  

one way to do it would be to write a program that gets its PPID; if
you run it in the subshell, then you get back the PID of the
subshell.  e.g.,

| /* self-pid.c: get the PID of the parent process */
| 
| #include <sys/types.h>
| #include <stdio.h>
| #include <unistd.h>
| 
| int main(int argc, char * argv [])
| {
|     printf("%d\n", getppid());
|     return 0;
| }

then you can do something like this:

| $ ( ./self-pid > perl.pid && exec perl -lwe 'print "perl pid: $$"' ) && \
|   sleep 1
| perl pid: 16769
| $ cat perl.pid
| 16769

if you don't want to write a program, you can do that with perl (of
course), since it has the "getppid()" function available.  at that
point, however, you might be better off with the first version i gave:

| $ perl -we 'open(PID, ">perl.pid") && print(PID "$$\n") && close(PID) &&
|             exec(@ARGV);' perl -lwe 'print "perl pid: $$"' | cat &
| [1] 16911
| perl pid: 16910
| $ cat perl.pid
| 16910

t.



More information about the NCLUG mailing list