How can I use pipe to facilitate interprocess communication in Perl?

Can someone explain how I can successfully establish a connection between processes? I find that perldoc on IPC is confusing.

What I still have is:

$| = 1; $SIG{CHLD} = {wait}; my $parentPid = $$; if ($pid = fork();) ) { if ($pid == 0) { pipe($parentPid, $$); open PARENT, "<$parentPid"; while (<PARENT>) { print $_; } close PARENT; exit(); } else { pipe($parentPid, $pid); open CHILD, ">$pid"; or error("\nError opening: childPid\nRef: $!\n"); open (FH, "<list") or error("\nError opening: list\nRef: $!\n"); while(<FH>) { print CHILD, $_; } close FH or error("\nError closing: list\nRef: $!\n"); close CHILD or error("\nError closing: childPid\nRef: $!\n); } else { error("\nError forking\nRef: $!\n"); } 
  • First: what does perldoc pipe mean under READHANDLE , WRITEHANDLE ?

  • The second one. Can I implement the solution without relying on CPAN or other modules?

alt text
(source: wellho.net )

+3
source share
1 answer

Here is a simplified example based on the code found in perldoc perlipc :

 #!/usr/bin/perl use strict; use warnings; $SIG{CHLD} = sub { wait }; pipe my $reader, my $writer; my $pid = fork; defined $pid or die "fork failed: $!"; if ( $pid ) { # parent close $reader; for my $n ( 1 .. 5 ) { select $writer; $| = 1; print $writer "Message $n\n" or die "Failed to pass message to child: $!"; sleep 1; } close $writer; exit; } else { # child close $writer; while ( my $msg = <$reader> ) { print "Child received: $msg"; last if rand > 0.5; # to check error handling in parent } close $reader; exit; } 
+5
source

Source: https://habr.com/ru/post/1305906/


All Articles