Find daemon process linux

How to Find the List of Daemon Processes and Zombie Processes in Linux

This article will guide you to understand the Zombie process and Daemons, and also help us to find the process which is running in the background.

What is Zombie Process?

When a process ends the execution, then it will have an exit status to report to its master process. Because of that little bit of information, the process will remain in the OS process table as a zombie process, which indicates that it is not to be scheduled for future, but this process cannot be completely removed or the process ID will not be used until the exit has been determined and no longer needed.

When a child completes the process, the master process will receive a SIGCHLD signal to indicate that one of its child process has finished the executing; the parent process will typically call the wait() system status at this point. That status will provide the parent with the child’s process exit status, and will cause the child process to be reaped, or removed from the process table.

Daemons?

Linux is a multi-tasking operating system. Each program running at any time is called a process. Every running command starts with at least one new process and there are many numbers of system processes that are running.

Each process is identified by a number called Process ID (PID). Similar to files, each process has its owner and group, and the group and owner permissions are useful to identify which files and devices are related to those processes. Most processes also have their own parent process that started them.

Example: The shell is a process, and any command executed in the shell is a process which belongs to the shell parent process. The exception is a special process called init(8) which is the first process to start at booting time and which has a PID(Process ID) of 1.

Some programs are to be run with continuous user input and disconnected from the terminal. For example, a web server responds to web requests, instead of user input. Mail servers are another examples of this type application. These type of programs are also known as daemons.

Foreground Processes

Every process has to start running in the foreground. It gets its input from the keyboard and sends its output to the screen after the process.

You can see this happen with the ls command. If I want to list all the files in my current directory, I can use the following command –

This will show all the files in the current directory.

The process runs in the foreground and will direct the output to my screen, and if a command wants any input it waits for input.

While a program is running in foreground and taking so much time, we cannot run any other commands from the command prompt which can be available until the program finishes its processing.

Читайте также:  Список всех сообщений windows

Background Processes

A background process runs without being the interaction of users. If the background process requires any input, it waits.

The advantage of running a process in the background is that you can run other commands, and you are not supposed to wait until it completes to start another process.

The simplest way to start the background process is to add an ampersand (&) at the end of the command we execute.

The above will write the output to files file with all the files and directories which will take more time. So, for instance, ampersand (&) at the end of the line will run in the background as a process and the cursor will come to prompt waiting for another command.

The first line contains information about the background process about how many background process are running and the job number or process ID. We need to know the PID to manipulate it between background and foreground.

If you press the Enter now, we can see the following output

The first line tells you that the find command background process finishes successfully and waits for the other command.

Listing Running Processes

This command will list the own processes by running, the ps (process status) command.

The commonly used flags for ps is the -f, -f will display full information, which provides more information as shown below.

Full Usage of PS Command

Stopping Processes

A process can be stopped in several ways. Often, from a command line, by sending a CTRL + C keystroke – will exit the command. This works when the process is running in the foreground.

If a process is running in background mode, then first you would need to get its Job ID using the ps command and after that you can use kill command to kill the process as follows –

Here kill command would terminate ssh root@192.168.1.89. If a process ignores a regular kill, we can use kill -9 followed by the process ID as follows.

How can we see if there are zombie processes running on a system.

Run “ps aux” and look for a Z in the STAT column.

In the above example, the process with process ID 12196 is having status z, use the kill command to kill that process

After this article you are able to understand what is zombie process and daemons and how to find out it and how to stop it, also how to make a process in background.

Источник

Linux find process by name

Procedure to find process by name on Linux

  1. Open the terminal application.
  2. Type the pidof command as follows to find PID for firefox process:
    pidof firefox
  3. Or use the ps command along with grep command as follows:
    ps aux | grep -i firefox
  4. To look up or signal processes based on name use:

pgrep firefox

Linux find process by name using pgrep command

pgrep command looks through the currently running processes and lists the process IDs which match the selection criteria to screen. All the criteria have to match. For example, will only list the processes called sshd AND owned by root user:
$ pgrep -u root sshd
Just look up pid for firefox process:
$ pgrep firefox

How to use ‘ps aux | grep command’

ps command shows information about a selection of the active processes:
$ ps aux
$ ps aux | grep -i ‘search-term’
$ ps aux | grep ‘firefox’
$ ps aux | grep ‘sshd’
OR use the following syntax instead of using egrep command in pipes:
$ ps -fC firefox
$ ps -fC chrome
The -C option asks ps command to select PIDs by command name.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard
Читайте также:  Windows 10 проводник не обновляет список файлов

Join Patreon

Using pidof command to grab PIDs for any named program on Linux

The pidof command finds the process id’s (pids) of the named programs such as sshd, firefox and more. For example:
$ pidof sshd
$ pidof firefox
Sample outputs:

A note about top/htop command

To display Linux processes use top command or htop command:
$ top
OR
$ htop

See also

Getting more help

Read the man pages for the following command using man command:
$ man pgrep
$ man pidof
$ man ps

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Что такое демоны (daemons) в Linux?

Обновл. 20 Июл 2021 |

В этой статье мы рассмотрим, что такое демоны (и их примеры) в Linux, а также версии происхождения термина «daemon».

Что такое демоны?

Демоны (англ. «daemons») — это работающие в фоновом режиме служебные программы (или процессы), целью которых является мониторинг определенных подсистем ОС и обеспечение её нормальной работы. Например, демон принтера контролирует возможности печати, демон сети контролирует и поддерживает сетевые коммуникации и т.д.

