d9vx has asked for the wisdom of the Perl Monks concerning the following question:

launching an external program with SYSTEM() command, causes the script to hang until the process has finished, i.e. the program is closed. how do i make pearl continue on with the script, while the program it has launched with the system command continues running? Thanks to anyone who can help
  • Comment on launching external program with SYSTEM causes script to hang until program closed

Replies are listed 'Best First'.
Re: launching external program with SYSTEM causes script to hang until program closed
by graff (Chancellor) on Sep 27, 2007 at 00:51 UTC
    Instead of doing system(), you could do "fork()" and have the child do "exec()". The parent process will continue to do whatever it's doing, because "fork()" returns immediately.

    See perlipc for details, and the perlfunc section on fork for a brief description. A simple example:

    my $child_pid = fork(); if ( ! defined( $child_pid )) { warn "fork failed\n"; } elsif ( $child_pid == 0 ) { # true for the child process exec( $cmd, @args ); } # the parent gets here when the fork succeeds...
      That's great for UNIX-y systems.

      fork() uses threads.pm on Windows, so (in some situations) you may wish to use Win32::Process::Create() instead.

      -David

        Even easier on Win32 is system( 1, $cmd ). It is unfortunate that this easy way to "spawn" (which the Perl C code knows how to do portably) was never exposed for Perl scripts to do portably.

        - tye        

      I have had good success with fork on Windows (perl release 5.6+). However, you can also use a piped open command which will not wait for the output. If the trailing character is a pipe symbol, "open" launches a new process with a read-only filehandle connected to it. For example:
      open(NET, "netstat -i -n |") or die "can't fork: $!"; # You could go off and do other things here for a bit, # and then come back to check on your results. while (<NET>) { # your code here... } close(NET) or die "can't close netstat: $!/$?";
      Please note that when you explictly close the piped filehandle, it will cause the parent process to wait for the child to finish (and I recommend closing it).
Re: launching external program with SYSTEM causes script to hang until program closed
by naikonta (Curate) on Sep 27, 2007 at 10:28 UTC
    I think what you're looking for is in the Perl FAQ:
    How do I start a process in the background?

    Several modules can start other processes that do not lock your Perl program. You can use IPC::Open3, Parallel::Jobs, IPC::Run, and some of the POE modules. See CPAN for more details.

    You could also use

    system("cmd &")
    or you could use fork as documented in "fork" in perlfunc, with further examples in perlipc.

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!