windows - 当父进程被杀死/完成时如何保持子进程处于活动状态(在 Windows 中)
问题描述
我实际上是在创建一个脚本,在该脚本中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 实现这一点?
解决方案
Windows 不提供分叉机制。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 {
...
}