Демоны являются аналогом служб (services) в Windows: они выполняют определенные действия в заранее определенное время или в ответ на определенные события. Существует множество различных демонов, работающих в Linux, каждый из которых создан специально для наблюдения за своей собственной маленькой частью системы. Из-за того, что демоны выполняют основную часть своей работы в фоновом режиме и не находятся под прямым контролем пользователя, бывает трудно определить предназначение того или иного демона.

Так как демон — это процесс, который выполняется в фоновом режиме и обычно находится вне контроля пользователя, то у него нет управляющего терминала.

Процесс — это запущенная программа. В определенный момент времени процесс может либо выполняться, либо ожидать, либо быть «зомби».

В Linux существует три типа процессов:

Процессы переднего плана (или «интерактивные процессы») — это те процессы, которые запускаются пользователем в терминале.

Фоновые процессы (или «автоматические процессы») — это объединенные в список процессы, не подключенные к терминалу; они не ожидают пользовательского ввода данных.

Демоны (англ. «daemons») — это особый тип фоновых процессов, которые запускаются при старте системы и продолжают работать в виде системных служб; они не умирают.

Процессы переднего плана и фоновые процессы не являются демонами, хотя их можно запускать в фоновом режиме и выполнять некоторую работу по мониторингу системы. Для данных типов процессов необходимо участие пользователя, который бы их запускал. В то время как демонам для их запуска пользователь не требуется.

Когда завершается загрузка системы, процесс инициализации системы начинает создавать демоны с помощью метода fork(), устраняя необходимость в терминале (именно это подразумевается под «отсутствием управляющего терминала»).

Я не буду вдаваться в подробности работы метода fork(), отмечу лишь, что, хотя существуют и другие методы, традиционный способ создания дочернего процесса в Linux заключается в создании копии существующего процесса (посредством своеобразного «ответвления»), после чего выполняется системный вызов exec() для запуска другой программы.

Читайте также:  Примеры ключей продукта windows

Примечание: Термин «fork» не был взят с потолка. Он получил свое название от метода fork() из Стандартной библиотеки языка программирования Си. В языке Си данный метод предназначен для создания новых процессов.

Примеры демонов в Linux

Наиболее распространенный способ идентификации демона в Linux — это поиск процесса, имя которого заканчивается буквой d. Есть много способов увидеть работающих демонов. Их можно отследить в списках процессов через такие команды, как: ps , top , htop , а также pstree .

Команда pstree показывает процессы, запущенные в настоящее время в нашей системе, и отображает их в виде древовидной диаграммы. Откройте терминал и введите следующую команду:

Вывод команды pstree — это довольно хорошая иллюстрация того, что происходит с нашей системой. Перед нами появился список всех запущенных процессов, среди которых можно заметить и несколько демонов: cupsd, dbus-daemon, kdekonnectd, packagekitd и некоторые другие.

Вот несколько «популярных» примеров демонов, которые могут работать в вашей системе:

systemd — это системный демон, который (подобно процессу init) является родителем (прямым или косвенным) всех других процессов, и имеет PID=1.

rsyslogd — используется для регистрации системных сообщений. Это более новая версия syslogd, имеющая несколько дополнительных функций.

udisksd — обрабатывает такие операции, как: запрос, монтирование, размонтирование, форматирование или отсоединение устройств хранения данных (жесткие диски, USB-флеш-накопители и пр.).

logind — крошечный демон, который различными способами управляет входами пользователей в систему.

sshd — демон, отвечающий за управление службой SSH. Используется практически на любом сервере, который принимает SSH-соединения.

ftpd — управляет службой FTP. Протокол FTP (сокр. от англ. «File Transfer Protocol») является широко используемым протоколом для передачи файлов между компьютерами, где один компьютер действует как клиент, другой — как сервер.

crond — демон планировщика заданий, зависящих от времени. С его помощью можно выполнять обновление программного обеспечения, проверку системы и пр.

Версии происхождения термина «daemon»

Есть несколько версий происхождения термина «daemon»:

Научная версия: Использование термина «daemon» в вычислительной технике произошло в 1963 году. Project MAC (сокр. от англ. «Project on Mathematics and Computation») — это проект по математике и вычислениям, созданный в Массачусетском технологическом институте. Именно здесь термин «daemon» вошел в обиход для обозначения любого системного процесса, отслеживающего другие задачи и выполняющего предопределенные действия в зависимости от их поведения. Процессы были названы термином «daemons» в честь демона Максвелла.

Примечание: Демон Максвелла — это результат мысленного эксперимента. В 1867 году Джеймс Клерк Максвелл представил себе разумное и изобретательное существо, способное наблюдать и направлять движение отдельных молекул в заданном направлении. Цель мысленного эксперимента состояла в том, чтобы показать возможность противоречия второму закону термодинамики.

Талисман BSD: В операционных системах BSD есть свой талисман — красный чертёнок (этакая игра слов «daemon/demon»). BSD-демона зовут Beastie (Бисти), и его часто можно увидеть с трезубцем, который символизирует системный вызов fork(), активно используемый программами-демонами.

Примечание: «Бисти» по звучанию напоминает BSD (произносится как «Би-Эс-Ди»). При этом beastie является уменьшительной формой от слова beast (зверь).

Теологическая версия: Сторонники данной версии считают, что первоначальной формой произношения слова «daemon» было «daimon», что обозначает (по одной из версий) ангела-хранителя. В то время как «daemon» — помощник, «demon» — злой персонаж из Библии.

Примечание: Также «daemon» иногда произносится как «day-mon» или как рифма к слову «diamond».

Аббревиатура: Некоторые пользователи утверждают, что термин «daemon» является аббревиатурой от «Disk and Execution Monitor».

Поделиться в социальных сетях:

Android – это Linux? Сравнение Android и Linux

Источник

Оцените статью