2

I am writing a Perl script that asks for some inputs and then eventually runs another script passing those inputs as arguments. That script I'm calling has print outputs that specify the % of how much processing is done as it goes through a foreach loop.

Currently I'm calling the other Perl script like this:

   print `perl /path/to/script.pl -x 0990;`

This works fine, but only prints any output when that called script finishes... so for example, when that script finishes, the output I get is:

   Status: 100% Completed
   Done!

When I want to be getting the output of every % number.

Any possible solutions for this?

Thanks!

1 Answer 1

1

I hope this works for you:

#!/usr/bin/perl
use POSIX ":sys_wait_h";
use IPC::Open3;
use IO::Select;

# forces a flush to stdout
$| = 1;

# open a process for writing, reading, and error
my $pid = open3(0,\*READ,0,"perl /path/to/script.pl -x 0990");

# reading process output in non-blocking mode
my $sel = new IO::Select();
$sel->add(\*READ);

# read process output until process returns
do {
 foreach my $h ($sel->can_read)
 {
  my $buf = '';
  sysread(READ,$buf,4096);
  if($buf){print "response->$buf"}
 }
 $kid = waitpid(-1, WNOHANG);
} while $kid > -1;

EDITED:

This script is not working on Windows platform

Sign up to request clarification or add additional context in comments.

7 Comments

Doesn't work for me. I was working on a solution, but you posted yours first (and mine wasn't working!), so I tried yours. The DO loop runs for the exact length of time the child script run, but the FOREACH loop never gets entered.
@jimtut Work's here. it might be because your process doesn't have any output so $sel->can_read block never executed.
Works on my end. However it does ONLY the print outputs INSIDE the foreach loop in the script that gets called. There are a couple print outputs in that script that did NOT get shown during the process... any idea why that would behave like that? Is that snippet just looking for outputs inside a foreach?
Does your process prints to stderr?
Nvm - I added the $| = 1 line and that seemed to include EVERYTHING that has a print output. Seems good to go now! Would love to know how you came to this solution...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.