Question

Im trying to handle SIGINT. Main purpose of SIGINT in my program cancelling current search function and printing the currently avaliable results. But whenever I try to catch a SIGINT signal it just closes my program. (I ve searched so much ,please just do not say that I have not searched enough)

I have tried :

  1. basic signal handling(as shown as below)

  2. sigaction functionality

  3. non-local signal handling

  4. sigprocmask (problem with procmask whenever I block a signal I cannot catch it but I need to catch and make printing on screen)

after all i have run out of search keyword to find a solution. Any idea ? (search keyword or part of code or logic way to do it ^^)

NOTE : This text may have grammar errors. Sorry for any mistakes.

#ifdef DEBUG
#define DPRINT(file ,message ,arg)      fprintf(file ,message ,arg);
#define NDPRINT(file ,message)          fprintf(file ,message);
#endif

static volatile sig_atomic_t isSignalCaught = 0;
void SIGHandler(int signo);

int main(int argc, char** argv)
{
    file_t *files,*nextP;

    signal(SIGINT, SIGHandler);

    files = findFiles("/");

    while (files != NULL) {
        DPRINT(stderr, "%s\n", files->fileName.string);
        nextP = files->pNext;
        free(files->fileName.string);
        free(files);
        files = nextP;
    }

    return(0);
}

void SIGHandler(int signo)
{
    file_t *nextP;
    if (signo == SIGINT) {
        isSignalCaught = 1;
    }
}
Was it helpful?

Solution

Here's an example of how to do what I think you want to do.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <ctype.h>

typedef void(*  sig_func_t  )(int);

volatile sig_atomic_t keep_looping = 1;

void sig_handler(int sig_number) {
    switch (sig_number) {
    case SIGINT:
        keep_looping = 0;
        break;
    }
}

int should_continue(void) {
    char line[256];
    while (1) {
        printf("Continue? (y/n) ");
        fgets(line, sizeof line, stdin);
        if (tolower(line[0]) == 'y') {
            keep_looping = 1;
            signal(SIGINT, sig_handler);
            return 1;
        }
        if (tolower(line[0]) == 'n')
            break;
    }
    return 0;
}

int main (void) {
    sig_func_t sig_func;

    sig_func = signal(SIGINT, sig_handler);
    if (sig_func == SIG_ERR) {
        perror("signal");
        exit(EXIT_FAILURE);
    }

    unsigned n = 0;
    printf("Starting...\n");

    while (1) {
        while (keep_looping)
            n++;

        printf("Current value: n=%u\n", n);

        if (!should_continue())
            break;
    }

    signal(SIGINT, sig_func);

    return EXIT_SUCCESS;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top