How can I run Perl system commands in the background

       这有一篇关于使用system函数在后台运行一个程序的文章,http://stackoverflow.com/questions/2711520/how-can-i-run-perl-system-commands-in-the-background

      文中有如下几点需要注意:

      1.Perl's system function has two modes:

         (1)taking a single string and passing it to the command shell to allow special charactors to be processed.

         (2)taking a list of strings,execing the first and passing the remaining strings as arguments

      2.You can try using fork,.Both the main process and the background one(the 'child' process) share the same STDIN,STDOUT,and STDERR filehandles .If both try to access them at once,strange things can happen.You may want to close or reopen these for the child.You can get around this with opening a pipe (see open in perlfunc) but on some system that the child process cannot outlive the parent.

      3.Signals. You'll have to catch the SIGCHLD signal,and possibly SIGPIPE too.SIGCHLD is sent when the backgrounded process finishs.SIGPIPE is sent when you write to a filehandle whose child process has closed (an untrapped SIGPIPE can cause your program to silently die).This is not an issue with system("cmd"). 

      4.Zombies .You have to be prepared to "reap" the child process when it finishes.

         $SIG{CHLD}=sub{wait}; or $SIG{CHLD}='IGNORE';

You can also use a double fork.You immdiately wait() for your first child,and the init daemon will wait() for your grandchild once it exits

         unless($pid=fork){

                 unless(fork){

                         exec "what you really wanna do";

                         die "exec failed!";

                  }

                  exit(0);

          }

          waitpid($pid,0);

 

以上虽然是针对perl语言的,但这样情况同样也适应于C语言。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值