我实际上是在创建一个脚本,其中 fork()
创建一个在后台运行的子进程,并使用其进程 ID 检查在前台运行的主脚本(父进程)的时间段。如果主脚本(父进程)超过阈值时间,则采取动作/秒。
在 Linux 中,它的实现是因为 INIT 进程在主脚本(父)被杀死或完成后成为活动子进程(孤立进程)的父进程。
但是,我无法在 Windows 中实现它,因为父子架构与 Linux 不同。
Perl 语言下相同(在 Linux 中)的简短代码是:
sub run_sleep {
my $pid = fork(); ## Here, $pid var. will have child process PID for parent, and value 0 for child process
return if $pid; # returns to the parent process( out of function)
print "Running child process\n"; # Proceeds for the child process
select undef, undef, undef, $initial_time_wait ;
if ( kill 0, $Parent_ID ) { ##Here, $Parent_ID is main script id (parent process id)
print "Parent process $Parent_ID_or_script_id still exists\n";
}
else {
print "Parent process $Parent_ID_or_script_id must have completed";
exit 0;
}
print "Done with child process\n";
exit 0; # end child process
}
如何在 Windows 上实现这一点?
答案 0 :(得分:2)
Windows 不提供 fork 机制。 Perl 提供了使用线程的有限模拟。由于没有创建子进程,也就没有子进程可以存活。
您也许可以使用以下内容(但您需要将任何相关状态传达给孩子,因为它不是父母的副本):
if (@ARGV && $ARGV[0] eq "!fork!") {
shift(@ARGV);
child();
exit;
}
...
my $pid;
if ($^O eq 'Win32') {
$pid = system(-1, $^X, '--', $0, "!fork!", ...args...);
} else {
...
}