星期二, 11月 04, 2008

[Perl] perl使用POSIX的sys_wait_h

http://manpages.ubuntu.com/manpages/feisty/zh_TW/man1/perlfunc.html

關於POSIX的sys_wait_h的用法,原文如下:

waitpid PID,FLAGS
Waits for a particular child process to terminate and returns
the pid of the deceased process, or "-1" if there is no such
child process. On some systems, a value of 0 indicates that
there are processes still running. The status is returned in
$?. If you say

use POSIX ":sys_wait_h";
#...
do {
$kid = waitpid(-1, WNOHANG);
} until $kid > 0;

then you can do a non-blocking wait for all pending zombie pro-
cesses. Non-blocking wait is available on machines supporting
either the waitpid(2) or wait4(2) system calls. However, wait-
ing for a particular pid with FLAGS of 0 is implemented every-
where. (Perl emulates the system call by remembering the sta-
tus values of processes that have exited but have not been har-
vested by the Perl script yet.)

Note that on some systems, a return value of "-1" could mean
that child processes are being automatically reaped. See per-
lipc for details, and for other examples.

意思就是說如果要用waitpid來等待child process terminal or child process的pid
就得這樣用嚕
與fork child process等timeout或是等child process結束一樣的道理

use POSIX qw(sys_wait_h);
my $pid = fork;
unless ($pid) {
exec $command;
die "Could not exec $command";
}
my $timeout;
my $wait_pid = -1;
eval
{
local $SIG{ALRM} = sub { die "time out" };
alarm $timeout;
$wait_pid = waitpid($pid, 0);
alarm 0;
};
if ($@ and $@ =~ /time out/)
{
kill_pid($pid);
}

沒有留言:

張貼留言