当 Perl 中的后台进程终止时,如何通知我?
我编写了一个 Perl 程序,它在子进程中分叉并调用后台程序,并有一个无限的 while 循环,它在父进程中执行一些操作。现在,当子进程中的后台程序终止时,应该留下 while 循环:
$pid = fork();
if ( !$pid ) {
exec( "program args" );
} else {
while ( 1 ) {
# do something
# needs help: if program terminated, break
}
}
I wrote a Perl program which forks and calls a background program in the child process and has a endless while loop which does some stuff in the parent process. Now the while loop should be left when the background program in the child process terminates:
$pid = fork();
if ( !$pid ) {
exec( "program args" );
} else {
while ( 1 ) {
# do something
# needs help: if program terminated, break
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,
fork
为您的父进程提供子进程的 PID(您在代码中尽职地检索它)。这正是父母可以照顾孩子的原因。要在循环终止时离开循环,可以使用
kill 0 $pid
来检查子进程是否仍然存在。请参阅perldoc -f Kill
。Well,
fork
gives your parent process the child's PID (which you dutifully retrieve in your code). This is precisely so the parent can look after the child.To leave the loop when it terminates, you can use
kill 0 $pid
to check whether the child still exists. Seeperldoc -f kill
.您需要有一个信号处理程序来处理子进程退出时父进程发送的 CHLD 信号。 (有关 perl 中信号处理的更多详细信息,请参阅 perldoc perlipc。)
您可以在 else 循环中执行如下操作来获取子进程。
或者您可以设置
$SIG{CHLD}='IGNORE'
来不用担心子进程变成僵尸进程。You need to have a signal handler to take care of CHLD signal the parent process is sent when the child process exits. (See
perldoc perlipc
for more details about signal handling in perl.)You can do something like below in the else loop to reap the child process.
or you can set
$SIG{CHLD}='IGNORE'
to not worry about child processes becoming zombies.根据您的申请,您可以不时检查孩子是否结束并且家长是否可以完成。您可以将 posix waitpid() 与 WNOHANG 一起使用来进行无阻塞等待,或者发出信号来检查您的孩子是否仍在运行,或者您可以使用管道(检查它何时关闭)。我个人会使用 waitpid()。 perlipc 中有一个很好的解释和例子。
Depending on your application you can check from time to time if the child ended and the parent can finish then. You can use posix waitpid() with WNOHANG to do a no-blocking wait, or signals to check if your child is still running, or you can use pipes (check when it gets closed). Personally I would use waitpid(). There is a very good explanation with examples in perlipc.
我猜想, exec() 正在阻塞,所以它在程序退出之前不会返回,但我可能是错的。
I guess, exec() is blocking, so it wouldn't return before the program quits, but I may be wrong.