1

I have a program which prints some info to stdout and I run it like so:

watch -n 0.1 myprogram

My problem is that I need myprogram to exit cleanly, calling appropriate destructors to release system-wide mutexes. If I press CTRL+C, then watch is killed and myprogram isn't given the chance to exit cleanly.

Is there a way to exit watch cleanly so that it waits for the child process to finish before returning?

The man page simply says:

watch will run until interrupted

  • 4
    The premise of the question is incorrect. Your program is given a chance to exit cleanly, but it is up to the program to handle SIGINT, just as if you were to run it without watch. – Patrick May 17 '18 at 12:56
1

Regarding the first part of your question "Is there a way to exit watch cleanly?", yes, you can stop a process by sending a signal.

First you need to find out the process ID (PID) of your running watch. You can do this by name:

pidof watch

or by user and How to see process created by specific user in Unix/linux

ps -u ${USER} | grep -i watch | cut -d " " -f 1

and then stop watch by sending a signal like

kill -IT ${PID}
kill -INT $(pidof watch)

The second part of your question is then more about handling signals.

  • Yes, it was the "handling signals" that I missed. Thanks! – Stewart May 19 '18 at 15:07
  • This answer is just a complicated alternative to pressing CTRL+C. CTRL+C sends SIGINT. Why would you want to do it manually through kill? And even sending a signal manually can be done much simpler: pkill -INT watch – Patrick May 19 '18 at 17:38
  • @Patrick, maybe one need to send an other signal instead of INT. It is scriptable if necessary, at least it is showing how to do it and one could use the approach in other use cases. One could automate things. Etc... – U880D May 19 '18 at 17:43

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.