2

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 Answer 1

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.

3
  • 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? Commented Nov 8, 2016 at 7:39
  • 1
    @Nishant I have edited my answer, hope that helps. Commented Nov 8, 2016 at 21:18
  • Thanks @DmitryGrigoryev really appreciate. That's more than enough pointers to understand this better. Commented Nov 9, 2016 at 3:25

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.