您的位置:首页 > 其它

How can I run Perl system commands in the background

2010-09-03 23:09 429 查看
这有一篇关于使用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语言。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: