典型用法:在perldoc -f fork
,waitpid
,wait
,kill
和perlipc
use POSIX ':sys_wait_h'; # for &WNOHANG
# how to create a new background process
$pid = fork();
if (!defined $pid) { die "fork() failed!" }
if ($pid == 0) { # child
# ... do stuff in background ...
exit 0; # don't forget to exit or die from the child process
}
# else this is the parent, $pid contains process id of child process
# ... do stuff in foreground ...
# how to tell if a process is finished
# also see perldoc perlipc
$pid = waitpid -1, 0; # blocking wait for any process
$pid = wait; # blocking wait for any process
$pid = waitpid $mypid, 0; # blocking wait for process $mypid
# after blocking wait/waitpid
if ($pid == -1) {
print "All child processes are finished.\n";
} else {
print "Process $pid is finished.\n";
print "The exit status of process $pid was $?\n";
}
$pid = waitpid -1, &WNOHANG; # non-blocking wait for any process
$pid = waitpid $mypid, 0; # blocking wait for process $mypid
if ($pid == -1) {
print "No child processes have finished since last wait/waitpid call.\n";
} else {
print "Process $pid is finished.\n";
print "The exit status of process $pid was $?\n";
}
# terminating a process - see perldoc -f kill or perldoc perlipc
# this can be flaky on Windows
kill 'INT', $pid; # send SIGINT to process $pid
血淋淋的細節。關於爲SIGCHLD
事件設置處理程序的perlipc
中的內容應該特別有用,儘管Windows不支持該操作。
分叉進程的I/O在Unix和Windows上通常是安全的。文件描述符是共享的,所以這樣的事情
open X, ">", $file;
if (fork() == 0) { # in child
print X "Child\n";
close X;
exit 0;
}
# in parent
sleep 1;
print X "Parent\n";
close X;
兩個孩子,父進程將成功地寫入同一個文件(注意輸出緩衝的,雖然)。
來源
2010-06-18 02:00:36
mob
更像是一個工作,但也許你可以每當一個進程開始時,寫一個文件,當它退出刪除文件或類似的東西......有一個主要的腳本來監視這些文件左右...... – Prix 2010-06-18 01:32:43