Bash – ctrl c vs. ctrl z with foreground job

bashjob-controlshellsignals

Ctrl+Z stops the job whereas Ctrl+C kills the job.

Why is that? Wouldn't the other way make more sense?

z@z-lap:~$ sleep 100&
[1] 4458
z@z-lap:~$ sleep 200&
[2] 4459
z@z-lap:~$ jobs
[1]-  Running                 sleep 100 &
[2]+  Running                 sleep 200 &
z@z-lap:~$ fg %1
sleep 100
^Z
[1]+  Stopped                 sleep 100
z@z-lap:~$ jobs
[1]+  Stopped                 sleep 100
[2]-  Running                 sleep 200 &
z@z-lap:~$ fg %1
sleep 100
^C
z@z-lap:~$ jobs
[2]+  Running                 sleep 200 &

Best Answer

I think you may be confused about the job control notation. Notably "Stopped" means that a job is still alive but that its ability to process anything has been held (it is not given any time on the CPU to process anything). This is effectively a "Pause" or "Suspended" state, although that is not the correct technical term.

  • CtrlC does not "stop" a job, it cancels or kills it. Technically it causes an interrupt signal to be sent to the program telling it to abort what it is doing and exit immediately. Some programs will hear this signal and do some emergency clean up work on themselves before exiting. Others will not respond to the signal and are subsequently just aborted.

  • CtrlZ, on the other hand, "stops" a job. Again this is done with a signal, but this time it is a 'stop' instead of an 'interrupt' signal. This effectively puts it on hold and returns control to the shell, but does not actually kill the job. If you would like such a job to keep running, you can then issue a bg command to send the last stopped job to the background. It will then continue running as a background job as if you had run it with & in the first place. You may also use fg to resume the last stopped job in the foreground (allowing it to continue where it left off, and allowing you to interact with it again).