我可以为 Perl 中的所有信号设置一个信号处理程序吗?

发布于 2024-09-26 05:13:28 字数 193 浏览 3 评论 0原文

在 Perl 中是否可以为其接收到的所有信号只安装一个信号处理程序?这背后的原因是,我不知道我的 Perl 代码在运行时会收到什么信号。我可以看到的一种方法是将所有可用信号指向我的自定义信号处理程序,但我不想这样做。有什么简单的方法可以做到这一点吗?像这样的东西:

$SIG{'ALL'} = 'sigHandler';

Is it possible in Perl to install only one signal handler for all the signals it receive? The reason behind this is, I am not aware of what signal my Perl code will get at run time. One way I can see is that point all the available signals to my custom signal handler, but I don't want to go this way. Is there any easy way to do this? something like:

$SIG{'ALL'} = 'sigHandler';

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苏大泽ㄣ 2024-10-03 05:13:28

真的不想这样做。仅为您需要以不同于默认方式处理的信号安装信号处理程序(我们无法帮助您,因为您没有提及您正在编写哪种类型的应用程序)。

在大多数正常情况下,您根本不必编写信号处理程序——默认值已设置为完全满足您的需要。您应该立即阅读perldoc perlipc,以便您了解哪些情况你有与平常不同的地方。

您可以使用 sigtrap pragma 一次修改多个信号:它对于添加处理程序非常有用通常未捕获的信号,或用于使正常错误处理更加严格。

# install a trivial handler for all signals, as a learning tool
use sigtrap 'handler' => \&my_handler, 'signal';
sub my_handler
{
    print "Caught signal $_[0]!\n";
}

You really don't want to do this. Only install signal handlers for the signals you need to handle differently than default (which we can't help you with, since you don't mention what kind of application you are writing).

In most normal cases, you don't have to write signal handlers at all -- the defaults are set up to do exactly what you need. You should read perldoc perlipc right now so you are aware of what cases you have that differ from normality.

You can modify more than one signal at once with the sigtrap pragma: it is useful for adding handlers for normally-untrapped signals, or for making normal error handling more strict.

# install a trivial handler for all signals, as a learning tool
use sigtrap 'handler' => \&my_handler, 'signal';
sub my_handler
{
    print "Caught signal $_[0]!\n";
}
痴者 2024-10-03 05:13:28
$SIG{$_} = 'sigHandler' for keys %SIG;

如果您想以不同方式对待 __WARN____DIE__

use Config;
$SIG{$_} = 'sigHandler' for split ' ', $Config{sig_name};
$SIG{$_} = 'sigHandler' for keys %SIG;

If you want to treat __WARN__ and __DIE__ differently,

use Config;
$SIG{$_} = 'sigHandler' for split ' ', $Config{sig_name};
烟火散人牵绊 2024-10-03 05:13:28

在我的脑海里,

foreach my $key (keys %SIG) {
    $SIG{$key} = \&sighandler
}

这可能是一个坏主意。您应该只捕获您知道可以处理的任何信号。不同的信号不应以相同的方式处理。例如,您真的希望 SIGINT 以与 SIGCHILD 相同的方式处理吗?叹息? SIGUSR1?

Off the top of my head,

foreach my $key (keys %SIG) {
    $SIG{$key} = \&sighandler
}

This is probably a bad idea though. You should only catch whatever signals you know you can handle. Different signals should not be all handled in the same way. Do you really want SIGINT to be handled the same way as SIGCHILD for example? SIGHUP? SIGUSR1?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文