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

How can i handle the otuput of multiple process; So, i can show the output of the one process in real time and other can be saved in temporary files and show later on when theses process completed.
  • Comment on a way to handle the multiple processes output

Replies are listed 'Best First'.
Re: a way to handle the multiple processes output
by moritz (Cardinal) on May 20, 2008 at 08:26 UTC
    You probably need open, and perhaps you need to disable buffering, $|=1. See perlvar for a description of $|.
Re: a way to handle the multiple processes output
by casiano (Pilgrim) on May 20, 2008 at 10:16 UTC
    I am not sure about your question.
    If the problem is buffering be sure you have set them to flush:
    use IO::Handle; $F = new IO::Handle; $F->autoflush(1);
    If what you want is to filter the output then create a filter by forking again like in this example
    $ cat -n openself 1 #!/usr/local/bin/perl -w 2 use strict; 3 use utf8; 4 binmode(STDOUT, ':utf8'); 5 binmode(STDIN, ':utf8'); 6 7 print "Father: $$\n"; 8 9 my $pid = open(STDOUT, "|-"); 10 die "cannot fork: $!" unless defined $pid; 11 12 # Child filters father's output 13 filterstdout() unless $pid; 14 15 # Father 16 print " <- This is the PID of the child\n"; 17 while (<>) { 18 print 19 } 20 21 sub filterstdout { 22 while (<STDIN>) { 23 tr/áéíóúñ€/aeioun$/; 24 print "$$: $_"; 25 } 26 exit; 27 }

    Hope it helps

    Casiano

Re: a way to handle the multiple processes output
by pc88mxer (Vicar) on May 20, 2008 at 15:24 UTC
    I'm looking for a way to dipslay output from one of the forked process in real time and other processes output in different temporay files.
    One way is to just use another process to display the contents of the desired output file(s):
    my $pid1 = background("command > some-file"); my $pid2 = background("other-command > some-other-file"); my $tail_pid = background("tail -f some-file"); ...do stuff... if (waitpid $pid1) { kill 9, $tail_pid; } ... sub background { defined(my $pid = fork) or die "unable to fork: $!"; if ($pid == 0) { exec(@_); exit 1 } $pid; }
    If you want to monitor several output files (since you say you have several background processes), multitail might be what you're looking for.
Re: a way to handle the multiple processes output
by samtregar (Abbot) on May 20, 2008 at 17:14 UTC
    Perl makes it easy to fork a process that writes data down a pipe to the parent:

      open(my $pipe, "cat foo |") or die $!;

    Then you can read from that pipe to get output as it comes in:

      while (<$pipe>) { print $_ }

    If you need to read from multiple kids at once, use IO::Select:

    -sam