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

You could use fork and exec instead. For example (no Unix box right now, so untested) something like:

use strict; my $JAVA_CLASSPATH = '...whatever'; my $java_command = "java -classpath $JAVA_CLASSPATH TextEntry"; my $kid; defined($kid = fork()) or die "error: fork: $!"; if ($kid == 0) { ## child # Could redirect child stdout/stderr here if desired. # open(STDOUT, '>', 'javastdout.tmp') or die "redirect stdout: $ +!"; # open(STDERR, '>', 'javastderr.tmp') or die "redirect stderr: $ +!"; exec($java_command); die "error: exec: $!"; } warn "parent continues ... child pid is $kid\n"; # Could wait for child to exit using waitpid if required. # waitpid($kid, 0); # script continues... END { # Update: should first check that $kid is still alive before killi +ng it. # Something like: kill 0, $kid should do it (see "perldoc -f kill" +) if ($kid) { kill 9 => $kid; # bang }; };
Also, as a matter of technique, you should try "kill 15" (SIGTERM) before resorting to "kill 9" so as to give the Java process a chance to catch the SIGTERM signal, clean up and die more gracefully.

Update: For more elaborate sample code, using fork/exec, "kill 15" (softer kill before resorting to "kill 9"), "kill 0" (to check if process is still alive), and waitpid (to reap the exited child and test its exit code), see Timing and timing out Unix commands (especially the "kill_it" subroutine).

Replies are listed 'Best First'.
Re^4: how to kill background process when script exit?
by Allasso (Monk) on Feb 20, 2011 at 01:01 UTC

    Abbot:

    Just saw that, I'll have to look into it tomorrow, thanks.

Re^4: how to kill background process when script exit?
by Allasso (Monk) on Feb 21, 2011 at 14:04 UTC
    eyepopslikeamosquito:

    thanks, I had a chance to go through it, and it works fine. I was unfamiliar with fork() and exec() so I had to do a bit of studying first. I think open[_23]() provide a few more options and are more straightforward though, but maybe there is a price for this. Can you tell me any advantages to using fork()/exec() over open()?

    All in all, the experience has been very good for me. The whole thing about processes and threads has always been kind of mysterious to me, and I never have had a reason to grind through and get it figured out.

    I like your kill_it routine, and will use it.
        thanks, that's a really good explanation and easy to follow. (and entertaining)