Home > Backend Development > C++ > How to Gracefully Handle Ctrl-C Events in C ?

How to Gracefully Handle Ctrl-C Events in C ?

Mary-Kate Olsen
Release: 2024-11-11 01:47:02
Original
261 people have browsed it

How to Gracefully Handle Ctrl-C Events in C  ?

Catching Ctrl-C Events in C

In C , capturing Ctrl-C (SIGINT) events is crucial for handling graceful program termination. The signal library provides a straightforward mechanism for this, but its reliability varies across different implementations.

To ensure consistent behavior, it's recommended to use the sigaction function instead. Here's a revised version of Tom's code using sigaction:

#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;
}
Copy after login

This code defines a signal handler, my_handler, that prints a message and exits the program when a SIGINT signal (Ctrl-C) is received. The sigaction function registers the handler for the SIGINT signal and sets the necessary flags for correct behavior.

Now, when the program is running and Ctrl-C is pressed, it will catch the signal and invoke the handler, which in turn prints the appropriate message and terminates the program gracefully.

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

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