+ -
当前位置:首页 → 问答吧 → 谁给解释下这几行代码

谁给解释下这几行代码

时间:2011-06-18

来源:互联网

pipe(FROM_PARENT, TO_CHILD)   or die "pipe: $!";
pipe(FROM_CHILD, TO_PARENT)   or die "pipe!";
select((select(TO_CHILD), $| = 1))[0]);
select((select(TO_PARENT), $| = 1))[0]);

作者: vgra   发布时间: 2011-06-18



QUOTE:
pipe(FROM_PARENT, TO_CHILD)   or die "pipe: $!";
pipe(FROM_CHILD, TO_PARENT)   or die "pipe!";
s ...
vgra 发表于 2011-06-18 11:14




    pipe函数用来建立一对管道:
http://perldoc.perl.org/functions/pipe.html

select那句,表示把对应的句柄的写buffer关闭:
$|

If set to nonzero, forces a flush right away and after every write or print on the currently selected output channel. Default is 0 (regardless of whether the channel is really buffered by the system or not; $| tells you only whether you've asked Perl explicitly to flush after each write). STDOUT will typically be line buffered if output is to the terminal and block buffered otherwise. Setting this variable is useful primarily when you are outputting to a pipe or socket, such as when you are running a Perl program under rsh and want to see the output as it's happening. This has no effect on input buffering. See getc for that. See select on how to select the output channel. See also IO::Handle.

作者: 兰花仙子   发布时间: 2011-06-18



QUOTE:
select((select(TO_CHILD), $| = 1))[0]);



补充一下,select函数的返回是select之前的旧句柄。
所以上述写法对应于:
  1. my $old_fh = select TO_CHILD;
  2. $|=1;  # 关闭TO_CHILD的buffer
  3. select $old_fh;
复制代码

作者: 兰花仙子   发布时间: 2011-06-18

后面两个纯粹是因为 $| 对应的文件句柄问题。要先切换默认输出文件再设置 $|,然后再把切换回来

作者: zhlong8   发布时间: 2011-06-18