c - 如何显示 sigusr1 和 sigusr2 的输出?

标签 c operating-system signals

我是 C 和系统编程的初学者。我编写了一个程序,它应该显示以下内容: 捕获 SIGUSR1 捕获 SIGUSR2 捕获信号

但是,当我执行“./test.c”时,当我键入 Ctrl-C 时,我唯一看到的是“Caught SIGINT”。如何修复我的代码以便我的程序显示上述消息?抱歉,如果我的问题很愚蠢。非常感谢您的帮助。感谢您的阅读。

编辑:

#include <signal.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

static void sigHandler_sigusr1(int sig)
{
    //sig contains the signal number that was received
    printf("Caught SIGUSR1, %d\n", getpid());
    //kill(getpid(), SIGUSR1);
}

static void sigHandler_sigusr2(int sig)
{
    //sig contains the signal number that was received
    printf("Caught SIGSR2, %d\n", getpid());
    //kill(getpid(), SIGUSR2);
}

static void sigHandler_sigint(int sig)
{
    //sig contains the signal number that was received
    printf("Caught SIGINT, Existing, %d\n", getpid());
    //kill(getpid(), SIGINT);
    exit(EXIT_SUCCESS);
}

int main(int argc, char *argv[])
{

    if (signal(SIGUSR1, sigHandler_sigusr1) == SIG_ERR)
        printf("Unable to create handler for SIGUSR1\n");

    if (signal(SIGUSR2, sigHandler_sigusr2) == SIG_ERR)
        printf("Unable to create handler for SIGUSR2\n");

    if (signal(SIGINT, sigHandler_sigint) == SIG_ERR)
        printf("Unable to create handler for SIGINT\n");

    kill(getpid(), SIGUSR1);
    kill(getpid(), SIGUSR2);
    kill(getpid(), SIGINT);

    while (1)
    {
        sleep(1);
    }

    return 0;
}

最佳答案

为了激活信号处理函数,您需要向进程发送信号。 您的代码中缺少它。

这就是你向自己发送信号的方式:

kill(getpid(), SIGUSR1);

您需要对 SIGUSR1SIGUSR2 执行此操作。

您可以看到 SIGINT 消息的原因是,当您按 ctrl+c 时,您实际上向您的进程发送了 SIGINT 信号。

关于c - 如何显示 sigusr1 和 sigusr2 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17702727/

相关文章:

c - 在 Doxygen 中处理两个同名的不同函数

c - 带有新库的 schoolproject 额外功能

linux - 如何在 Linux 中从 OS Process Sampler 执行 jar

python - django-paypal 收不到信号

c - 如何在 ctrl+C 上关闭管道?

c - 我的结构数组的大小不同......为什么?

c++ - char ** 数组在 C++ 中给出段错误

python - 有没有一种可靠的方法可以使用 Python 确定系统 CPU 架构?

go os/exec 命令参数问题

java - linux 父进程可以保护子进程免受信号影响吗?