perl system和exec 调用

system 函数:

[oracle@jhoa 10]$ cat 1.pl 
system "date";
[oracle@jhoa 10]$ perl 1.pl 
Sat Oct 11 15:39:51 CST 2014

[oracle@jhoa 10]$ cat 1.pl 
system "sleep 60";

[oracle@jhoa ~]$ ps -ef | grep 1.pl
oracle    8796  7930  0 15:40 pts/0    00:00:00 perl 1.pl
oracle    8835  8801  0 15:40 pts/1    00:00:00 grep 1.pl

[oracle@jhoa ~]$ ps -ef | grep 8796
oracle    8796  7930  0 15:40 pts/0    00:00:00 perl 1.pl
oracle    8797  8796  0 15:40 pts/0    00:00:00 sleep 60
oracle    8837  8801  0 15:40 pts/1    00:00:00 grep 8796


[oracle@jhoa ~]$ ps -ef | grep 8797
oracle    8797  8796  0 15:40 pts/0    00:00:00 sleep 60
oracle    8839  8801  0 15:40 pts/1    00:00:00 grep 8797


会创建一个子进程来运行sleep 命令,并且它继承了Perl的标准输入,标准输出和标准出错


[oracle@jhoa 10]$ cat 2.pl 
unless (system "date") {
print "$!\n";
print "We gave you a date,Ok!\n";
}
[oracle@jhoa 10]$ perl 2.pl 
Sat Oct 11 16:15:01 CST 2014

We gave you a date,Ok!


操作符的返回值是根据子进程的结束状态来决定的,在Unix里,退出值0代表正常,非0值则代表有问题

0在Perl里代表假

exec 函数

到目前为止,我们提到的system函数的所有语法也都适用于exec函数。当然有一个重要的例外,

system函数会创建子进程,子进程会在Perl睡眠期间执行任务。而exec 函数却导致Perl进程自己去执行任务。

这类似于程序调用与goto的差别


[oracle@jhoa 10]$ cat 3.pl 
unless (exec  "sleep 60") {
print "$!\n";
print "We gave you a date,Ok!\n";
}


[oracle@jhoa ~]$ ps -ef | grep sleep
oracle    9014  7930  0 16:47 pts/0    00:00:00 sleep 60
oracle    9016  8801  0 16:47 pts/1    00:00:00 grep sleep

[oracle@jhoa ~]$ ps -ef | grep 7930
oracle    7930  7929  0 09:15 pts/0    00:00:00 -bash
oracle    9014  7930  0 16:47 pts/0    00:00:00 sleep 60
oracle    9020  8801  0 16:47 pts/1    00:00:00 grep 7930
exec 函数却导致Perl进程自己去执行任务。

[oracle@jhoa 10]$ perl 4.pl 
Sat Oct 11 16:55:23 CST 2014
[oracle@jhoa 10]$ cat 4.pl 
exec "date";
system "ls";
[oracle@jhoa 10]$ perl 4.pl 
Sat Oct 11 16:55:28 CST 2014

exec 后面写的任何代码都无法运行

你可能感兴趣的:(Perl开发)