Reputation: 1507
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.
Upvotes: 1
Views: 1337
Reputation: 118685
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 &";
}
Upvotes: 7
Reputation: 86774
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.
Upvotes: 1