Is it possible to wake a process that is paused using the sleep
command?
As an example, lets say you have this script:
#!/bin/bash
echo "I am tired"
sleep 8h
echo "I am fresh :)"
After 30 minutes you discover that you need the script to stop, that is, you wished you had written sleep 30m
instead.
You do not want to either call kill PID
or press Ctrl+C, since then the last command is not executed and you will remain tired.
Is there a way to wake the process from sleep
or perhaps use another command that supports wakeup? Solutions to both background and foreground processes are welcome.
Best Answer
When a Bash script is running a
sleep
, here's what thepstree
might look like:Both have process IDs (PIDs), even when running as a script. If we wanted to interrupt the sleep, we'd send
kill 8506
and the Bash session would resume... The problem is in a scripted environment we don't know the PID of thesleep
command and there isn't a human to look at the process tree.We can get the PID of the Bash session through the
$$
magic variable. If we can store that somewhere, we can then target instances ofsleep
that are running underneath that PID. Here's what I'd put in the script:And then we can tell
pkill
to nukesleep
instances running underneath that PID:Again, this is limiting itself to only
sleep
processes running directly under that one Bash session. As long as the PID was logged correctly, this makes it a lot safer thankillall sleep
orpkill sleep
, which could nuke anysleep
process on the system (permissions allowing).We can prove that theory with the following example where we have three separate bash sessions, two running
sleep
. Only because we're specifying the PID of the top-left bash session, only itssleep
is killed.An alternative approach is to push
sleep
into the background, store its PID and then return it to the foreground. In the script:And to kill it: