Skip to content

Instantly share code, notes, and snippets.

@griloHBG
Created May 26, 2022 20:47
Show Gist options
  • Save griloHBG/29cccec5111e4e484e1fbd6a96b42432 to your computer and use it in GitHub Desktop.
Save griloHBG/29cccec5111e4e484e1fbd6a96b42432 to your computer and use it in GitHub Desktop.

Revisions

  1. griloHBG created this gist May 26, 2022.
    95 changes: 95 additions & 0 deletions signal_logger_test.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,95 @@
    //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;
    }