Perl 管道函数



说明

此函数打开一对已连接的通信管道:READHANDLE 用于读取和 WRITEHANDLE 用于写入。您可能需要将 $| 设置为在每条命令后刷新您的 WRITEHANDLE。

语法

以下为此函数的简单语法 −

pipe READHANDLE, WRITEHANDLE

返回值

此函数在失败时返回 0,在成功时返回 1。

示例

以下是显示其基本用法的示例代码 −

#!/usr/bin/perl -w

use IO::Handle;

pipe(PARENTREAD, PARENTWRITE);
pipe(CHILDREAD, CHILDWRITE);

PARENTWRITE->autoflush(1);
CHILDWRITE->autoflush(1);

if ($child = fork) { # Parent code
   close CHILDREAD; # We don't need these in the parent
   close PARENTWRITE;
   print CHILDWRITE "34+56;\n";
   chomp($result = <PARENTREAD>);
   print "Got a value of $result from child\n";
   close PARENTREAD;
   close CHILDWRITE;
   waitpid($child,0);
} else {
   close PARENTREAD; # We don't need these in the child
   close CHILDWRITE;
   chomp($calculation = <CHILDREAD>);
   print "Got $calculation\n";
   $result = eval "$calculation";
   print PARENTWRITE "$result\n";
   close CHILDREAD;
   close PARENTWRITE;
   exit;
}

它将产生以下结果:您可以看到计算值发送至 CHILDWRITE,然后子进程从 CHILDREAD 中读取该值。然后计算结果,并通过 PARENTWRITE 发送回父进程,父进程从 PARENTREAD 中读取结果。

Got 34+56;
Got a value of 90 from child
perl_function_references.htm
广告