linuxbashshell

How bash handles/difference signals in heredocs?


I currently making a project to write my own shell, a very simple one, but i got stuck on how I can differentiate a SIGINT signal received inside a heredoc and while interactive mode.

In bash, consider this input:

cat << eof

it will open input lines until the "eof" delimiter is meet or a signal is detected.

enter image description here

and this is how the bash behave receiving a SIGINT outside a heredoc:

enter image description here

the question is, how bash handles these signals differently? the heredoc is run as a child process from the shell, so they share the same signals handlers, since they will have different behaviors (in heredoc SIGINT ends the process, in interactive mode SIGINT is ignored)


Solution

  • how bash handles these signals differently?

    There are several ways to handle signals differently in the same application.

    1. You can have multiple signal handlers and switch when as you enter different states (or parts) of your application. Just issue signal(SIG_INT, handler_for_ABC) and do a signal(SIG_INT, normal_handler) upon returning to "wait for user" state of your application.
    2. You can have a single handler, with a global variable of enum data type. And in the handler you just switch(app_state) { case ABC: do_abc_handling(); break; default do_normal_handling()}. Just do not forget to reassign this global flag as needed.
    3. You can have a combination of this two approaches - a global flag will be an index to a table with actual handlers or just a pointer to an appropriate handler. And you would have a solitary signal handler function, which would call that appropriate handler from index/pointer flag.
    4. If you prefer to spawn a child process for a different state of your application - then the child will have its own set of signal handlers.
    5. If you spawn a thread (and not a process), then the singular signal handler can use thread id (just call pthread_self()) and use it to determine which set of handlers are appropriate in this case.

    There are several other ways to have a single-entry with multiple paths approaches. Just choose whatever is more convenient to you.