Created
May 26, 2022 20:47
-
-
Save griloHBG/29cccec5111e4e484e1fbd6a96b42432 to your computer and use it in GitHub Desktop.
A C application that logs some received signals to a file
This file contains hidden or 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
//name: signal_logger_test.c | |
//how to comiple: | |
//${CC} signal_logger_test.c -o signal_logger_test | |
#include <signal.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <time.h> | |
FILE *mylog; | |
time_t mytime; | |
int go_on = 1; | |
char signal_table[][12] ={ | |
"NO 0 SIG", | |
" 1) HUP", | |
" 2) INT", | |
" 3) QUIT", | |
" 4) ILL", | |
" 5) TRAP", | |
" 6) ABRT", | |
" 7) BUS", | |
" 8) FPE", | |
" 9) KILL", | |
"10) USR1", | |
"11) SEGV", | |
"12) USR2", | |
"13) PIPE", | |
"14) ALRM", | |
"15) TERM", | |
"16) STKFLT", | |
"17) CHLD", | |
"18) CONT", | |
"19) STOP", | |
"20) TSTP", | |
"21) TTIN", | |
"22) TTOU", | |
"23) URG", | |
"24) XCPU", | |
"25) XFSZ", | |
"26) VTALRM", | |
"27) PROF", | |
"28) WINCH", | |
"29) POLL", | |
"30) PWR", | |
"31) SYS", | |
"32) RTMIN" | |
}; | |
int counter = 1; | |
void signal_handler (int signum) { | |
struct tm tm = *localtime(&mytime); | |
fprintf(mylog, "[%d-%02d-%02d %02d:%02d:%02d] %s ( counter = %d )\n", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec, signal_table[signum], counter); | |
fflush(mylog); | |
printf("signal \"%s\" called!.\n", signal_table[signum]); | |
if ( signum == SIGINT || signum == SIGTERM ) { | |
go_on = 0; | |
} | |
} | |
int main () { | |
mytime = time(NULL); | |
mylog = fopen("signal.log", "w"); | |
for (int mysig = 1; mysig < 33; mysig++) { | |
if (signal(mysig, signal_handler) == SIG_ERR) | |
{ | |
fprintf(mylog, "signal \"%s\" not installed.\n", signal_table[mysig]); | |
printf("signal \"%s\" not installed.\n", signal_table[mysig]); | |
} | |
else | |
{ | |
fprintf(mylog, "signal \"%s\" installed correctly.\n", signal_table[mysig]); | |
printf("signal \"%s\" installed correctly.\n", signal_table[mysig]); | |
} | |
} | |
fprintf(mylog, "\n-------------------------\n"); | |
fflush(mylog); | |
while(go_on) { | |
printf("counter: %d\n", counter++); | |
sleep(1); | |
} | |
fclose(mylog); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment