LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 936|回复: 3

哪们大侠帮我解释一下这个程序

[复制链接]
发表于 2011-3-14 12:21:28 | 显示全部楼层 |阅读模式
[PHP]#!/usr/bin/perl
use warnings;
use strict;
my $date;
my $format="%s";
    unless (open DATE,"-|") {
    exec '/bin/date','-u',"+$format";
    #exec replaces our script so we never get here
}

$date=<DATE>;
close DATE;
print "Date 1date\n";

my $result=open (DATE,"-|");
exec '/bin/date','-u',"+$format" unless $result;
$date=<DATE>;
close DATE;
print "Date 2date\n";

open (DATE,"-|") || exec '/bin/date','-u',"+$format";
$date=<DATE>;
close DATE;
                                                              1,1          顶端
[/PHP]

执行结果:
[PHP]Date 1:1300076385

Date 2:1300076385

Date 3:1300076385
[/PHP]



open(DATE,"-|")返回的应该是true才对啊,这几个exec应该不会被执行啊!
发表于 2011-3-15 10:41:29 | 显示全部楼层
下面是一段摘自perl open的描述:
If you open a pipe on the command '-' , i.e., either '|-' or '-|' with 2-arguments (or 1-argument) form of open(), then there is an implicit fork done, and the return value of open is the pid of the child within the parent process, and 0 within the child process. (Use defined($pid) to determine whether the open was successful.) The filehandle behaves normally for the parent, but I/O to that filehandle is piped from/to the STDOUT/STDIN of the child process. In the child process, the filehandle isn't opened--I/O happens from/to the new STDOUT/STDIN. Typically this is used like the normal piped open when you want to exercise more control over just how the pipe command gets executed, such as when running setuid and you don't want to have to scan shell commands for metacharacters.

open(DATE,"-|"),这通常应该是3参数形式,然而没有通过第三个参数给open传递要执行的命令,结果就是上面描述的行为。
open()会隐含fork调用,创建原来进程的一个拷贝,这样open有两次返回,在父进程,返回值为子进程pid,在子进程,返回0,并且子进程的标准输出被送到父进程标准输入,父进程的标准输出被送到子进程的标准输入。

如果你使用常规的3参数形式,后面的exec就不会被执行了。
回复 支持 反对

使用道具 举报

 楼主| 发表于 2011-3-17 11:05:04 | 显示全部楼层
非常感谢!!明白了.
这是perl doc中的东西吗
回复 支持 反对

使用道具 举报

发表于 2011-3-17 23:45:29 | 显示全部楼层
  1. perldoc -f open
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表