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:
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.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 }; };
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 | |
|
Re^4: how to kill background process when script exit?
by Allasso (Monk) on Feb 21, 2011 at 14:04 UTC | |
by Anonymous Monk on Feb 21, 2011 at 14:15 UTC | |
by Allasso (Monk) on Feb 21, 2011 at 17:49 UTC |