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

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.

Replies are listed 'Best First'.
Re^10: how to kill background process when script exit?
by Allasso (Monk) on Feb 20, 2011 at 19:02 UTC
    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 :-)
Re^10: how to kill background process when script exit?
by Allasso (Monk) on Feb 20, 2011 at 23:36 UTC

    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".

Re^10: how to kill background process when script exit?
by Allasso (Monk) on Feb 20, 2011 at 18:58 UTC
    yes, you are right, it works.

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