如何将分叉子进程中的 croak 抛出的异常传播到父进程/前台进程?
在分叉子进程中通过 croak 抛出异常似乎会像后台进程一样打印错误。也就是说,它会破坏 shell 提示符。
如果我die
而不是croak
,错误消息会作为前台进程弹出。我试图找出 Carp
文档中的原因,但没有成功。
这就是我的意思。 croak
版本:
$ perl Wrapper.pm
$ error: ... does not exist at Wrapper.pm line 624
die
版本:
$ perl Wrapper.pm
error: ... does not exist at Wrapper.pm line 515.
我尝试捕获 fork
并将 $@
打印到 STDERR 并退出,但这没有效果。有什么想法吗?我希望能够在这种特殊情况下使用 croak 。
尽管我的代码相当复杂,但您可以通过以下方式重现此行为:
$ perl -MCarp -e 'unless (fork) {croak "child"}'
$ child at -e line 1
<- cursor blinking here. Pressing enter gives me a new prompt:
$
$ perl -e 'unless (fork) {die "child"}'
child at -e line 1.
$
已解决: cjm 明白了:
$ perl -e '$SIG{__DIE__} = sub {sleep 1}; unless (fork) {die "child"}'
$ child at -e line 1.
感谢您的帮助!
Throwing an exception via croak
in a forked child process seems to print the error as a background process would. That is, it clobbers the shell prompt.
If I die
instead of croak
, the the error message pops up as a foreground process. I've trying to find out why that is in the Carp
documentation without any luck.
Here's what I mean. The croak
version:
$ perl Wrapper.pm
$ error: ... does not exist at Wrapper.pm line 624
The die
version:
$ perl Wrapper.pm
error: ... does not exist at Wrapper.pm line 515.
I tried trapping the fork
and printing $@
to STDERR and exiting, but that didn't have an effect. Any ideas? I'd like to be able to use croak
in this particular case.
Although my code is quite a bit more convoluted, here is how you can reproduce this behavior:
$ perl -MCarp -e 'unless (fork) {croak "child"}'
$ child at -e line 1
<- cursor blinking here. Pressing enter gives me a new prompt:
$
$ perl -e 'unless (fork) {die "child"}'
child at -e line 1.
$
Solved: cjm got it:
$ perl -e '$SIG{__DIE__} = sub {sleep 1}; unless (fork) {die "child"}'
$ child at -e line 1.
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我很确定这只是一个时间问题。
die
版本稍快一些,因此它有更好的机会在 shell 打印下一个提示之前输出错误消息。当我尝试运行您的示例时,croak
版本通常会在提示之后打印,但有时会在提示之前打印。die
版本非常一致地出现在提示之前。I'm pretty sure it's just a timing issue. The
die
version is slightly faster, so it has a better chance of outputting the error message before the shell can print the next prompt. When I try running your examples, thecroak
version usually gets printed after the prompt, but occasionally it comes before the prompt. Thedie
version pretty consistently comes before the prompt.