How to run a script and not wait for it in Perl?

I have a system call in Perl that looks like this:

system('/path/to/utility >> /redirect/to/log file'); 

But it is waiting for the utility complete. I just want to call this and let the Perl script finish, whether the utility call has finished or not.

How can i do this?

I tried changing the line to

 system('/path/to/utility >> /redirect/to/log file &'); 

but this syntax is still waiting for the call to complete on Windows. I need to get it to work with both Linux and Windows.

+6
source share
4 answers
 if ($^O eq 'MSWin32') { system('start "" \\path\\to\\utility >> \\redirect\\to\\log_file'); } else { system('/path/to/utility >> /redirect/to/log_file &'); } 

or

 if ($^O eq 'MSWin32') { system(1, '\\path\\to\\utility >> \\redirect\\to\\log_file'); } else { system('/path/to/utility >> /redirect/to/log_file &'); } 
+6
source

You can try to look at the fork keyword and run your system command from a forked process. See the perlipc page for examples.

+2
source

The easiest way for POSIX-like systems is the one you have already tried:

 system('/path/to/utility >> /redirect/to/log_file &'); 

The easiest way to get a tool to run in the background on Windows is to use start.exe as a startup assistant:

 system('start /path/to/utility >> /redirect/to/log_file'); 

However, I do not know if this works to redirect the output to the log file in this way, and I do not have a Windows system at this point to test it.

Yes, this means that you will need a code branch depending on the current system, but other solutions may also be needed. If your Perl has fork() emulation, you can actually use fork() for both systems (this is a bit more complicated since you cannot redirect stdout to a log file, which is easy, you first need to open it on Perl and make it stdout forked child before calling a new process). If your Windows Perl does not have fork() emulation, you also need a code branch, since in this case you can only use fork() on UNIX, and you will need to use Win32::Process::Create with the DETACHED_PROCESS option on Windows.

But maybe you can tell us first if using start already works for you. If this is not the case, start.exe not handle slashes. In this case, you may have to use something like

 C:\\path\\to\\utility 

instead (double backslash is important! The only backslash has special meaning in string literals, it is an escape character).

To find out if you work on Windows or not, look at the variable $OSNAME or $^OS , it should say something like "MSWin32" on Windows.

+2
source

This general task was abstracted in the CPAN module Proc:: Background

+2
source

Source: https://habr.com/ru/post/897167/


All Articles