in reply to exec sometimes changes pid

I think the explanation moritz gives above is right. Should you need a workaround, you can probably send the entire process group a signal (other than KILL, obviously) after putting a handler in to ignore that signal in the parent.

Warning: drylabbed code ahead. Not tested, though I do have a little experience using signals in Perl.
my $pgrp_id=getpgrp(0) # gets the process group id of # the current process { # scoping is important! Otherwise # that signal will always be ignored # by the parent, which is probably bad. # I picked SIGINT, you might prefer something # else. local $SIG{'INT'}='IGNORE'; kill 2, -$pgrp_id; # - means it's a group id. }
But, of course, this assumes you don't have other stuff running in the process group that you need to leave alive, besides the parent.

This does raise the question of why you need to kill it via a signal, of course.

Replies are listed 'Best First'.
Re^2: exec sometimes changes pid
by doom (Deacon) on Aug 03, 2009 at 01:12 UTC

    I've done this sort of thing for a number of different reasons, usually involving driving emacs code from perl. For example, I've written test code in perl that spins off an emacs window, and captures an image of it. The parent perl process then kills the emacs, and examines the image to see if it looks okay (has the right number of colors, for example).

    The work around that I had in mind was to run the child with a munged program name, then do a "ps ax" listing, and grep for the munged name. That would get me the actual pid of the child to kill. Your idea looks a bit simpler (if a little less surgical).

Re^2: exec sometimes changes pid
by cdarke (Prior) on Aug 03, 2009 at 03:44 UTC
    Assuming that the pid returned from fork is the shell's, then why not do the opposite? Set SIGHUP to 'DEFAULT' then kill the shell. Assuming that the shell command is not doing something like 'nohup', then that should kill the shell's child, without needing `ps`.

      If killing the pid for the intermediate shell Just Worked, then I wouldn't be asking this question. I must say I don't understand why it doesn't work...

      It didn't occur to me to explicitly set SIGHUP to 'DEFAULT', maybe that would've made a difference.