Выполняю установку, настройку, сопровождение серверов. Для уточнения деталей используйте форму обратной связи
Что же это такое?
Это дочерний процесс в Unix-системе, завершивший своё выполнение, но ещё присутствующий в списке процессов операционной системы, чтобы дать родительскому процессу считать код завершения. Процесс при завершении освобождает все свои ресурсы (за исключением PID — идентификатора процесса) и становится «зомби» — пустой записью в таблице процессов, хранящей код завершения для родительского процесса.
Система уведомляет родительский процесс о завершении дочернего с помощью сигнала SIGCHLD. Предполагается, что после получения SIGCHLD он считает код возврата с помощью системного вызова wait(), после чего запись зомби будет удалена из списка процессов. Если родительский процесс игнорирует SIGCHLD (а он игнорируется по умолчанию), то зомби остаются до его завершения.
А теперь возникают вопросы: как же всё-таки их найти и убить? Найти их очень просто. Вот несколько вариантов:
1)
top | grep zombie
225 processes: 1 running, 222 sleeping, 2 zombie
2)
ps aux | grep -w Z
root 3994 0,0 0,0 0 0 ?? Z 13июн11 16:23,02
root 3995 0,0 0,0 0 0 ?? Z 13июн11 13:43,28
Что касается «убийства», то их нельзя просто так убить. Самый правильный вариант — найти родительский процесс и перезапустить его. Некоторые могут посоветовать и перегрузиться, но это не выход.
Находим родительский процесс:
ps ajx | grep -w Z
root 3994 3992 3992 3992 0 Z ?? 16:23,02
root 3995 3992 3992 3992 0 Z ?? 13:43,28
3-я колонка как раз и показывает pid родительского процесса. Смотрим, что это за процесс:
ps auxww | grep 3992
root 3992 0,0 0,2 30664 9872 ?? Ss 13июн11 0:08,21 [exilog_agent] (perl5.12.3)
Собственно мы нашли виновника. Это exilog_agent. А дальше — либо просто прибиваем родительский процесс либо перезапускаем его:
#kill -9 3992
#top | grep zombie
#
Зомби процессы Linux
Каждая программа, которая выполняется в Linux, — это системный процесс, у которого есть свой идентификатор. Каждый процесс может запускать дочерние процессы с помощью функции fork. Такие процессы остаются под контролем родительского процесса и не могут быть завершены без его ведома. Если один из дочерних процессов всё же завершился, а его родительский процесс не смог получить об этом информацию, то такой дочерний процесс становится зомби.
Зомби процессы Linux не выполняются и убить их нельзя, даже с помощью sigkill, они продолжают висеть в памяти, пока не будет завершён их родительский процесс.
Посмотреть такие процессы можно с помощью утилиты ps, здесь они отмечаются как defunct:
ps aux | grep defunct
Если вы попытаетесь убить такой процесс с помощью сигнала KILL, то ничего не выйдет:
Чтобы его завершить, нужно найти «родителя» этого процесса. Для этого используйте команду:
ps -xal | grep defunct
Здесь идентификатор родительского процесса находится в четвёртой колонке (PPID). Теперь мы можем послать ему сигнал завершения, и такого процесса в системе больше не будет:
Для большего удобства вы можете использовать утилиты top или htop, но принцип их действия будет аналогичным, поэтому я не буду здесь его рассматривать. Теперь вы знаете, что делать, если в вашей системе появились зомби процессы Linux.
How to kill zombie process
I launched my program in the foreground (a daemon program), and then I killed it with kill -9 , but I get a zombie remaining and I m not able to kill it with kill -9 . How to kill a zombie process?
If the zombie is a dead process (already killed), how I remove it from the output of ps aux ?
5 Answers 5
A zombie is already dead, so you cannot kill it. To clean up a zombie, it must be waited on by its parent, so killing the parent should work to eliminate the zombie. (After the parent dies, the zombie will be inherited by pid 1, which will wait on it and clear its entry in the process table.) If your daemon is spawning children that become zombies, you have a bug. Your daemon should notice when its children die and wait on them to determine their exit status.
An example of how you might send a signal to every process that is the parent of a zombie (note that this is extremely crude and might kill processes that you do not intend. I do not recommend using this sort of sledge hammer):
/status – Daniel Andrei Mincă Sep 4 ’18 at 11:22
What is Zombie Process and Kill Zombie Process in Linux
In Linux OS, a zombie process or a defunct process is a finished (dead) process, but it has still occupied an entry in the process table. Normally, a child process that has completed its execution will send a SIGCHLD signal to the parent process which has created it. Then the parent process will send a wait system call through which it can read the child’s exit status. After receiving the wait system call, the child’s entry will get removed from the process table. In some cases, the parent may ignore the SIGCHLD signal which causes the finished process to still exist in the process table which makes it a zombie process. Sometimes, this is desirable for the parent process to ensure that it doesn’t allocate the same PID to another child.
When a process becomes dead, it will free up the memory and other resources allocated to it. So, a zombie process will not be using any resources at all, other than an entry in the process table. The problem may start only when a large number of zombie processes exist and system run out of PIDs. In this tutorial, we will see how a zombie process can be detected and terminated.
If the system generates large number of zombie processes, then it should be an application bug which needs to be checked for available patches to correct the problem.
Detecting zombie processes
You can find the zombie processes using Linux ps command. This command will list all processes with a “STAT” column. If the process is a zombie process, the STAT column will have the character “Z”. Using any of the following commands, you can find the zombie processes.
Handling zombie process
As zombie processes don’t consume any resources, you can ignore it if the server runs smoothly. But in the case of server facing heavy load, large number of zombie processes may become an issue. So, in order to get rid of the zombie processes we can consider any of the following methods.
1) Sending SIGCHLD signal to the parent process of zombie
Upon receiving SIGCHLD command, the parent process must send a wait system call which will remove the zombie process. This can be accomplished by executing the following command.
PPID is the PID of the parent process which invoked the zombie child process. You can execute the following command to find the PPID of a zombie process.
If the parent process explicitly ignores the SIGCHLD signal, then you should consider killing the parent process (step 2).
2) Killing the parent process
If the zombie processes are not able to get removed, you should kill the parent process or restart the service to get rid of the zombies. When a parent gets killed, all child processes will become the child process of ‘init process (PID 1)’. Init process will wait for the children to die by sending a wait signal which in turn removes the zombie processes. The parent process can be killed using the ‘kill’ command:
Please provide your thoughts and suggestions on this article. Thanks for reading.
How to Kill Zombie Processes in Ubuntu 18.04 LTS
A zombie or a defunct process in Linux is a process that has been completed, but its entry still remains in the process table due to lack of correspondence between the parent and child processes. Usually, a parent process keeps a check on the status of its child processes through the wait() function. When the child process has finished, the wait function signals the parent to completely exit the process from the memory. However, if the parent fails to call the wait function for any of its children, the child process remains alive in the system as a dead or zombie process. These zombie processes might accumulate, in large numbers, on your system and affect its performance. In that case, you might have to kill these zombies manually through the ways and commands described in this tutorial.
Viewing Zombie Processes
You can have a check on your system performance by viewing the various processes running on your system, including the efficiency altering zombie processes. Ubuntu allows you to view these processes in the following manner:
- Through the Graphical User Interface
- Through the Command Line
Through the GUI
In order to graphically view any zombie processes running on your system, open the System Monitor utility through your Ubuntu Dash. In the following screenshot of my System Monitor, you can view that there are two zombies running on my system. It is also possible that the number of zombie processes on your system might be less or more than the ones running on mine.
Through the Command Line
The top command displays a detailed view of the processes running on your system along with the memory and CPU resources they are using. It also gives you information about any zombie processes running on your system. Open the Terminal by pressing Ctrl+Alt+T and then type top. I got the following output after running this command.
You can see in the second line that there is 1 zombie process running on my system.
If you want further details about the zombie process, use the following command:
This command will give you the state, parentID, the process ID, the program that is running the zombie process(a dummy program by the name ‘zombie’ on my system). The defunct flag tells you that this is a dead, zombie process.
Killing a Zombie-Process
First, let us understand how zombie processes are a threat to our system’s performance. It is important to learn that zombies are dead and mostly completed processes that do not take memory or CPU resources. However, each of these processes has a unique process ID assigned to them which comes from a limited pool of PIDs reserved for your processor. If a large number of zombies gather, they will eat up most part of the PID pool and the new processes will not be able to launch due to lack of a process ID. Advertisement
A small number of defunct programs occupying your system is not a big threat but that means that their parent programs have not been able to call them off due to a bug or a missing wait() function.
When a parent process has not been able to call the wait() function automatically, we need to manually signal the parent process to run the wait function on all its children so the ones with a complete state can be called back. We can do this by running the SIGCHLD command. When that doesn’t work, we can manually kill the parent process so that all its zombie children are also killed, freeing the process IDs for the new processes.
You can kill the zombie processes through the following ways:
- Through the Graphical User Interface
- Through the Command Line
Through the GUI
You can kill a zombie process graphically through the System Monitor Utility as follows:
- Open the System Monitor utility through Ubuntu Dash.
- Search for the term Zombie through the Search button.
- Select the zombie process, right-click and then select Kill from the menu.
The zombie process will be killed from your system.
Through the Command Line
After you know that there any zombie processes running on your system through the top command, view the details of the processes.
The usual way is to use the following command that signals the zombie’s parent process to kill the command.
This command may not work in a few cases as not all parent processes are programmed properly in order check upon the child processes. In that case, you can kill the parent process through the following command:
When you have killed all the zombie processes through this way and run the top command, you will be able to see that there are no zombie processes running on your system anymore:
After working along with this tutorial, you can optimize your operating system by looking for any zombie processes on your system and killing them manually through the command line or the graphical user interface. This act will free up process IDs for the new processes that you want to run on your system.
Karim Buzdar
About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn