0

I'm trying to write a program that intercepts Ctrl^C using sigaction, and then terminates the child of a fork.

Code:

static void usrHandler(int sig, siginfo_t * si, void * ignore) {
    printf("Interrupt Worked");
}

int main(int argc, char * argv[]) {
    struct sigaction sa;
    sa.sa_flags = SA_SIGINFO;
    sigemptyset( & sa.sa_mask);
    sa.sa_sigaction = usrHandler;
    sigaction(SIGINT, & sa, NULL);

    int currentFile = 1;
    int fd;
    int forkChild;

    forkChild = fork();
    if (forkChild == 0) {
        sleep(100);
    } else if (forkChild > 0) {
        sa.sa_sigaction = SIG_IGN;
        sigaction(SIGUSR1, & sa, NULL);
    }
}

I tried to remove all non necessary code for my example. For some reason I can not get the interrupt to work when I press Ctrl^C. Eventually I would like to be able to close the child and continue in the parent. Am I doing something wrong here?

karel
  • 5,489
  • 46
  • 45
  • 50
sixstring
  • 31
  • 6
  • I am getting a warning when compiling that says: assignment to 'void (*)(int, siginfo_t *, void *)' from incompatible pointer type 'void (*) (int) on sa.sa_sigaction = SIG_IGN – sixstring Mar 10 '19 at 06:21
  • You shouldn't use the more complex signature unless you're going to use the data. Use the `sa.sa_handler` element of `struct sigaction` and `void usrHandler(int signum) { … }` for the handler function. However, that evades the reported error; it doesn't explain it. When you use `SIG_IGN`, you should _not_ use `SA_SIGINFO` and should assign to `sa.sa_handler`. Ditto with `SIG_DFL`. – Jonathan Leffler Mar 17 '19 at 22:27
  • Your parent process tries to ignore `SIGUSR1`, but then immediately exits. You need to think what you're up to and have a bit more code in `main()` to make an MCVE ([MCVE]). When you interrupt, do you want the child to stop? The parent to stop? Both? You probably need a loop on either `wait()` or `waitpid()` for the parent process. – Jonathan Leffler Mar 17 '19 at 22:31

1 Answers1

0

For some reason I can not get the interrupt to work when I press Ctrl^C.

Because your data in IO buffer, so change printf("Interrupt Worked"); to printf("Interrupt Worked\n"); (add \n), you will get data.

For IO buffer, see https://stackoverflow.com/a/53083985/7671328

Yunbin Liu
  • 1,484
  • 2
  • 11
  • 20