pipe READHANDLE, WRITEHANDLE |
打开一个连接的通信管道:对READHANDLE为的读取和WRITEHANDLE为写。您可能需要设置$ |刷新您的WRITEHANDLE的每一个命令后。
0 - 返回
1 - 成功
试试下面的例子:
#!/usr/bin/perl -w #by www.gitbook.net use IO::Handle; pipe(PARENTREAD, PARENTWRITE); pipe(CHILDREAD, CHILDWRITE); PARENTWRITE->autoflush(1); CHILDWRITE->autoflush(1); if ($child = fork) # Parent code { close CHILDTREAD; # 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