【问题标题】:Why is this application being closed?为什么这个应用程序被关闭?
【发布时间】: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


【解决方案1】:

getchar 等待用户输入时,信号处理程序被触发。

信号处理程序返回后,getchar返回EOF,errno设置为EINTR,表示调用中断。这会导致您的循环退出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2013-08-09
    相关资源
    最近更新 更多