- How to List All Running Services Under Systemd in Linux
- Listing Running Services Under SystemD in Linux
- If You Appreciate What We Do Here On TecMint, You Should Consider:
- Daemons
- Contents
- Typical functions of daemons
- List of service daemons for Linux and Unix-like systems
- How do I start / stop / restart daemons for the shell prompt?
- How do I see list of all running daemons?
- How to list all running daemons?
- 3 Answers 3
- Что такое демоны в Linux
- Что такое демоны в понятии Linux
- Какие демоны работают на вашем компьютере
- Запуск демонов в Linux
- Примеры демонов в Linux
- Как появился термин демон в Linux
How to List All Running Services Under Systemd in Linux
A Linux systems provide a variety of system services (such as process management, login, syslog, cron, etc.) and network services (such as remote login, e-mail, printers, web hosting, data storage, file transfer, domain name resolution (using DNS), dynamic IP address assignment (using DHCP), and much more).
Technically, a service is a process or group of processes (commonly known as daemons) running continuously in the background, waiting for requests to come in (especially from clients).
Linux supports different ways to manage (start, stop, restart, enable auto-start at system boot, etc.) services, typically through a process or service manager. Most if not all modern Linux distributions now use the same process manager: systemd.
Systemd is a system and service manager for Linux; a drop-in replacement for the init process, which is compatible with SysV and LSB init scripts and the systemctl command is the primary tool to manage systemd.
In this guide, we will demonstrate how to list all running services under systemd in Linux.
Listing Running Services Under SystemD in Linux
When you run the systemctl command without any arguments, it will display a list of all loaded systemd units (read the systemd documentation for more information about systemd units) including services, showing their status (whether active or not).
To list all loaded services on your system (whether active; running, exited or failed, use the list-units subcommand and —type switch with a value of service.
List All Services Under Systemd
And to list all loaded but active services, both running and those that have exited, you can add the —state option with a value of active, as follows.
List All Active Running Services in Systemd
But to get a quick glance of all running services (i.e all loaded and actively running services), run the following command.
List Running Services in Systemd
If you frequently use the previous command, you can create an alias command in your
/.bashrc file as shown, to easily invoke it.
Then add the following line under the list of aliases as shown in the screenshot.
Create a Alias for Long Command
Save the changes in the file and close it. And from now onwards, use the “running_services” command to view a list of all loaded, actively running services on your server.
View All Running Services
Besides, an important aspect of services is the port they use. To determine the port a daemon process is listening on, you can use the netstat or ss tools as shown.
Where the flag -l means print all listening sockets, -t displays all TCP connections, -u shows all UDP connections, -n means print numeric port numbers (instead of application names) and -p means show application name.
The fifth column shows the socket: Local Address:Port. In this case, the process zabbix_agentd is listening on port 10050.
Determine Process Port
Also, if your server has a firewall service running, which controls how to block or allow traffic to or from selected services or ports, you can list services or ports that have been opened in the firewall, using the firewall-cmd or ufw command (depending on the Linux distributions you are using) as shown.
List Open Services and Ports on Firewall
That’s all for now! In this guide, we demonstrated how to view running services under systemd in Linux. We also covered how to check the port a service is listening on and how to view services or ports opened in the system firewall. Do you have any additions to make or questions? If yes, reach us using the comment form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Источник
Daemons
A daemon (also known as background processes) is a Linux or UNIX program that runs in the background. Almost all daemons have names that end with the letter «d«. For example, httpd the daemon that handles the Apache server, or, sshd which handles SSH remote access connections. Linux often start daemons at boot time. Shell scripts stored in /etc/init.d directory are used to start and stop daemons.
Contents
Typical functions of daemons
- Open network port (such as port 80) and respond to network requests.
- Monitor system such as hard disk health or RAID array.
- Run scheduled tasks such as cron.
List of service daemons for Linux and Unix-like systems
- amd — Auto Mount Daemon
- anacron — Executed delayed cron tasks at boot time
- apmd — Advanced Power Management Daemon
- atd — Runs jobs queued using the at tool
- autofs — Supports the automounter daemon allowing mount and unmount of devices on demand
- crond — The task scheduler daemon
- cupsd — CUPS printer daemon
- dhcpd — Dynamic Host Configuration Protocol and Internet Bootstrap Protocol Server
- ftpd — FTP Server Daemon
- gated — routing daemon that handles multiple routing protocols and replaces routed and egpup
- httpd — Web Server Daemon
- inetd — Internet Superserver Daemon
- imapd — An imap server daemon
- lpd — Line Printer Daemon
- memcached — In-memory distributed object caching daemon
- mountd — mount daemon
- mysql — Database server daemon
- named — A DNS server daemon
- nfsd — Network File Sharing Daemon
- nfslock — Used to start and stop nfs file locking services
- nmbd — Network Message Block Daemon
- ntpd — Network Time Protocol service daemon
- postfix — A mail transport agent used as a replacement for sendmail
- postgresql — Database server daemon
- routed — Manages routing tables
- rpcbind — Remote Procedure Call Bind Daemon
- sendmail — A mail transfer agent Daemon
- smbd — Samba (an SMB Server) Daemon
- smtpd — Simple Mail Transfer Protocol Daemon
- snmpd — Simple Network Management Protocol Daemon
- squid — A web page caching proxy server daemon
- sshd — Secure Shell Server Daemon
- syncd — Keeps the file systems synchronized with system memory
- syslogd — System logging daemon
- tcpd — Service wrapper restricts access to inetd based services through hosts.allow and hosts.deny
- telnetd — Telnet Server daemon
- vsftpd — Very Secure FTP Daemon
- webmin — Web based administration server daemon
- xinetd — Enhanced Internet Superserver Daemon
- xntd — Network Time Server Daemon
How do I start / stop / restart daemons for the shell prompt?
You need to use the service command as follows [1] [2] ::
In this example, start, stop, and restart httpd daemon:
How do I see list of all running daemons?
To see the status all installed daemons, enter:
Sample outputs from CentOS Linux development server:
Sample outputs from my Ubuntu Linux desktop systems:
Источник
How to list all running daemons?
From my question Can Process id and session id of a daemon differ?, it was clear that I cannot easily decide the features of a daemon. I have read in different articles and from different forums that service —status-all command can be used to list all the daemons in my system. But I do not think that the command is listing all daemons because NetworkManager , a daemon which is currently running in my Ubuntu 14.04 system, is not listed by the command. Is there some command to list the running daemons or else is there some way to find the daemons from the filesystem itself?
3 Answers 3
The notion of daemon is attached to processes, not files. For this reason, there is no sense in «finding daemons on the filesystem». Just to make the notion a little clearer : a program is an executable file (visible in the output of ls ) ; a process is an instance of that program (visible in the output of ps ).
Now, if we use the information that I gave in my answer, we could find running daemons by searching for processes which run without a controlling terminal attached to them. This can be done quite easily with ps :
The tty output field contains «?» when the process has no controlling terminal.
The big problem here comes when your system runs a graphical environment. Since GUI programs (i.e. Chromium) are not attached to a terminal, they also appear in the output. On a standard system, where root does not run graphical programs, you could simply restrict the previous list to root’s processes. This can be achieved using ps ‘ -U switch.
Yet, two problems arise here:
- If root is running graphical programs, they will show up.
- Daemons running without root privileges won’t. Note that daemons which start at boot time are usually running as root.
Basically, we would like to display all programs without a controlling terminal, but not GUI programs. Luckily for us, there is a program to list GUI processes : xlsclients ! This answer from slm tells us how to use it to list all GUI programs, but we’ll have to reverse it, since we want to exclude them. This can be done using the —deselect switch.
First, we’ll build a list of all GUI programs for which we have running processes. From the answer I just linked, this is done using.
Now, ps has a -C switch which allows us to select by command name. We just got our command list, so let’s inject it into the ps command line. Note that I’m using —deselect afterwards to reverse my selection.
Now, we have a list of all non-GUI processes. Let’s not forget our «no TTY attached» rule. For this, I’ll add -o tty,args to the previous line in order to output the tty of each process (and its full command line) :
The final grep captures all lines which begin with «?», that is, all processes without a controlling tty. And there you go! This final line gives you all non-GUI processes running without a controlling terminal. Note that you could still improve it, for instance, by excluding kernel threads (which aren’t processes).
. or by adding a few columns of information for you to read:
Источник
Что такое демоны в Linux
Демоны много работают, для того, чтобы вы могли сосредоточится на своем деле. Представьте, что вы пишите статью или книгу. Вы заинтересованны в том, чтобы писать. Удобно, что вам не нужно вручную запускать принтер и сетевые службы, а потом следить за ними весь день для того чтобы убедится, что всё работает нормально.
За это можно благодарить демонов, они делают эту работу за нас. В сегодняшней статье мы рассмотрим что такое демоны в Linux, а также зачем они нужны.
Что такое демоны в понятии Linux
Демон Linux — это программа, у которой есть определённая уникальная цель. Обычно, это служебные программы, которые незаметно работают в фоновом режиме для того чтобы отслеживать состояние и обслуживать определённые подсистемы и гарантировать правильную работу всей операционной системы в целом. Например, демон принтера, отслеживает состояние служб печати, а сетевой демон управляет сетевыми подключениями и следит за их состоянием.
Многие люди, перешедшие в Linux из Windows знают демонов как службы или сервисы. В MacOS термин «Служба» имеет другое значение. Так как MacOS это тоже Unix, в ней испольуются демоны. А службами называются программы, которые находятся в меню Службы.
Демоны выполняют определённые действия в запланированное время или в зависимости от определённых событий. В системе Linux работает множество демонов, и каждый из них предназначен для того чтобы следить за своей небольшой частью операционной системы. Поскольку они не находятся под непосредственным контролем пользователя, они фактически невидимы, но тем не менее необходимы. Поскольку демоны выполняют большую часть своей работы в фоновом режиме, они могут казаться загадочными.
Какие демоны работают на вашем компьютере
Обычно имена процессов демонов заканчиваются на букву d. В Linux принято называть демоны именно так. Есть много способов увидеть работающих демонов. Они попадаются в списке процессов, выводимом утилитами ps, top или htop. Но больше всего для поиска демонов подходит утилита pstree. Эта утилита показывает все процессы, запущенные в вашей системе в виде дерева. Откройте терминал и выполните такую команду:
Вы увидите полный список всех запущенных процессов. Вы можете не знать за что отвечают эти процессы, но они все будут здесь перечислены. Вывод pstree — отличная иллюстрация того, что происходит с вашей машиной. Здесь удобно найти запущенные демоны Linux.
Вот демоны Linux, которых вы можете здесь увидеть: udisksd, gvfsd, systemd, logind и много других. Список процессов довольно длинный, поэтому он не поместится в одном окне терминала, но вы можете его листать.
Запуск демонов в Linux
Давайте разберемся как запустить демона Linux. Ещё раз. Демон — это процесс, работающий в фоновом режиме и находится вне контроля пользователя. Это значит, что демон не связан с терминалом, с помощью которого можно было бы им управлять. Процесс — это запущенная программа. В каждый момент времени он может быть запущенным, спящим или зомби (процесс выполнивший свою задачу, но ожидающий пока родительский процесс примет результат).
В Linux существует три типа процессов: интерактивные, пакетные и демоны. Интерактивные процессы пользователь запускает из командной строки. Пакетные процессы обычно тоже не связанны с терминалом. Они запускаются обычно во время когда на систему минимальная нагрузка и делают свою работу. Это могут быть, например, скрипты резервного копирования или другие подобные обслуживающие сценарии.
Интерактивные и пакетные процессы нельзя считать демонами, хотя их можно запускать в фоновом режиме и они делают определённую работу. Ключевое отличие в том, что оба вида процессов требуют участия человека. Демонам не нужен человек для того чтобы их запускать.
Когда загрузка системы завершается, система инициализации, например, systemd, начинает создавать демонов. Этот процесс называется forking (разветвление). Программа запускается как обычный интерактивный процесс с привязкой к терминалу, но в определённый момент она делится на два идентичных потока. Первый процесс, привязанный к терминалу может выполнятся дальше или завершится, а второй, уже ни к чему не привязанный продолжает работать в фоновом режиме.
Существуют и другие способы ветвления программ в Linux, но традиционно для создания дочерних процессов создается копия текущего. Термин forking появился не из ниоткуда. Его название походит от функции языка программирования Си. Стандартная библиотека Си содержит методы для управления службами, и один из них называется fork. Используется он для создания новых процессов. После создания процесса, процесс, на основе которого был создан демон считается для него родительским процессом.
Когда система инициализации запускает демонов, она просто разделяется на две части. В таком случае система инициализации будет считаться родительским процессом. Однако в Linux есть ещё один метод запуска демонов. Когда процесс создает дочерний процесс демона, а затем завершается. Тогда демон остается без родителя и его родителем становится система инициализации. Важно не путать такие процессы с зомби. Зомби, это процессы, завершившие свою работу и ожидающие пока родительский процесс примет их код выхода.
Примеры демонов в Linux
Самый простой способ определить демона — это буква d в конце его названия. Вот небольшой список демонов, которые работают в вашей системе. Каждый демон создан для выполнения определённой задачи.
- systemd — основная задача этого демона унифицировать конфигурацию и поведение других демонов в разных дистрибутивах Linux.
- udisksd — обрабатывает такие операции как: монтирование, размонтирование, форматирование, подключение и отключение устройств хранения данных, таких как жесткие диски, USB флешки и т д.
- logind — небольшой демон, управляющий авторизацией пользователей.
- httpd — демон веб-сервера, позволяет размешать на компьютере или сервере веб-сайты.
- sshd — позволяет подключаться к серверу или компьютеру удалённо, по протоколу SSH.
- ftpd — организует доступ к компьютеру по протоколу FTP для передачи файлов.
- crond — демон планировщика, позволяющий выполнять нужные задачи в определённое время.
Как появился термин демон в Linux
Так откуда же взялся этот термин? На первый взгляд может показаться, что у создателей операционной системы просто было искаженное чувство юмора. Но это не совсем так. Это слово появилось в вычислительной технике ещё до появления Unix. А история самого слова ещё более древняя.
Изначально это слово писалось как daimon и означало ангелов хранителей или духов помощников, которые помогали формировать характеры людей. Сократ утверждал, что у него был демон, который ему помогал. Демон Сократа говорил ему когда следует держать язык за зубами. Он рассказал о своем демоне во время суда в 399 году до нашей эры. Так что вера в демонов существует довольно давно. Иногда слово daimon пишется как daemon. Это одно и то же.
В то время как daemon — помощник, demon — это злой персонаж из библии. Различия в написании не случайны и видимо так было решено где-то в 16-том веке. Тогда решили, что daemons — хорошие парни, а demons — плохие.
Использовать слово демон (daemon) в вычислительной технике начали в 1963 году. Проект Project MAC (Project on Mathematics and Computation) был разработан в Массачусетском технологическом институте. И именно в этом проекте начали использовать слово демон для обозначения любых программ, которые работают в фоновом режиме, следят за состоянием других процессов и выполняют действия в зависимости от ситуации. Эти программы были названы в честь демона Максвелла.
Демон Максвелла — это результат мысленного эксперимента. В 1871 году Джеймс Клер Максвелл представил себе существо, способное наблюдать и направлять движение отдельных молекул. Целью мысленного эксперимента было показать противоречия во втором законе термодинамики.
Однако есть и другие варианты значения этого слова. Например это может быть аббревиатура от Disk And Executive MONitor. Хотя первоначальные пользователи термина демон не использовали его для этих целей, так что вариант с аббревиатурой, скорее всего неверный.
Теперь вы знаете что такое демоны в понятии Linux. На завершение, обратите внимание, что талисман BSD — демон. Он выбран в честь программных демонов (daemons) но выглядит как злой демон (demon). Имя этого демона Beastie. Точно неизвестно откуда взялось это имя, но есть предположения, оно походит от фразы: BSD. Try it; I did. Если произнести это на английском быстро, получится звук похожий на Beastie. А ещё тризуб Beastie символизирует разветвление (forking) процессов в Linux.
Источник