【发布时间】:2023-02-24 11:44:11
【问题描述】:
无论如何处理信号都会使应用程序关闭吗?我的目标是在时间用完时执行一些操作但陷入循环,直到用户输入 q 或找到 EOF 但由于某种原因,一旦收到信号,应用程序似乎根本不执行循环只是打印printf("从主函数返回!!\n");并退出应用程序。我错过了什么?我该如何解决?
这是完整的代码:
#include <signal.h>
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <ucontext.h>
#include <unistd.h>
void thread_signal_handler(int signal)
{
// Thread's time slice has run out, switch to another thread
// ...
printf("time run out!!!\n");
}
int main()
{
// Set up the signal handler for the thread's time slice
struct sigaction sa;
sa.sa_handler = thread_signal_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGALRM, &sa, NULL);
// Set up the timer for the thread's time slice
struct itimerval timer;
timer.it_value.tv_sec = 5;
timer.it_value.tv_usec = 0;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
setitimer(ITIMER_REAL, &timer, NULL);
while (1)
{
int ch = getchar();
if(ch == 'q' || ch == EOF) break;
}
printf("returning from main!!\n");
return 0;
}
【问题讨论】:
-
在信号处理程序中调用
printf并不安全,尽管它经常有效。
标签: c linux timeout signals wsl-2