Linux – Why can’t I kill this process on Linux

bashlinuxprocess

Problem

I would like to kill a process called raspivid (program which records videos using a Raspberry Pi Camera) but I cannot…

This is how I call it:

#!/bin/bash

#Start recording...
raspivid -w 800 -h 600 -t 15000 -o $1 -v -n -rot 270 >> /home/pi/log/camera_output.txt 2>&1 &

#Waiting the video to be complete
sleep 16

#Killing child process
sudo kill -9 $!

#Killing parent process
sudo kill -9 $$

If I search for this process, it is still there:

pi@raspberrypi ~ $ ps -ef | grep raspivid
root      7238     7234  0 21:53 ?        00:00:00 [raspivid]
pi       17096 14925  0 22:05 pts/0    00:00:00 grep --color=auto raspivid

If I try to kill it, it doesn't die. Instead it changes the parent PID to 1:

pi@raspberrypi ~ $ sudo killall raspivid
pi@raspberrypi ~ $ ps -ef | grep raspivid
root      7238     1  0 21:53 ?        00:00:00 [raspivid]
pi       17196 14925  0 22:05 pts/0    00:00:00 grep --color=auto raspivid
pi@raspberrypi ~ $ sudo killall raspivid

Observations:

  1. The call works fine for a while (2 hours or something) then it starts
    hanging.
  2. Only a physical power off solves the issue. I cannot reboot via
    terminal (it hangs too)

My questions:

  1. Why does Linux assign the parent PID to 1?
  2. Why the process cannot get killed? (I also tried sudo kill -9 7238)

Best Answer

Problem

Your script is probably creating zombies because of your kill -9 commands; as suggested from jjlin answer too is never a good practice to kill abruptly some process without being forced to.

From man bash we can read:

Processes marked < defunct > are dead processes (so-called "zombies") that remain because their parent has not destroyed them properly. These processes will be destroyed by init(8) if the parent process exits.

Answer #1: The process init has the PID 1 and for this Linux assigns them the parent with PID 1 (because it assign them to init).

Answer #2: They cannot be killed simply because they are just dead... if their parent is init probably is enough to wait some time.

To remove zombies from a system, the SIGCHLD signal can be sent to the parent manually, using the kill command. If the parent process still refuses to reap the zombie, the next step would be to remove the parent process. When a process loses its parent, init becomes its new parent. Init periodically executes the wait system call to reap any zombies with init as parent. [1]

Just in case this idea arises one day or another: to #kill -9 init process with root privilege is the software equivalent to physically unplug the computer from the electricity grid. [:-)]

However zombie processes can be identified in the output of ps command by the presence of a "Z" in the STAT column. You can use the following line to easily identify them

ps -aux | grep Z

Some references about Linux zombies world:

Related Question