4

I have the following contrived script to illustrate my issue:

#!/bin/bash
set -eux
sudo sleep 120 &
spid=$!
sleep 1
sudo kill $spid
wait $!

This will print

$ ./test.sh 
+ spid=21931
+ sleep 1
+ sudo sleep 120
+ sudo kill 21931
+ wait 21931

and then hang on wait until the sleep 120 times out. However, when I run sudo kill 21931 from another terminal the sleep process is killed immediately. I expected the sudo kill $spid line in the script to also kill the sleep process immediately. Why doesn't this work and how do I make this work?

(Might be relevant: I see this behaviour bash 4.3.42 and dash 0.5.7 on Ubuntu 15.10.)

  • 1
    Just tried the same on an Ubuntu 14.04 machine (bash 4.3.11 / dash 0.5.7), and that gives me the behaviour I would expect: the sudo kill command from the script immediately kills the sleep 120 and the script ends. So, what could be different on Ubuntu 15.10 (or this machine)? – Steffan Karger Nov 11 '15 at 22:26
  • Just a comment: The spid variable will hold the PID of the sudo process, not the PID of sleep. – Kusalananda Jan 10 '18 at 11:06
0

The difference could be in the /etc/sudoers file. Maybe your user is allowed to run kill with nopasswd on one machine, but not on the other.

  • Interesting thought, but the only difference between the sudoers files was that in one I had Defaults !tty_tickets (the 'hanging' 15.10 machine). But after removing the line, the machine still hangs on wait. (There were no files in /etc/sudoers.d/ on both machines.) – Steffan Karger Nov 12 '15 at 20:14
0

I confirm this strange behaviour occurs as well on Ubuntu 17.10 bash 4.4.12(1)-release (x86_64-pc-linux-gnu).

I wasn't able to track down the real reason but it seems it has something to do with process signals. By default, kill sends out signal 15 – TERM which stands for a soft kill. However, if I use a hard 9 – KILL, the sleep process gets immediately killed.

#!/bin/bash
set -eux
sudo sleep 120 &
spid=$!
sleep 1
sudo kill -9 $spid
wait $!

prints out

$ ./test.sh 
+ spid=4342
+ sleep 1
+ sudo sleep 120
+ sudo kill -9 4342
./test.sh: line 6:  4342 Killed                  sudo sleep 120
+ wait 4342
  • It's the sudo that gets killed, not the sleep. sudo ought to relay the TERM signal to sleep though. – Kusalananda Jan 10 '18 at 11:09

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.