Home Why is parent bash waiting for child bash to die to execute trap
Reply: 1

Why is parent bash waiting for child bash to die to execute trap

J. M.
1#
J. M. Published in 2018-01-12 18:43:46Z

This question already has an answer here:

  • Interrupt sleep in bash with a signal trap 3 answers
  • Catch signal in bash but don't finish currently running command 1 answer

Let's say I have a shell and another external shell. On the first shell I run bash: This is the parent bash. In the parent bash I set a trap with trap exit INT for example. Then I run bash again inside this parent bash, so I get a child bash where I do whatever. Then from the external shell, if I try to kill the parent bash's PID with -INT flag it does not do anything. Once I exit the child bash then it returns to the parent bash and executes the trap and kills the parent bash right away.

My main question is How can I force a trap to be executed right away, even if the corresponding bash has some subshells open? How can I work around it? I don't want brutal execution like -9 since I still want my bash's trap to do specific clean up work.

INT doesnt seem to matter. Example: In one shell run:

bash
ps
trap "echo HELLO" TERM
bash

In the other shell write:

kill -TERM (pid that you read in ps)

it won't do anything until you actually exit the child bash

Chris Dodd
2#
Chris Dodd Reply to 2018-01-12 18:56:07Z

You're running into the special handling tht shells do for keyboard interrupts (SIGINT and SIGQUIT). These signals are sent by the terminal to entire process groups, but should in general just kill the 'foreground' process in the group.

The way this actually works is that when a shell (any shell, not just bash) invokes a child (any child process, shell or executable or whatever) and immediately waits for the child's completion (a foreground command in the shell), while it is waiting, it ignores SIGINT (and SIGQUIT) signals. Once the child completes (which may be due to the child exiting from the SIGINT signal from the keyboard), the shell becomes foreground again and no longer ignores SIGINT/SIGQUIT.

The takeaway from this is that you should not use the keyboard control signals for things other than keyboard control actions. If you want to terminate the parent shell regardless of its state, use a SIGTERM signal. That's what the TERM signal is for.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.316029 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO