Created
July 24, 2018 16:28
-
-
Save emersonmello/bb9e8f91b13daf1ad10f763c20833eda to your computer and use it in GitHub Desktop.
Unix signals handling in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* File: os-signals.c | |
* Author: Emerson Ribeiro de Mello <mello@ifsc.edu.br> | |
* | |
* Created on 30 June 2016 | |
*/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <signal.h> | |
void signal_handler(int signal) { | |
switch (signal) { | |
case SIGHUP: | |
printf("\nSIGHUP received - Finalizing....\n"); | |
exit(EXIT_SUCCESS); | |
case SIGUSR1: | |
printf("\nSIGUSR1 received - Finalizing....\n"); | |
exit(EXIT_SUCCESS); | |
case SIGINT: | |
printf("\nSIGINT received - Finalizing....\n"); | |
exit(EXIT_SUCCESS); | |
case SIGTERM: | |
printf("\nSIGTERM received - ok, I'm going to start cleaning the houseand and then exit...\n"); | |
exit(EXIT_SUCCESS); | |
case SIGQUIT: | |
printf("\nSIGQUIT received - Finalizing....\n"); | |
exit(EXIT_SUCCESS); | |
default: | |
fprintf(stderr, "\nCaught wrong signal: %d\n", signal); | |
exit(EXIT_FAILURE); | |
} | |
} | |
int main(int argc, char** argv) { | |
// Handling Linux Signals | |
if (signal(SIGHUP, signal_handler) == SIG_ERR) { | |
perror("\nCan't catch SIGHUP\n"); | |
} | |
if (signal(SIGQUIT, signal_handler) == SIG_ERR) { | |
perror("\nCan't catch SIGQUIT\n"); | |
} | |
if (signal(SIGUSR1, signal_handler) == SIG_ERR) { | |
perror("\nCan't catch SIGUSR1\n"); | |
} | |
if (signal(SIGTERM, signal_handler) == SIG_ERR) { | |
perror("\nCan't catch SIGTERM\n"); | |
} | |
if (signal(SIGINT, signal_handler) == SIG_ERR) { | |
perror("\nCan't catch SIGINT\n"); | |
} | |
int sair = 1; | |
int pid = getpid(); | |
while(sair != 0){ | |
printf("\nPID: %d.\nTry:\n(1) Press CTRL+C\n(2) Press CTRL+\\\n", pid); | |
printf("(3) kill -s USR1 PID\n(4) kill PID\n(5) kill -9 PID\n"); | |
sleep(3); | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment