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

Hello, I am running a command in background in my perl script. I want that my program should exit only when the background command has completed. How should I give a wait command for that? Thanks.
  • Comment on wait syntax for background process to complete

Replies are listed 'Best First'.
Re: wait syntax for background process to complete
by jettero (Monsignor) on Jun 24, 2008 at 01:53 UTC
    I usually use waitpid. There is a demo do {} while loop in the doc page.

    -Paul

      Hi, I am running my process in background using system command in perl. I only have one child process and I have tried using wait and waitpid but still my script exits but I can see the process running in background. Also, I found that when running system command with only one parameter, Perl will spawn a command shell to do the work. Can this be the reason that my script exits? Here's my code:
      system(" some command >&file &"); wait;
      I would appreciate any help. Thanks.
        You are causing your external process to background and detach from your process group.

        You can't really wait for it to end like that in a reliable way...

        Instead, do this:

        if( my $pid = fork ) { print "I am the parent pid ($$), and I'm going to wait for $pid to + exit.\n"; my $kid; do { $kid = waitpid $pid, 0; } while $kid > 0; exit 0; } else { exec(qw(ls -al /tmp)); die "hrm, exec() failed: $!"; }

        Using a '&' in the system() call causes perl to fork a shell and asks the shell to fork a kid. Then the shell returns and perl completely looses track of the kids.

        UPDATE: Also, I just noticed that you probably need some kind of redirection:

        # exec(qw(ls -al /tmp)); die ... blah open my $out, ">", "filename" or die $!; open my $in, "-|", qw(ls -al /tmp) or die $!; print $out $_ while <$in>; close $out; close $in;

        -Paul

Re: wait syntax for background process to complete
by pc88mxer (Vicar) on Jun 24, 2008 at 00:37 UTC
    while (wait > -1) {};
    If you know you only can have one child process, you could just use:
    wait;