【问题标题】:Linux (C) Signal HanldingLinux (C) 信号处理
【发布时间】:2021-07-03 17:16:51
【问题描述】:

我的简单代码将捕获所有信号并显示您在确切时间触发的信号,但我的问题是当信号被捕获时代码将结束并且我无法触发其他 SIGINT 的任何其他信号我该如何触发喜欢 (SIGSEGV , SIGABRT)

#include<stdio.h>
#include<time.h>
#include<signal.h>
#include<unistd.h>
//bos501_hw_signals_handling_Linux
void sig_handler(int signo)
{ time_t current_time;
    char* c_time_string;
    //Catch the current time. /
    current_time = time(NULL);
    // Convert to local time  /
    c_time_string = ctime(&current_time);
//putting a condition for signals when they are caught to print the signal.
    if (signo == SIGINT)
printf("received SIGUSR1\n"" ::Current time is %s", c_time_string);
    else if (signo == SIGSEGV)
printf("received SIGSEGV\n"" ::Current time is %s", c_time_string);
    else if (signo == SIGABRT)
printf("received SIGABRT\n"" ::Current time is %s", c_time_string);
    else if (signo == SIGKILL)
printf("received SIGKILL\n"" ::Current time is %s", c_time_string);
    else if (signo == SIGSTOP)
printf("received SIGSTOP\n"" ::Current time is %s", c_time_string);
}

int main(void)
{    //putting a conditon to show the signal that isnt caught like (SIGKILL,SIGSTOP)
    if (signal(SIGUSR1, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGUSR1\n");
    if (signal(SIGSEGV, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGSEGV\n");
    if (signal(SIGABRT, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGABRT\n");
    if (signal(SIGKILL, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGKILL\n");
    if (signal(SIGSTOP, sig_handler) == SIG_ERR)
        printf("\ncan't catch SIGSTOP\n");
    // long wait to process the signal 
    while (1)
        sleep(1);
    return 0;
    //end of code
}

【问题讨论】:

  • 不鼓励在信号处理程序中使用 stdio 函数。查看signal-safety(7) 以获取异步信号安全函数列表。

标签: c linux signals


【解决方案1】:
  1. SIGKILL 和 SIGSTOP 信号不能被捕获、阻止或忽略。对于这些,默认操作总是发生。

  2. 不推荐使用信号系统调用。使用 sigaction 系统调用来设置信号动作。

  3. printf 不应在信号处理程序中使用。请改用文件描述符 2 上的 write 系统调用。

【讨论】:

  • 我如何使用 sigaction 系统调用,是的,我想忽略我没有提到的其他两个信号(SIGSTOP,SIGKILL)我该怎么做
  • 您不能忽略 SIGSTOP 和 SIGKILL。如果这些信号中的任何一个出现,与它们相关的默认操作就会发生。 sigaction系统调用使用示例请参考softprayog.in/programming/signals-in-linux
猜你喜欢
  • 1970-01-01
  • 2021-05-19
  • 2014-04-29
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多