LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   perl fork & pipe help (https://www.linuxquestions.org/questions/programming-9/perl-fork-and-pipe-help-873832/)

kdelover 04-08-2011 03:10 PM

perl fork & pipe help
 
Hi,
I am learning about forks and pipes in perl,and i seem to be having a small problem in communicating between a child and a parent process using pipes.

Code:

#!/bin/perl
use strict;
use warnings;

my $pid;
my $result;
pipe (READ,WRITE);
$pid=fork();
if ($pid == 0 ) {
#child process

$result=`tail -10 /var/log/messages`;
print WRITE ($result);
exit(1);
}
else {
#parent process
my $stat=<READ>;
print "Printed by parent ($$) - $stat\n";
waitpid($pid,0);
}

Output:

Code:

Printed by parent (3623) - Apr  9 00:39:30 hp-laptop kernel: [  23.450059] EXT4-fs (sda5): re-mounted. Opts: errors=remount-ro,user_xattr,commit=600
For some reason the parent process is printing only the first line returned by the child process through a pipe,can any one tell me where am i going wrong over here? Thanks.

theNbomr 04-08-2011 05:29 PM

When you assign to a scalar, a read returns one record, which is by default, a line. Perhaps you should make "$stat" into "@stat".
--- rod.

kdelover 04-09-2011 01:19 AM

Hi,

I had tried making $stat to @stat,the programme just hangs,doesnt give any output when changing the scalar to an array.

Sergei Steshenko 04-09-2011 04:12 AM

Quote:

Originally Posted by kdelover (Post 4318798)
Hi,

I had tried making $stat to @stat,the programme just hangs,doesnt give any output when changing the scalar to an array.

You have to start from something like this:

Code:

while(defined(my $line = <READ>))
  {
  warn "parent: \$line=$line";
  }


kdelover 04-09-2011 06:20 AM

Hi,

The while loop actually works,but the programme doesn't quit now after printing those 10 lines.I think the pipe is expecting an EOF character,which it never gets.

kdelover 04-09-2011 08:42 AM

I solved the problem by using a named pipe,i don't know why cant i use a pipe(read,write) function.

Quote:

#parent process
open (FIFO,'<','./mypipe');
my @arr=<FIFO>;
close (FIFO);
print "@arr\n";
waitpid ($pid,0);

}


All times are GMT -5. The time now is 08:27 PM.