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


In reply to Re^3: how to kill background process when script exit? by eyepopslikeamosquito
in thread how to kill background process when script exit? by Allasso

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.