1

I am using a perl script to fire off a jar that needs to stay running. However, I want my perl process to end. I thought this thread would solve my problems: How can I fire and forget a process in Perl?

However, I have tried both forking and using the system(cmd &) techniques and in both my perl script stays running.

Here was my code to fork:

if (index($all_jars, 'myjar.jar') == -1) {
  unless(fork) {
  }
  else {
    exec("java -jar myjar.jar");
  }
}

Here was my code for the system(cmd &): I wasn't sure if this meant to type cmd & my command or just my command & but both systems didn't quit the perl script until after the jar process died.

system("cmd & java -jar myjar.jar");

OR

system("java -jar myjar.jar &");

Not sure what I am doing wrong... Thanks for any help or ideas you could give me.

Community
  • 1
  • 1
dev
  • 1,477
  • 5
  • 18
  • 43
  • Please describe what _"neither worked"_ means. In general, when saying something didn't work, you must explain _exactly_ what happened (error message, wrong output, computer reduced to a puddle of molten metal and silicon...) – Jim Garrison Aug 15 '13 at 22:15
  • @JimGarrison Sorry about that, I edited the topic. I mean that the perl script didn't die until after the jar process did. – dev Aug 15 '13 at 22:18
  • Just out of curiosity, what OS are you using? – squiguy Aug 15 '13 at 22:24
  • I am currently on OEL6 but it will need to work on any Windows/Unix box – dev Aug 15 '13 at 22:28

2 Answers2

7

I have a lot of experience in this domain, and I've learned that the best way to create a background process that can outlive the parent process depends on your operating system.

In Unix, you can ask system to run a job in the background or use fork and exec:

system("java -jar myjar.jar &");

if (fork() == 0) {
    exec("java -jar myjar.jar");
    die "exec shouldn't have returned";
}

Note that your logic (unless(fork){...}else{exec(...)}) is backwards and you are calling exec in the parent process.

In Windows, the best way to create a background process that runs in a separate process group is with the system 1, ... hack:

system 1, "java -jar myjar.jar";

Check $^O to see what operating system you are running under:

if ($^O eq 'MSWin32') {
    system 1, "java -jar myjar.jar";
} else {
    system "java -jar myjar.jar &";
}
mob
  • 117,087
  • 18
  • 149
  • 283
1

Perl has several ways to launch background processes.

(Note: I typically avoid posting link-only answers, but since there are several modules and that page is likely never going away, I feel it's safer than usual).

For completeness, here's a short quote from the page:

Several CPAN modules may be able to help, including IPC::Open2 or IPC::Open3, IPC::Run, Parallel::Jobs, Parallel::ForkManager, POE, Proc::Background, and Win32::Process.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190