2008年5月12日 星期一

Using fork() exec() like C, Unix environment in Perl.

Use fork() -> exec() in UNIX in Perl.

In UNIX, the child process who called exec() will use the same process id returning by fork.
However, exec() in perl is not like the exec() in UNIX.

int pid = fork();

if (pid) {
// parent
sleep(...);
kill(pid);
}
else {
// child
exec(.....);
}

In this case, the parent process will kill child process by calling "kill(pid)" in c code executing under UNIX.
But things go different in Perl
The similar code

$pid = fork();

if ($pid) {
sleep(...);
kill 'KILL', $pid;
}
else {
exec(....);
}

Although the parent process can still kill child by using "kill 'KILL', $pid", the process triggered by exec(....) still alive.
Since setpgrp() does not always work, the solution of mine is using module WIn32::Process.

http://www.xav.com/perl/site/lib/Win32/Process.html
(If the link became unavailable, just goole "Perl Win32::Process")

By using Win32::Process to open the process, you can get process id by method GetProcessID().
It seems that there is also a function "Kill" to kill the process.
However, I am not sure whether it works well. Meanwhile, it may not also close all its' child process.
I use

kill 'SIGABRT', $ProcessObj->GetProcessID();

instead.

沒有留言: