How to kill zombie process linux
How to kill zombie process linux
How to Find and Kill a Zombie Process on Linux
Such “defunct” processes are seen to occur mainly for the child processes. The parent process reads the exit status of its child process. It’s done via the wait() system call. Once it’s done, the zombie process gets eliminated. This is called reaping the zombie process.
To have a better understanding of the zombie process formation and elimination, follow the diagram given below.
How Zombie Process State Works
Before going into the zombie process state, let’s briefly overview the process states in Linux.
Linux keeps track of vulnerabilities and the applications running on your computer by maintaining a process table. In the Linux kernel memory, a process table is comprised of a list of structures. Each process of the process table has its entry in the list that is occupied by some information about the process. They hold a pointer to the PCB (process control block), a process ID, and some other data.
The Linux PCB contains process state, process number, process counter, registers, open file list, CPU scheduling information, memory management information, and input-output status information. There can be 5 process states, and those are R, S, D, T, and Z. R is a running process, S denotes a sleeping process, D denotes an uninterruptable sleep state, T is a terminated or stopped process, and Z is a zombie process.
So, how does a zombie process state work? In the zombie process state, the parent calls one wait() function during the child process creation. Then it waits for the state change to take place in the child process. In case the state change where the child process has stopped, its exit status code is read.
After that, the child process’s PCB is destroyed, and the entry is cleared. It happens very quickly, and the zombie process doesn’t last long.
What Causes a Zombie Process to Form in Linux
So, what’s the cause behind the formation of a zombie process in Linux? A not-so-perfect parent process can’t call the wait() function at the time of child process creation. So, in the child process, nothing watches for state changes; as a result, the SIGCHLD signal gets ignored. A second reason could be, another application affected the parent process execution due to malicious intent or simply poor coding.
By any means, if the parent process is unable to view child process state changes, the system housekeeping doesn’t happen. Then PCB and the entry are not cleared while the child process ends. As an effect of this, the zombie state is not cleared from the PCB.
Facts about Zombie Processes
Some interesting facts about zombie processes include:
All the system memory and other resources allocated to a zombie process are deallocated while it ends using the exit() system call.
But its entry in the table remains available.
If the parent process isn’t running, the zombie process’s presence signifies an operating system bug. This might not cause a serious issue if there are some zombie processes. But under heavier loads, the presence of zombie processes can create a shortage of process table entries. We’ll explore the danger of zombie processes in this article’s next section.
The parent process reads the exit status of a zombie process using the wait() function. Then the zombie process is eliminated from the system. After its removal, the process table entry and the process ID can be reused.
If the wait() is not used by the parent, the zombie remains in the process table. It creates a resource leak.
Sending SIGCHLD signal to a parent process with the kill command, you can remove a zombie process from the system.
If the zombie process remains in the process table even after sending the SIGCHLD signal, the parent process must be terminated if acceptable.
Are Zombie Processes Dangerous?
Zombie processes use a little bit of memory, but usually, they don’t pose a danger. The process table entry is small, but you can’t use its process ID until the zombie process is released. On a 64-bit OS, it’s not going to create a problem because the PCB is larger than the entry of the process table.
A huge number of zombie processes could affect the free memory available for other processes. If you face too many zombies, there’s some serious issue with the operating system bug or the parent application. In that case, the remaining process IDs get monopolized by the zombies. If there remain no process IDs, other processes are unable to run.
How to Find and Kill a Zombie Process
To kill the zombie process, at first, find it out. Use the code given below to identify zombie processes.
Z used in the STAT column and/or [defunct] used in the last output column would identify a zombie process.
Actually, you can’t kill zombie processes as they are already dead. All you can do is, notifying its parent process so that it can again try to read the status of the child process, which has now become a zombie process, and eventually, the dead process gets cleaned from the process table. Use the following command to find out the parent process ID.
Once you get the parent process ID of the zombie, send a SIGCHLD to the parent process.
In case this doesn’t work in removing the zombie process from the process table, you need to restart or kill its parent process. To kill the zombie’s parent process, use the following code.
Side Note: Once you kill a parent process, its child processes get affected. So it’s recommended to go through a quick double-check. It’ll help you to be safe.
If there’s a huge surge in the existing zombie processes, resulting in or heading towards a system outage, you have to do a system reboot. Alternatively, suppose a small number of zombie processes are not using much memory or system resources. In that case, it’s wise to reboot or kill its parent process in the upcoming scheduled system maintenance.
Conclusion
In this article, you have learned how to find and kill a zombie process on Linux. Now you know what a zombie process is, how to identify a zombie process on Linux and get it removed from the process table. We have also explored the process states in brief and how a zombie process state works.
So the conclusion is, zombies are not dangerous as far as they have been cleaned and maintained in a timely fashion. Hope you find this write-up useful, and it provides answers to your questions related to the zombie processes on Linux.
About the author
Suparna Ganguly
I’m an Engineer by degree and a Writer by choice. I like to learn and explore a good range of topics including Linux, programming, open-source, games, and computers. My content write-ups in LinuxHint can be your source of knowledge, guide, and values.
How to kill a zombie process on Linux
Happy Halloween Open SOURCE-rers!
Here’s a tale as old as epoch time. Since there has been C and Unix, and (later on) Linux, we’ve had zombies. Specifically, there are processes that get marked as a zombie process. Misunderstood by some, ignored by others, and immune to the efforts of so many of us trying to kill these processes without much success. Why is that?
What is a process in Linux?
It all begins when a program in Linux gets executed, and when it does, its running instance is called a process. You can see all processes on your Linux environment with the ps command.
Sometimes a process starts another process, making the first process the parent of the second. The pstree command is a great tool that allows you to see the processes’ «genealogy» on your system.
Every process gets assigned a number in the system. Process ID number 1 gets assigned to the very first process executed during the boot process, and every subsequent process after PID 1 is a descendant of it. The PID 1 process is the init, which on most newer versions of Linux is just a symbolic link to the systemd program.
More Linux resources
Ending a process with the kill command
You can terminate processes in a Linux system with the kill command. Despite the name, the kill command and a set of others such as pkill and killall got written/designed to send SIGNALS to one or more processes. When not specified, the default SIGNAL it sends is the SIGTERM signal to terminate the process.
When a parent process dies or gets killed, and its child process doesn’t follow its parent’s demise, we call that process an orphan process.
How to kill a zombie process
Zombie processes, on the other hand, cannot be killed! Why might you ask? Well, because they are already dead!
Every child process, when terminated, becomes a zombie process and then removed by the parent. When the process exits its existence and releases the resources it had used, its name is still on the OS process table. It is then the parent’s process job to remove its name from the process table. When that fails, we have the zombie process, which isn’t really a process anymore, but just an entry on the process table of the OS.
So, to kill a zombie process, as in to remove its name from the process list (the process table), you have to kill its parent. For instance, if PID 5878 is a zombie process, and its parent is PID 4809, then to kill the zombie (5878) you end the parent (4809):
My final word of warning about zombies. Be very careful when killing parent processes. If the parent of a process is PID 1 and you kill that, you’ll reboot yourself!
And that will be an even scarier story to tell!
Плохо написанные или плохо работающие программы могут оставлять зомби-процессы, скрывающиеся внутри вашего Linux-компьютера. Узнайте, как создаются зомби и как их наконец упокоить.
Как состояния процесса работают в Linux
Linux, конечно же, должен отслеживать все приложения и демоны, работающие на вашем компьютере. Один из способов сделать это — поддерживать таблицу процессов. Это список структур в памяти ядра. Каждый процесс имеет запись в этом списке, которая содержит некоторую информацию о нем.
В каждой из структур таблицы процессов нет ничего особенного. Они держат идентификатор процесса, несколько других элементов данных и указатель на блок управления процессом (PCB) для этого процесса.
Это печатная плата, которая содержит множество деталей, которые Linux необходимо найти или настроить для каждого процесса. Плата также обновляется по мере создания процесса с учетом времени обработки и, наконец, уничтожается.
«Состояние процесса» может быть любым из следующих:
В состоянии Zombie родительский процесс вызывает один из wait() семейства функций при создании дочернего процесса. Затем он ждет изменения состояния в дочернем процессе. Был ли дочерний процесс остановлен, продолжен или уничтожен сигналом? Завершилось ли оно естественным завершением своего кода?
Если изменение состояния означает, что дочерний процесс остановлен, считывается его код выхода. Затем дочерняя печатная плата уничтожается, а его запись в таблице процессов удаляется. В идеале все это происходит в мгновение ока, а процессы в состоянии зомби существуют не очень долго.
Что вызывает зомби-процессы в Linux?
Плохо написанный родительский процесс может не вызывать wait() функция при создании дочернего процесса. Это означает, что ничто не отслеживает изменения состояния в дочернем процессе, и SIGCHLD сигнал будет проигнорирован. Или, возможно, другое приложение влияет на выполнение родительского процесса из-за плохого программирования или злого умысла.
Однако, если родительский процесс не следит за изменениями состояния в дочернем процессе, надлежащего обслуживания системы не произойдет. Плата и запись в таблице процессов не будут удалены при завершении дочернего процесса. Это приводит к тому, что состояние зомби никогда не удаляется с печатной платы.
Зомби используют немного памяти, но обычно не представляют проблемы. Запись в таблице процессов небольшая, но, пока она не будет выпущена, идентификатор процесса нельзя использовать повторно. В 64-битной операционной системе это вряд ли вызовет какие-либо проблемы, потому что размер платы намного больше, чем запись в таблице процессов.
Возможно, огромное количество зомби может повлиять на объем памяти, свободной для других процессов. Однако, если у вас так много зомби, у вас серьезная проблема с родительским приложением или ошибка операционной системы.
Как удалить зомби-процессы
Поэтому мы вводим следующую команду для поиска информации о процессе 7641, но она будет сообщать только идентификатор родительского процесса:
Нам сказали, что идентификатор родительского процесса — 7636. Теперь мы можем ссылаться на него, используя ps еще раз.
Зомби не страшны…
… Если они не в огромной орде. О некоторых не стоит беспокоиться, и простая перезагрузка уничтожит их.
Однако, если вы заметили, что приложение или процесс всегда порождают зомби, вам следует изучить это. Скорее всего, это просто небрежно написанная программа, и в этом случае, возможно, есть обновленная версия, которая должным образом очищается после своих дочерних процессов.
How to Find and Kill Zombie Process in Linux
Brief: This is a quick tip on finding zombie processes in Linux and then killing them. You also learn a thing or two about processes and zombie processes.
Before you learn about Zombie process, let me recall what is a process in Linux.
In a few words, a process is a running instance of a program in performance. It can be foreground (interactive process) or background (not interactive or automatic process). It can be a parent (creator of other processes during run-time) or child (process created by others) process.
In Linux, except for the first init (or systemd) process with PID 0, every other process has a parent process. Processes also have their own child processes.
Don’t believe me? Use the pstree command in terminal to look at the process tree to see the ‘family tree’ of your system’s processes.
What is a Zombie process in Linux?
When a child process dies, the parent process is informed so that it can do some clean up like freeing up memory etc. However, child process goes into zombie state if the parent process is not aware of its death. For the parent, the child still exists but the child process is actually dead. This is how zombie processes (also known as defunct processes) are created and stay in the system.
Here’s an excellent funny take on the zombie process by Turnoff.us:
» data-medium-file=»https://itsfoss.com/wp-content/uploads/2021/10/zombies-turnoff-300×175.webp» data-large-file=»https://itsfoss.com/wp-content/uploads/2021/10/zombies-turnoff-800×467.webp» width=»800″ height=»467″ src=»https://itsfoss.com/wp-content/uploads/2021/10/zombies-turnoff-800×467.webp» alt=»zombies turnoff» data-lazy-srcset=»https://itsfoss.com/wp-content/uploads/2021/10/zombies-turnoff-800×467.webp 800w, https://itsfoss.com/wp-content/uploads/2021/10/zombies-turnoff-300×175.webp 300w, https://itsfoss.com/wp-content/uploads/2021/10/zombies-turnoff-768×448.webp 768w, https://itsfoss.com/wp-content/uploads/2021/10/zombies-turnoff.webp 1200w» data-lazy-sizes=»(max-width: 800px) 100vw, 800px» data-lazy-src=»https://itsfoss.com/wp-content/uploads/2021/10/zombies-turnoff-800×467.webp?is-pending-load=1″ srcset=»data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7″> Image credit: Turnoff.us
Do you really need to worry about Zombie processes?
Here is important to say that zombie processes are not as dangerous as its name can sound.
The problem may arise if your system has limited RAM or if there are too many zombie processes eating up RAM. Also, most Linux processes can have maximum PID set to 32768. If there are no available IDs for other productive tasks, your system may crash.
This rarely happens, but it’s a possibility, specially if a poorly coded program starts inducing numerous zombie processes.
In such case, it would be a good idea to find and kill zombie process.
How to find zombie processes?
A process in Linux can have one of the following states:
But where can you see the processes and their respective status? One easy way is to use the terminal and the top command.
» data-medium-file=»https://itsfoss.com/wp-content/uploads/2021/10/top-command-view-300×178.png» data-large-file=»https://itsfoss.com/wp-content/uploads/2021/10/top-command-view-800×474.png» width=»800″ height=»474″ src=»https://itsfoss.com/wp-content/uploads/2021/10/top-command-view-800×474.png» alt=»top command view» data-lazy-srcset=»https://itsfoss.com/wp-content/uploads/2021/10/top-command-view-800×474.png 800w, https://itsfoss.com/wp-content/uploads/2021/10/top-command-view-300×178.png 300w, https://itsfoss.com/wp-content/uploads/2021/10/top-command-view-768×455.png 768w, https://itsfoss.com/wp-content/uploads/2021/10/top-command-view.png 976w» data-lazy-sizes=»(max-width: 800px) 100vw, 800px» data-lazy-src=»https://itsfoss.com/wp-content/uploads/2021/10/top-command-view-800×474.png?is-pending-load=1″ srcset=»data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7″> Top command show processes and their status
As you can see in the screenshot above, there are 250 total tasks (or processes), 1 is running, 248 processes are sleeping and 1 is in zombie state.
Now, the question arises, how to kill the zombie process?
How to find and kill a zombie process? Can a zombie process be killed?
A zombie process is already dead. How do you kill an already dead process?
In the zombie movies, you shoot the zombies in the head or burn it. That’s not an option here. You can burn your system for killing the zombie process but that’s not a feasible solution 😉
Some people suggests sending SIGCHLD signal to the parent process. But it is more likely to be ignored. The other option to kill the zombie process is to kill its parent process. That sounds brutal but that’s the only sure shot way of killing zombie processes.
So, first, let’s list the zombie processes to know their ID. It can be achieved by using the ps command like this in the terminal.
The 8th column in the output of the ps aux command displays the state of a process. You are asking to print all the matching lines where the state of a process starts with Z or z.
Once you have identified its process ID, let’s get its parent’s process ID.
Alternatively, you can combine the above two commands in the following fashion where it directly provides the PID of the zombie process and the PID of its parent process.
Here you get the parent process ID, so finally kill the process by typing the command line with its respective ID process obtained before.
killing parent process
» data-medium-file=»https://itsfoss.com/wp-content/uploads/2021/10/killing-parent-process-300×68.png» data-large-file=»https://itsfoss.com/wp-content/uploads/2021/10/killing-parent-process-800×180.png» width=»800″ height=»180″ src=»https://itsfoss.com/wp-content/uploads/2021/10/killing-parent-process-800×180.png» alt=»killing parent process» data-lazy-srcset=»https://itsfoss.com/wp-content/uploads/2021/10/killing-parent-process-800×180.png 800w, https://itsfoss.com/wp-content/uploads/2021/10/killing-parent-process-300×68.png 300w, https://itsfoss.com/wp-content/uploads/2021/10/killing-parent-process-768×173.png 768w, https://itsfoss.com/wp-content/uploads/2021/10/killing-parent-process.png 976w» data-lazy-sizes=»(max-width: 800px) 100vw, 800px» data-lazy-src=»https://itsfoss.com/wp-content/uploads/2021/10/killing-parent-process-800×180.png?is-pending-load=1″ srcset=»data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7″> Killing parent process
You can verify if the zombie process is killed or not by running the ps command again or even the top command.
Congrats! Now you know how to eliminate zombie processes.
With inputs from Abhishek Prakash.
My name is Marco Antonio Carmona, I’m a physics and data science student, a great and passionate reader, and randomly, my favorite hobby is writing about what I learn day by day.
Search
How To Kill Zombie Processes on Linux
Killing Zombies!
Also known as “defunct” or “dead” process – In simple words, a Zombie process is one that is dead but is present in the system’s process table. Ideally, it should have been cleaned from the process table once it completed its job/execution but for some reason, its parent process didn’t clean it up properly after the execution.
In a just (Linux) world, a process notifies its parent process once it has completed its execution and has exited. Then the parent process would remove the process from process table. At this step, if the parent process is unable to read the process status from its child (the completed process), it won’t be able to remove the process from memory and thus the process being dead still continues to exist in the process table – hence, called a Zombie!
In order to kill a Zombie process, we need to identify it first. The following command can be used to find zombie processes:
$ ps aux | egrep «Z|defunct»
Z in the STAT column and/or [defunct] in the last (COMMAND) column of the output would identify a Zombie process.
Now practically you can’t kill a Zombie because it is already dead! What can be done is to notify its parent process explicitly so that it can retry to read the child (dead) process’s status and eventually clean them from the process table. This can be done by sending a SIGCHLD signal to the parent process. The following command can be used to find the parent process ID (PID):
Once you have the Zombie’s parent process ID, you can use the following command to send a SIGCHLD signal to the parent process:
However, if this does not help clearing out the Zombie process, you will have to kill or restart its parent process OR in case of a huge surge in Zombie processes causing or heading towards system outage, you will have no choice but to go for a system reboot. The following command can be used to kill its parent process:
Note that killing a parent process will affect all of its child processes, so a quick double check will be helpful to be safe. Alternatively, if few lying zombie processes are not consuming much CPU/Memory, it’s better to kill the parent process or reboot the system in the next scheduled system maintenance.
Nawaz is a Linux CLI enthusiast and likes sharing tips and tutorials related to command-line and shell scripting. He can be reached via LinkedIn.