-1

I want a script run in the background, take some actions for every hour. It should also quit if receiving a signal. And at last, it should perform some clean-up actions before quitting.

Based on the concept, I wrote something like the following:

trap 'clean_up; exit' SIGTERM
while true
do
    someActions
    sleep 1h
done

I ran the script by

./script &

I kill the script by

kill -SIGTERM <pid>

It turned out the script didn't work as expected. I think the reason is that you can kill a sleeping process only by SIGKILL signal. But on the other hand, you cannot trap a SIGKILL signal to do some cleanup before quitting.

So how can I make a process wait in the background and be able to quit when it receives a signal other than SIGKILL?

  • 1
    Show us a small script that you have tried. (Not something like) – ctrl-alt-delor Apr 10 '15 at 10:12
1

If by "didn't work as expected" you mean you wrote a SIGTERM handler and it did not fire for SIGTERM, you've made a mistake in your code.

Here's a working example:

#!/bin/bash

cleanup () {
        echo "goodbye!"
        exit 0
}

trap 'cleanup' SIGTERM

while sleep 1; do
        echo $BASHPID
done

Reacts as expected to kill -SIGTERM. You can use any signal you want except, as you already know, SIGKILL, and SIGSTOP.

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.