Skip to content

Instantly share code, notes, and snippets.

@rwcitek
Last active January 18, 2024 00:51
Show Gist options
  • Save rwcitek/96ac443d42ff0579d79b12e6f504e219 to your computer and use it in GitHub Desktop.
Save rwcitek/96ac443d42ff0579d79b12e6f504e219 to your computer and use it in GitHub Desktop.
process kill signals in Docker

Proccess and kill signals

These are best practiced in a virtual environment. Docker will do.

$ docker run --rm -it ubuntu /bin/bash

Here we create a background process, capture its process id ( PID ), and then kill it.

# sleep 100 &

# pid=$( jobs -p )

# echo pid=${pid}
pid=10

# ps -fux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.4  0.1   4624  3756 pts/0    Ss   23:23   0:00 /bin/bash
root        10  0.0  0.0   2788  1024 pts/0    S    23:23   0:00 sleep 100
root        12  0.0  0.0   7060  1576 pts/0    R+   23:24   0:00 ps -fu

# kill ${pid}

# ps -fux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.3  0.1   4624  3760 pts/0    Ss   23:23   0:00 /bin/bash
root        13  0.0  0.0   7060  1576 pts/0    R+   23:24   0:00 ps -fu

Here we do the same with one change: we "trap" the TERM signal and ignore it.

# trap '' TERM

# sleep 100 &

# pid=$( jobs -p )

# echo pid=${pid}
pid=15

# ps -fux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.1  0.1   4624  3760 pts/0    Ss   23:23   0:00 /bin/bash
root        15  0.1  0.0   2788  1028 pts/0    S    23:24   0:00 sleep 100
root        17  0.0  0.0   7060  1580 pts/0    R+   23:25   0:00 ps -fu

# kill ${pid}

# ps -fux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.1  0.1   4624  3760 pts/0    Ss   23:23   0:00 /bin/bash
root        15  0.1  0.0   2788  1028 pts/0    S    23:24   0:00 sleep 100
root        18  0.0  0.0   7060  1576 pts/0    R+   23:25   0:00 ps -fu

Notice that this time the process keeps running. In order to kill the process we have to send it a different signal, e.g. HUP. By default, kill sends a TERM signal ( aka SIGTERM or 15 ). See man kill for more details.

# kill -s HUP ${pid}

# ps -fux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.1  0.1   4624  3760 pts/0    Ss   23:23   0:00 /bin/bash
root        19  0.0  0.0   7060  1576 pts/0    R+   23:25   0:00 ps -fu

# exit
# The same ( mostly ) but in script form
<< 'eof' docker run --rm -i ubuntu /bin/bash 2> /dev/null
# Create a background process then kill it
sleep 100 &
echo
pid=$( jobs -p )
echo pid=${pid}
ps -fux
kill ${pid}
echo
ps -fux
# Add the trap and repeat
trap '' TERM
sleep 100 &
echo
pid=$( jobs -p )
echo pid=${pid}
ps -fux
kill ${pid}
echo
ps -fux
# Kill with another signal
kill -s HUP ${pid}
sleep 1
echo
ps -fux
eof
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment