perl中使用pipe(管道)

打开一个管道,然后从管道中读取:
open(FILE , ” ls |” ) or die (“can not create a pipe”);

管道可以多层,比如
open(FILE,” ls -1 | grep cpp |”) or die (“can not open pipe”)
这样,通过FILE就可以读到当前目录下的所有cpp文件。

另一种方法是输出到管道:
open(FILE, ” | cat” ) or die (“can not open pipe”) ;
这样, 所有写到FILE的数据会被cat处理。

对于管道中命令很复杂的情况,请使用下面的方法:
$cmd=”blabla blabla” ;
open(FILE , ” -|” , $cmd ) or die (“can not open pipe”) ; //read FILE from $cmd output
open(FILE, ” |-” , $cmd) or die (“can not open pipe”) ; //write FILE to $cmd input

下面的几种方法是等价的,例子来自这里


open(FOO, “|tr ‘[a-z]’ ‘[A-Z]'”);

open(FOO, “|-“, “tr ‘[a-z]’ ‘[A-Z]'”);

open(FOO, “|-“) || exectr’, ‘[a-z]’, ‘[A-Z]’;

open(FOO, “|-“, “tr”, ‘[a-z]’, ‘[A-Z]’);
open(FOO, “cat -n ‘$file’|”);

open(FOO, “-|”, “cat -n ‘$file'”);

open(FOO, “-|”) || exec “cat”, “-n”, $file;

open(FOO, “-|”, “cat”, “-n”, $file);

safe fork: from here


my $PRECIOUS = “/path/to/some/safe/file”;

my $sleep_count;

my $pid;

do {

$pid = open(KID_TO_WRITE, “|-“);

unless (defined $pid) {

warn “cannot fork: $!”;

die “bailing out” if $sleep_count++ > 6;

sleep 10;

}

} until defined $pid;

if ($pid) { # I am the parent

print KID_TO_WRITE @some_data;

close(KID_TO_WRITE) || warn “kid exited $?”;

} else { # I am the child

# drop permissions in setuid and/or setgid programs:

($EUID, $EGID) = ($UID, $GID);

open (OUTFILE, “> $PRECIOUS”)

|| die “can’t open $PRECIOUS: $!”;

while () {

print OUTFILE; # child’s STDIN is parent’s KID_TO_WRITE

}

close(OUTFILE) || die “can’t close $PRECIOUS: $!”;

exit(0); # don’t forget this!!

}


本文地址: http://www.bagualu.net/wordpress/archives/1621 转载请注明




发表评论

电子邮件地址不会被公开。 必填项已用*标注