Search code examples
clinuxtimeoutsignalswindows-subsystem-for-linux

Why is this application being closed?


Does handling signals make the application close in anyway? my goal is to do some action when time run out but get stuck in the loop, until the user enter q or EOF is found but for some reason as soon the singal is received, the application seem to not execute the loop at all just print printf("returning from main!!\n"); and exit from the application. What am I misisng? how do i fix that?

here's the full code:

#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;
}

Solution

  • The signal handler is getting fired while getchar is waiting for user input.

    After the signal handler returns, getchar returns EOF and errno is set to EINTR, indicating that the call was interrupted. This causes your loop to exit.