Search code examples
clinuxsignalshandler

Signal in a infinte while loop


I'm totally blocked. I tried to modify the "alarm" signal in C such that to read a simple variable when the number of seconds expires. My code is the following:

in main :

int semnal;
   signal(SIGALRM, alarmHandler);
   setbuf(stdout, NULL);
    alarm(5);
    while(flag!=0)
    {
    mymenu();
    }

mymenu() function:

void mymenu()
{
  int optiune;
  printf("%s", "My menu\n");
  scanf("%i", &optiune);
}

my handler function:

void alarmHandler(int sig)
    {    
        int speed;
        printf("\nparent signal alarm handler: times up\n");
        scanf("%i", &speed);
        if(speed<0)
        {
          exit(0);
          flag=0;
        }
        else 
        {
          flag++;
          alarm(5);
        }
    }

My scope is to read unlimited options in mymenu() and after 5 seconds the signal handler to be called. After I read that something in handler, I want to read again unlimited options in mymenu() and after 5 seconds the handler to be called again and so on. My current output is the following: I read unlimited options in that while from main, after 5 seconds the handler is called, but after this point just the handler is called from 5 to 5 second, without mymenu(). Could you help me please?


Solution

  • I think I understand what you want to do, first think:

    {
       exit(0);
       flag=0;
    }
    

    The flag will not be set as 0 because your program will exit first. Answering your question, this is happening to you because when an alarm is called the function is running in that moment is interrupted and set as failed, and after the call your program will continue in the next line.

    I suggest you to use siginterrupt with 0 flag, is a call allow you to try to rerun the same function was interrupted after the alarm call.

    Good luck, tell us the result!