Home  >  Article  >  Backend Development  >  What's the most reliable way to handle Ctrl-C events in C ?

What's the most reliable way to handle Ctrl-C events in C ?

Original
2024-11-15 17:26:03808browse

What's the most reliable way to handle Ctrl-C events in C  ?

Reliable Ctrl-C Handling in C

Question:

How can we gracefully capture a Ctrl-C event in C ?

Response:

While using signal is a common approach, it's not always reliable across different implementations. A more robust method is recommended using sigaction.

Here's the modified code based on Tom's example:

#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); // or perform other necessary actions
}

int main() {
  struct sigaction sigIntHandler;

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

  sigaction(SIGINT, &sigIntHandler, NULL);

  pause(); // block the main thread until a Ctrl-C signal is received

  return 0;
}

In this revised code, we use sigaction to register a signal handler function, my_handler. This function is executed when a Ctrl-C (SIGINT) signal is received. By using sigaction, we gain more control over the signal handling mechanisms, making our event capturing more reliable.

The above is the detailed content of What's the most reliable way to handle Ctrl-C events 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