pipe
优质
小牛编辑
127浏览
2023-12-01
描述 (Description)
此功能打开一对连接的通信管道:READHANDLE用于读取,WRITEHANDLE用于写入。 你可能需要设置$ | 在每个命令后刷新你的WRITEHANDLE。
语法 (Syntax)
以下是此函数的简单语法 -
pipe READHANDLE, WRITEHANDLE
返回值 (Return Value)
此函数在失败时返回0,在成功时返回1。
例子 (Example)
以下是显示其基本用法的示例代码 -
#!/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