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

Hi, I have a perl script that calls a shell script with a system command. I need to wait on this to complete and the control should be back to the perl script.

I have been searching and i am not sure which is the best module to use for this. Can you please suggest

  • Thanks
  • Replies are listed 'Best First'.
    Re: which module - linux/process
    by oha (Friar) on Sep 25, 2007 at 10:01 UTC
      you can use backticks, or a pipe open
      my $output = `ls -la`; # or open PIPE, "ls -la |"; while(<PIPE>) { .... }

      Oha

        or system if the command output is not going to be used later:
        system($command, @args);

        It is documented in perlfunc

          Yes, system(command,args) is what i use

          What i need is to wait for the above command to complete and control passed back to the perl script, so i can do something more in there

        I was trying something on the lines of waitpid, fork and exec. But waitpid dint work for me

          As noted, you will need to use the system(...) or `...` to execute any system-level commands. These commands will wait for the external processes to complete.

          But you mentioned you would like to try using fork and wait/waitpid, so try this example:

          my $pid; if (defined($pid = fork)) { if ($pid) { &parent(); } else { &child(); } } else { die "Fork didn't work...\n"; } sub child { print "Running child process instructions...\n"; sleep 5; # If you have system-level commands to process, # you will still need to use system(...) or `...` exit; } sub parent { waitpid($pid,0); # Will wait for a specific child process # wait; # Will wait for ANY child process to finish print "Finished waiting for child process $pid\n"; }
    Re: which module - linux/process
    by cdarke (Prior) on Sep 25, 2007 at 12:15 UTC
      You had better show us your system command, since what you are asking for is the normal action. Are you running the script in background (& suffix) for example?