Bash – What’s the difference between Ctrl-Z and kill -STOP

bashshell-scriptsignals

When I run a command (make on a large project) from the shell, I can type Ctrl-Z to stop the process and return to the shell. Subsequently, I can run fg to continue the process.

I'm trying to write a shell script to automate this (specifically, to check my CPU temperature every few seconds and stop the process if it gets too hot, since my computer is prone to overheating). My first attempt worked like this (simplified):

make &
subpid="$!"

sleep 2
# If the CPU temperature is too high...
kill -STOP "$subpid"

sleep 2
# If the CPU temperature has dropped to safe levels...
kill -CONT "$subpid"

wait "$subpid"

Unfortunately, this didn't work; sending SIGSTOP to the process didn't pause it (as made evident by its continuing to send output to the terminal). I ran make & at the command line, sent SIGSTOP, and checked the process status with ps; it was listed as stopped (and started again when I sent SIGCONT), but it was still spewing output and driving up my core temperature! Stopping it with Ctrl-Z never had this problem, but I don't know how to do that in a script.

What makes Ctrl-Z different from kill -STOP, and how can I get the behavior of the former in a shell script?

Best Answer

What makes Ctrl-Z different from kill -STOP, and how can I get the behavior of the former in a shell script?

CTRL-Z usually sends SIGTSTP (which can be blocked), and - apart from other things - shells often reset tty to a previously saved state on these occasions. More importantly however, the controlling terminal process group is set to the shell's PID (and then again to a PID of a job resumed with fg).

Back to your original problem: using a temperature dependent frequency scaling like e.g. Cpufreqd might be actually a better hammer for your nail.

Related Question