3

I work on a web application which uses memcache, mongodb etc along with a python based web framework. python needs to be in foreground so that I can see the console output, or enter debugger if required.

Currently I have a start.sh

memcache_start
mongodb_start
python fg

and stop.sh

memcache_stop
mongodb_stop

scripts that does automates everything.

Normaly I kill the python in fg using Ctrl-C which kills the python. Now I need to explicitly run the stop.sh to bring the system down gracefully.

Is it possible for start.sh to be aware of the Ctrl-C SIGINT so that I can execute the stop commands as well since it is logically the next successive action that has to be performed?

1

Use trap ' ' INT before running python to tell your shell to ignore SIGINT and trap - INT afterwards to restore default behavior:

memcache_start
mongodb_start
trap ' ' INT
python fg
trap - INT
memcache_stop
mongodb_stop

After the trap ' ' INT line the shell is instructed to ignore SIGINT, but python is not affected by this. So, when you hit Ctrl+C, python quits normally, but the shell carries on, executing the remaining cleanup commands of your script. The second command, trap - INT is not strictly required, it enables you to use Ctrl+C again to stop the cleanup process. That is, if you send SIGINT to memcache_stop, the shell won't try to execute mongodb_stop and will simply quit.

Here's a detailed article describing how SIGINT/SIGQUIT are handled by shells.

  • This is simply BRILLIANT. I don't understand what you mean though. Can you explain a little more in detail or give a pointer to read? – Nishant Nov 8 '16 at 7:39
  • 1
    @Nishant I have edited my answer, hope that helps. – Dmitry Grigoryev Nov 8 '16 at 21:18
  • Thanks @DmitryGrigoryev really appreciate. That's more than enough pointers to understand this better. – Nishant Nov 9 '16 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.