Home  >  Article  >  Backend Development  >  How can I intercept Ctrl C signals in C ?

How can I intercept Ctrl C signals in C ?

DDD
DDDOriginal
2024-11-16 15:26:03316browse

How can I intercept Ctrl C signals in C  ?

Intercepting Control-C Signals in C

In the realm of programming, it's often necessary to capture keyboard events, such as the ubiquitous Ctrl C, which typically triggers program termination. This article addresses this specific need: how to intercept Ctrl C signals in C .

Capturing Ctrl C Events

In C , there are two primary methods for capturing Ctrl C events: signal and sigaction.

Using sigaction

The sigaction function provides a more reliable approach compared to signal, as it offers greater control and portability across different implementations. To use sigaction, follow these steps:

  1. Include necessary headers:

    #include <signal.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <unistd.h>
  2. Define a signal handler function:

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

    In this handler, you can specify the actions to be performed when Ctrl C is pressed.

  3. Configure the sigaction:

    struct sigaction sigIntHandler;
    
    sigIntHandler.sa_handler = my_handler;
    sigemptyset(&amp;sigIntHandler.sa_mask);
    sigIntHandler.sa_flags = 0;
    
    sigaction(SIGINT, &amp;sigIntHandler, NULL);

    Here, you attach your signal handler to the Ctrl C signal (SIGINT) and specify signal-related settings.

  4. Pause the program:

    pause();

    This function causes the program to wait for signals, including Ctrl C.

Example:

The following example demonstrates how to use sigaction to capture Ctrl C events:

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

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

When you run this program and press Ctrl C, it will print "Caught signal 2" and exit gracefully.

The above is the detailed content of How can I intercept Ctrl C signals in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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