-1

I am learning about signals. In the following code, how can I keep printing the prompt inside the while loop after the CTRL-C signal has been entered. Also how to terminate the process with the CTRL-D signal.

int main(int argc, char *argv[]){  

    struct sigaction sh;
    sh.sa_handler = sigint_handler;
    sigemptyset(&sh.sa_mask);
    sh.sa_flags = 0;
    sigaction(SIGINT, &sh, NULL);

    while(1)
    {
        printf("Some prompt: ");
    }
    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
elnamy
  • 27
  • 4
  • 1
    You need to show more code (e.g. the `sigint_handler()` function), and you also need to use less code (use `int main(void)` since you don't pay any attention to `argc` or `argv`). Don't forget that by default, standard output will be line-buffered. That means you won't see the prompt until the buffer is filled. – Jonathan Leffler Dec 06 '19 at 03:36
  • 1
    And also do a search. There a quite a few existing questions on how to ignore and handle signals. There is even a question that is almost identical to this one: https://stackoverflow.com/questions/2485028/signal-handling-in-c. – kaylum Dec 06 '19 at 03:39
  • 1
    Note what is discussed in [How to avoid using `printf()` in a signal handler](https://stackoverflow.com/questions/16891019/) — and maybe [What is the difference between `signal()` and `sigaction()`?](https://stackoverflow.com/questions/231912/) – Jonathan Leffler Dec 06 '19 at 03:42
  • Does this answer your question? [Signal Handling in C](https://stackoverflow.com/questions/2485028/signal-handling-in-c) – kaylum Dec 06 '19 at 03:43

1 Answers1

0

How to use signal handler in unix?

Read signal(7) and most importantly signal-safety(7). Use fflush(3) appropriately, since stdio(3) is buffered.

Also how to terminate the process with the CTRL-D signal.

But Ctrl D is not a signal. See stty(1). It triggers the end of file condition on stdin when that is a terminal. See isatty(3) and pty(7). To detect that end of file condition, see read(2) and feof(3).

See also this answer.

You might be interested in using readline(3).

You should read a good book, such as Advanced Linux Programming (it explains signals very well) then syscalls(2).

Linux has signalfd(2), more friendly with event loops since usable with multiplexing syscalls such as poll(2).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547