如何捕获两个以上的连续信号?

发布于 2024-12-23 01:37:31 字数 684 浏览 6 评论 0原文

如果我向以下程序发送多个后续 Hangup 信号,则只会处理其中两个,其余的将被忽略:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>

int id;
void handler(int s)
{
    id++;
    int i;
    for(i=0; i<3; i++)
    {
        printf("Sig %d\n", id);
        sleep(2);
    }
}

int main()
{
    int i;
    signal(SIGHUP, handler);
    for( i=0; ; i++ )
    {
        printf("%d\n", i);
        sleep(1);
    }
    return 0;
}

我使用以下命令向进程发送信号:

kill -l {#process}

如果我运行上面的命令连续三次命令,第三个信号将被忽略,如以下输出所示:

0
1
2
3
4
5
6
7
Sig 1
Sig 1
Sig 1
Sig 2
Sig 2
Sig 2
8
9
10
11
12

有没有办法也捕获第三个信号?

If I send multiple subsequent Hangup signals to the following program, only two of them would be handled and the rest will be ignored:

#include <stdio.h>
#include <unistd.h>
#include <signal.h>

int id;
void handler(int s)
{
    id++;
    int i;
    for(i=0; i<3; i++)
    {
        printf("Sig %d\n", id);
        sleep(2);
    }
}

int main()
{
    int i;
    signal(SIGHUP, handler);
    for( i=0; ; i++ )
    {
        printf("%d\n", i);
        sleep(1);
    }
    return 0;
}

I use the following command to send signal to the process:

kill -l {#process}

If I run the above command three times consecutively, the 3rd signal will be ignored as in the following output:

0
1
2
3
4
5
6
7
Sig 1
Sig 1
Sig 1
Sig 2
Sig 2
Sig 2
8
9
10
11
12

Is there any way to catch the third signal too?

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

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

发布评论

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

评论(2

难理解 2024-12-30 01:37:31

通常,您无法使用标准信号来做到这一点。 Unix 内核通常只对一个待处理信号进行排队。如果当进程在 Sig1 处理程序中休眠时发送 Sig2 和 Sig3,它们将被合并。

您可以使用 sigaction(2) 设置信号处理程序并向其提供 SA_NODEFER 标志。它将允许在信号处理程序中传递新信号。确保您的处理程序是可重入的,这是容易出错的解决方案。

还有 POSIX.1b (POSIX.1-2001) 扩展,称为“实时信号”。此类信号可以多次排队,但 SIGHUP 不是其中之一。 Linux 上的 signal(7) 指出实时信号的编号为 33 (SIGRTMIN) 到 64 (SIGRTMAX)。

Normally, you can't do it with standard signals. Unix kernel generally queues up only one pending signal. If Sig2 and Sig3 are sent while process sleeping in Sig1 handler, they are merged.

You can use sigaction(2) to set up your signal handler and supply SA_NODEFER flag to it. It will allow to deliver new signal while still in signal handler. Make sure your handler is reenterant, it's error-prone solution.

Also there is POSIX.1b (POSIX.1-2001) extension called "real-time signals". Such signals can be queued multiple times, but SIGHUP isn't one of them. signal(7) on Linux states that real-time signals are numbered 33 (SIGRTMIN) to 64 (SIGRTMAX).

栖迟 2024-12-30 01:37:31

在 Linux 上,待处理信号仅用一位表示。这意味着如果在处理程序已经运行时生成多个信号,那么它只会被再次调用一次。

On Linux, pending signals are represented with only one bit. This means that if multiple signals are generated while the handler is already running, then it will only be called once more.

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