【发布时间】: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(¤t_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)以获取异步信号安全函数列表。