in reply to Re^6: how to kill background process when script exit?
in thread how to kill background process when script exit?

Then the code I gave you should already work and kill the child at the end of the program. Maybe closing the filehandle to the kid and also adding a call to kill outside the END block helps to kill the kid earlier.

  • Comment on Re^7: how to kill background process when script exit?

Replies are listed 'Best First'.
Re^8: how to kill background process when script exit?
by Allasso (Monk) on Feb 20, 2011 at 14:43 UTC
    Okay, I tried that - closing the filehandle and putting the kill at the end of the script - still no go. Perl program stops executing until I exit the java app. It just does not seem that open() is launching the process in the background.

      The following code behaves just like it should (and like I said) for me:

      corion@aliens:~/tmp$ cat test.pl #!perl -w use strict; my $pid = open my $fh, 'sleep 1000 |' or die "Couldn't spawn: $! / $?"; print "Spawned child as $pid"; print "Doing own work $_\n" for 1..10; print "Killing child $pid"; kill 9 => $pid; print "done\n";
      corion@aliens:~/tmp$ perl -w test.pl Spawned child as 26868Doing own work 1 Doing own work 2 Doing own work 3 Doing own work 4 Doing own work 5 Doing own work 6 Doing own work 7 Doing own work 8 Doing own work 9 Doing own work 10 Killing child 26868done

      I'm not sure what you're doing differently.

        okay, I believe my problem was that I was redirecting my output, which causes open() to open the process in a shell. So the pid it was returning was the pid of the shell process.

        remove the redirection, and it works.

        sorry for all the hassle, I've sure learned a lot about processes though that I didn't know before on this little venture :-)

        Actually I found another problem that was causing me confusion. I was closing the filehandle after opening it. (at your suggestion :-)) This was what was causing my script to not execute until after the app was closed, making me believe that it was not running in the background. I don't know why closing the filehandle would affect it this way though.

        Try this: (after 10 sec the script will run)

        #!/usr/bin/perl use strict; my $pid = open my $fh, 'sleep 10 |' or die "Couldn't spawn: $! / $?"; close $fh; print "Spawned child as $pid"; print "Doing own work $_\n" for 1..10; print "Killing child $pid\n"; kill 9 => $pid; print "done\n";

        ps: is it appropriate to call a process that runs in the background a "child"? It seems like it is disassociated from the "parent".

        yes, you are right, it works.

        I'll have to see what I was doing before.