如何解决如何在父进程被杀死/完成时保持子进程处于活动状态在 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,$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 不提供 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 {
...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。