... The system() call returns while these programs execute in the background.

If the programs - as it seems - actually do run in the background, the problem is that the initial process (which you start via system or open) will fork another process and terminate itself, thereby also closing the pipe.  And as the command (parent process) has terminated, the respective Perl function will return more or less immediately.

In case you're on Unix you should be able to use a named pipe (aka fifo):

#!/usr/bin/perl my $command = "./program_to_run.pl"; my $fifo = "tmp.fifo"; system "mkfifo $fifo; $command >$fifo 2>&1 &"; open my $fh, "<", $fifo or die "Couldn't open fifo '$fifo': $!"; while (<$fh>) { print ": $_"; } close $fh; unlink $fifo;

The background script (program_to_run.pl):

#!/usr/bin/perl my $pid = fork(); if ($pid) { exit; } else { $| = 1; for (1..3) { print "foo"; print STDERR "bar\n"; sleep 1; } print "done.\n"; }

Output (from the first script):

: foobar : foobar : foobar : done.

In reply to Re: Unable to capture STDOUT from system command by almut
in thread Unable to capture STDOUT from system command by Greg_R

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.