Home > Backend Development > C++ > body text

How to Gracefully Handle Ctrl-C Interrupts in C with the Sigaction Function?

Mary-Kate Olsen
Release: 2024-11-13 01:35:02
Original
524 people have browsed it

How to Gracefully Handle Ctrl-C Interrupts in C   with the Sigaction Function?

Intercepting Ctrl-C Events in C

Intercepting Ctrl-C Events is a necessary task in programming, especially when you want Gracefully respond to unexpected interruptions.

Use Sigaction

In C, it is more reliable to use the sigaction function to handle signals. The syntax is as follows:

int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact);
Copy after login

Where:

  • signum: The number of the signal to be processed, for Ctrl-C, it is SIGINT.
  • act: Specifies the action of the new signal handler.
  • oldact: Stores previous behavior.

In the example given by Thomas, the sigaction structure is as follows:

struct sigaction sigIntHandler;

sigIntHandler.sa_handler = my_handler;
sigemptyset(&sigIntHandler.sa_mask);
sigIntHandler.sa_flags = 0;
Copy after login

Where:

  • sa_handler: points to the handler function.
  • sa_mask: The signal mask to prevent during processing of this signal.
  • sa_flags: additional flags, usually 0.

Use this sigaction structure with the SIGINT signal:

sigaction(SIGINT, &sigIntHandler, NULL);
Copy after login

Handler function

Finally, you need a handler function to respond to the signal. In the example, my_handler just prints a message and exits the program:

void my_handler(int s){
   printf("Caught signal %d\n", s);
   exit(1);
}
Copy after login

Full code

Here is the complete code using sigaction to capture Ctrl-C events :

#include 
#include 
#include 
#include 

void my_handler(int s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{

   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

   pause();

   return 0;    
}
Copy after login

By using sigaction you can reliably catch Ctrl-C incident and take appropriate action.

The above is the detailed content of How to Gracefully Handle Ctrl-C Interrupts in C with the Sigaction Function?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template