1

I was trying to demonstrate job control to a friend, when I ran into an unexpected behaviour. For certain commands, kill works with the job number, but not with the process ID.

An example of the bahaviour I expected:

user@host:~$ sleep 1h &
[1] 4518
user@host:~$ sleep 2h &
[2] 4519
user@host:~$ kill %2
[2]+ Terminated   sleep 2h
user@host:~$ kill 4518
[1]+ Terminated   sleep 1h

In both cases, sleep is terminated. One by job number, and one by PID. Now I tried this originally with the command cat, and it didn't work out as expected:

user@host:~$ cat &
[1] 4521
user@host:~$ cat &
[2] 4522

[1]+ Stopped   cat
user@host:~$ kill %2
[2]+ Terminated   cat
user@host:~$ kill 4521
user@host:~$ jobs
[1]+ Stopped   cat
user@host:~$ kill 4521
user@host:~$ jobs
[1]+ Stopped   cat
user@host:~$ kill %1
[1]+ Terminated   cat

So kill did not work on the PID of my process, but it worked with the job number. I don't think this should happen. Why is this the case?

I'm using Debian 9 with bash 4.4.12(1)-release.

EDIT: In the process of trying to solve this, I have become aware that the state of cat being "stopped" can make it unresponsive to the default signal SIGTERM. But if that is true, then the kill command should fail with both the process ID and the job number. Shouldn't it?

1 Answers1

3

What the kill builtin really does in these circumstances is not documented in the Bourne Again shell's manual, but it is documented in the Z shell and Korn shell manuals:

  • Korn shell:
    If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process will be sent a CONT (continue) signal if it is stopped.
  • Z shell:
    If the signal being sent is not KILL or CONT, then the job will be sent a CONT signal if it is stopped.

The Bourne Again shell manual should similarly read something like:

If the signal being sent is TERM or HUP and a targetted process is part of a job, then the job will be sent a CONT signal if it is stopped or job control is not available in the current terminal.

Because that is what it actually does.

JdeBP
  • 68,745