简体   繁体   中英

learning POSIX signals using sigaction

I am trying to learn signals using the POSIX sigaction function.

What I am trying to do is prompt the user for input. After the prompt, a 5 second alarm is set. If the user does not enter something before the alarm expires, the user is reprompted. If the user does enter something, the alarm is canceled and the input is echoed back. If there is no input after the third re-prompt, the program exits.

Below is what I have so far. What this does is, after displaying the prompt for the first time, when no input is entered, it exits with the message "Alarm signal".

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <time.h>
#include <signal.h>

volatile sig_atomic_t count = 0;

void sighandler(int signo)
{
  ++count;
}

int main(void)
{
  char buf[10];
  struct sigaction act;
  act.sa_handler = sighandler;

  sigemptyset(&act.sa_mask);

  act.sa_flags = 0;

  if(sigaction(SIGINT, &act, 0) == -1)
  {
    perror("sigaction");
  }

  while(count < 3)
  {
    printf("Input please: ");

    alarm(5);

    if(fgets(buf, 10, stdin))
    {
      alarm(0);
      printf("%s", buf);
    }
  }

return 0;
}

You are registering your handler for SIGINT instead of SIGALRM . Thus when the alarm does arrive it's not catched so, per the default disposition, the process is terminated.

As a side note, you could also use select for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM