第十六章 进程管理
1. system函数
?system "ls -l $HOME";? #启用shell子进程
?system "netstat -ap &"; #后台运行
?system 'for i in * ; do echo ====$i=====; done'
?
?system一般使用一个以上参数,避免调用shell启动子进程
?system "tar","cvf",$tarfile,@dirs;
?system "/bin/sh","-c",$command_line; #多参数启用子进程
?
?system的返回值为命名结果的返回值,一般0为正常,非0为异常
2. exec函数
?用法及参数完全和system函数,但是会跳进子程序中不再返回,exec后面的程序永远不会执行;
?exec后面只能接die "";
3. 环境变量%ENV
?%ENV 环境变量通常从父进程继承来
?$ENV{'PATH'} = "";
4. 用反引号捕获输出
?my @line = `who`;
5. 将进程视为文件句柄(打开管道)
?system启动的都是同步进程,需要等待结束. Perl其实也可以开启异步子进程,并保持通信.
?open DATE,"date |" or die "Can't pipe from data:$!n";? #只读文件句柄,date | your_program
?open MAIL,"| mail Jerry" or die "Can't pipe to mail:$!n"; #只写文件句柄,your_program | mail Jerry
?my $now = <DATE>; #读
?print MAIL "The time is now $now"; #写,发送mail
?close(MAIL) or die "mail no-zero exit $?" if $?;
6. fork创建子进程
?my $pid = fork;
?if ( $pid == 0) {
??#child process
??exec "date";
??die "Can't exec date:$!";
?}
?waitpid($pid,0); #等待子进程
?7. 发送与接收信号 ?kill INT,$pid or die "Can't not signal SIGINT:$!n"; ?$SIG{'INT'} = 'my_int_handle'; # my_int_handle为信号处理函数,%SIG为Perl内置特殊哈希 ?$SIG{CHLD} = 'IGNORE'; #忽略子进程信号 ?$SIG{'INT'} = 'DEFAULT'; #设置为缺省处理?