in reply to how to kill background process when script exit?

can anyone tell me why this works:
#!/usr/bin/perl my $pid = open(my $fh, "java -classpath /Users/allasso/AWS/utility/too +ls_additional/SC_add/java TextEntry |") or die "Couldn't launch: $! / $?"; print "pid: $pid\n\ndoing stuff...\n\npress return to exit script...\n +\n"; <STDIN>; if ($pid) { kill 9 => $pid; # bang };
and this doesn't (hangs - can't exit script until java app is closed):
#!/usr/bin/perl my $pid = open(my $fh, "java -classpath /Users/allasso/AWS/utility/too +ls_additional/SC_add/java TextEntry |") or die "Couldn't launch: $! / $?"; END { if ($pid) { kill 9 => $pid; # bang }; }; print "pid: $pid\n\ndoing stuff...\n\npress return to exit script...\n +\n"; <STDIN>;

Replies are listed 'Best First'.
Re^2: how to kill background process when script exit?
by Corion (Patriarch) on Feb 21, 2011 at 15:24 UTC

    Most likely because the second snippet does an implicit

    close $fh;

    after the end of your program code and just before it starts to run the END block.

      I just observed that if I use FH instead of my $fh as the first arg to open(), it works

        This likely is because the globals are only cleaned up on global destruction, that is, they live until after the last END block has run. As you kill the child before that, this allows things to work as expected.