Chinaunix首页 | 论坛 | 博客
  • 博客访问: 153366
  • 博文数量: 42
  • 博客积分: 972
  • 博客等级: 准尉
  • 技术积分: 382
  • 用 户 组: 普通用户
  • 注册时间: 2010-06-17 10:59
文章分类

全部博文(42)

文章存档

2014年(2)

2013年(5)

2012年(35)

我的朋友

分类: Python/Ruby

2012-11-26 09:55:02

主要方法:

1. system("command");
使用该命令将开启一个子进程执行引号中的命令,父进程将等待子进程结束并继续执行下面的代码。

点击(此处)折叠或打开

  1. @args = (“command”, “arg1″, “arg2″);
  2. system(@args) == 0
  3. or die “system @args failed: $?”

  4. if ($? == -1) {
  5.      print “failed to execute: $!\n”;
  6. }
  7. elsif ($? & 127) {
  8.      printf “child died with signal %d, %s coredump\n”,
  9.      ($? & 127), ($? & 128) ? ‘with’ : ‘without’;
  10. }
  11. else {
  12.      printf “child exited with value %d\n”, $? >> 8;
  13. }


2. exec("command");
效果同system命令类似,区别是不会开启子进程,而是取代父进程,因此执行完引号中的命令后进程即结束。一般和fork配合使用。

点击(此处)折叠或打开

  1. exec (‘foo’) or print STDERR “couldn’t exec foo: $!”;
  2. { exec (‘foo’) }; print STDERR “couldn’t exec foo: $!”;
而对于exec这个函数来说,仅仅是执行一个系统的命令,一般情况下并没有返回值。exec只有在系统没有你要执行的命令的情况下,才会返回false值。


3. `command`;
使用反引号调用外部命令能够捕获其标准输出,并按行返回且每行结束处附带一个回车。反引号中的变量在编译时会被内插为其值。

若要获取命令返回值,需要$?>>8

a.sh

点击(此处)折叠或打开

  1. #!/bin/bash
  2. echo "script out put"
  3. exit 2
test.pl

点击(此处)折叠或打开

  1. #!/usr/bin/perl -w
  2. $output = qx(/home/liqing/a.sh);
  3. $exitcode = $?>>8;
  4. print "output = " . $output;
  5. print "exitcode = " . $exitcode;

[liqing@localhost ~]$ ./test.pl
output = script out put
exitcode = 2

$exitcode = $?; 则exitcode=512.


4. open LIST "ls -l|";
    open MORE "|more";
    @list=;
    print MORE @list;
    close(LIST);
    close(MORE);
使用带管道的文件句柄来执行外部命令,使用方式与读写文件类似。可以从外部命令的输出读取数据,也可以将数据输出到外部命令作为输入。

5. defined(my $pid=fork) or die "Can not fork: $!\n";
    unless ($pid) {
        exec ("date");
    }
waitpid ($pid,0);
使用fork将会开启子进程与父进程同时执行之后的代码,其中父进程中fork会返回一个非零的数,而子进程中将返回零。上面的代码完成和system("date")相同的功能。比起system单纯地调用外部命令,fork可以完成更加复杂的进程操作。



阅读(1071) | 评论(0) | 转发(1) |
0

上一篇:Virtualization 概念

下一篇:Perl threads

给主人留下些什么吧!~~