- Services and Daemons — runit
- Section Contents
- Service Directories
- Configuring Services
- Editing Services
- Managing Services
- Runsvdirs
- Booting A Different runsvdir
- Basic Usage
- Enabling Services
- Disabling Services
- Testing Services
- Что такое демоны (daemons) в Linux?
- Что такое демоны?
- Примеры демонов в Linux
- Версии происхождения термина «daemon»
- Linux Jargon Buster: What are Daemons in Linux?
- What is a Daemon in Linux?
- What Daemons are Running on Your Machine?
- Spawning Daemons
- Examples of Linux Daemons
- What is the origin of the word, daemon?
Services and Daemons — runit
Void uses the runit(8) supervision suite to run system services and daemons.
Some advantages of using runit include:
- a small code base, making it easier to audit for bugs and security issues.
- each service is given a clean process state, regardless of how the service was started or restarted: it will be started with the same environment, resource limits, open file descriptors, and controlling terminals.
- a reliable logging facility for services, where the log service stays up as long as the relevant service is running and possibly writing to the log.
If you don’t need a program to be running constantly, but would like it to run at regular intervals, you might like to consider using a cron daemon.
Section Contents
Service Directories
Each service managed by runit has an associated service directory.
A service directory requires only one file: an executable named run , which is expected to exec a process in the foreground.
Optionally, a service directory may contain:
- an executable named check , which will be run to check whether the service is up and available; it’s considered available if check exits with 0.
- an executable named finish , which will be run on shutdown/process stop.
- a conf file; this can contain environment variables to be sourced and referenced in run .
- a directory named log ; a pipe will be opened from the output of the run process in the service directory to the input of the run process in the log directory.
When a new service is created, a supervise folder will be automatically created on the first run.
Configuring Services
Most services can take configuration options set by a conf file in the service directory. This allows service customization without modifying the service directory provided by the relevant package.
Check the service file for how to pass configuration parameters. A few services have a field like OPTS=»—value . » in their conf file.
To make more complex customizations, you should edit the service.
Editing Services
To edit a service, first copy its service directory to a different directory name. Otherwise, xbps-install(1) can overwrite the service directory. Then, edit the new service file as needed. Finally, the old service should be stopped and disabled, and the new one should be started.
Managing Services
Runsvdirs
A runsvdir is a directory in /etc/runit/runsvdir containing enabled services in the form of symlinks to service directories. On a running system, the current runsvdir is accessible via the /var/service symlink.
The runit-void package comes with two runsvdirs, single and default :
- single just runs sulogin(8) and the necessary steps to rescue your system.
- default is the default runsvdir on a running system, unless specified otherwise by the kernel command line.
Additional runsvdirs can be created in /etc/runit/runsvdir/ .
See runsvdir(8) and runsvchdir(8) for further information.
Booting A Different runsvdir
To boot a runsvdir other than default , the name of the desired runsvdir can be added to the kernel command-line. As an example, adding single to the kernel command line will boot the single runsvdir.
Basic Usage
To start, stop, restart or get the status of a service:
The placeholder can be:
- Service names (service directory names) inside the /var/service/ directory.
- The full paths to the services.
For example, the following commands show the status of a specific service and of all enabled services:
See sv(8) for further information.
Enabling Services
Void Linux provides service directories for most daemons in /etc/sv/ .
To enable a service on a booted system, create a symlink to the service directory in /var/service/ :
If the system is not currently running, the service can be linked directly into the default runsvdir:
This will automatically start the service. Once a service is linked it will always start on boot and restart if it stops, unless administratively downed.
To prevent a service from starting at boot while allowing runit to manage it, create a file named down in its service directory:
The down file mechanism also makes it possible to disable services that are enabled by default, such as the agetty(8) services for ttys 1 to 6. This way, package updates which affect these services
- in this case, the runit-void package — won’t re-enable them.
Disabling Services
To disable a service, remove the symlink from the running runsvdir:
Or, for example, from the default runsvdir, if either the specific runsvdir, or the system, is not currently running:
Testing Services
To check if a service is working correctly when started by the service supervisor, run it once before fully enabling it:
If everything works, remove the down file to enable the service.
Источник
Что такое демоны (daemons) в Linux?
Обновл. 20 Июл 2021 |
В этой статье мы рассмотрим, что такое демоны (и их примеры) в Linux, а также версии происхождения термина «daemon».
Что такое демоны?
Демоны (англ. «daemons») — это работающие в фоновом режиме служебные программы (или процессы), целью которых является мониторинг определенных подсистем ОС и обеспечение её нормальной работы. Например, демон принтера контролирует возможности печати, демон сети контролирует и поддерживает сетевые коммуникации и т.д.
Демоны являются аналогом служб (services) в Windows: они выполняют определенные действия в заранее определенное время или в ответ на определенные события. Существует множество различных демонов, работающих в Linux, каждый из которых создан специально для наблюдения за своей собственной маленькой частью системы. Из-за того, что демоны выполняют основную часть своей работы в фоновом режиме и не находятся под прямым контролем пользователя, бывает трудно определить предназначение того или иного демона.
Так как демон — это процесс, который выполняется в фоновом режиме и обычно находится вне контроля пользователя, то у него нет управляющего терминала.
Процесс — это запущенная программа. В определенный момент времени процесс может либо выполняться, либо ожидать, либо быть «зомби».
В Linux существует три типа процессов:
Процессы переднего плана (или «интерактивные процессы») — это те процессы, которые запускаются пользователем в терминале.
Фоновые процессы (или «автоматические процессы») — это объединенные в список процессы, не подключенные к терминалу; они не ожидают пользовательского ввода данных.
Демоны (англ. «daemons») — это особый тип фоновых процессов, которые запускаются при старте системы и продолжают работать в виде системных служб; они не умирают.
Процессы переднего плана и фоновые процессы не являются демонами, хотя их можно запускать в фоновом режиме и выполнять некоторую работу по мониторингу системы. Для данных типов процессов необходимо участие пользователя, который бы их запускал. В то время как демонам для их запуска пользователь не требуется.
Когда завершается загрузка системы, процесс инициализации системы начинает создавать демоны с помощью метода fork(), устраняя необходимость в терминале (именно это подразумевается под «отсутствием управляющего терминала»).
Я не буду вдаваться в подробности работы метода fork(), отмечу лишь, что, хотя существуют и другие методы, традиционный способ создания дочернего процесса в Linux заключается в создании копии существующего процесса (посредством своеобразного «ответвления»), после чего выполняется системный вызов exec() для запуска другой программы.
Примечание: Термин «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
Источник
Linux Jargon Buster: What are Daemons in Linux?
Last updated June 5, 2021 By Bill Dyer 29 Comments
Daemons work hard so you don’t have to.
Imagine that you are writing an article, Web page, or book, Your intent is to do just that – write. It’s rather nice not having to manually start printer and network services and then monitor them all day to make sure that they are working right.
We can thank daemons for that – they do that kind of work for us.
What is a Daemon in Linux?
A daemon (usually pronounced as: day-mon , but sometimes pronounced as to rhyme with diamond ) is a program with a unique purpose. They are utility programs that run silently in the background to monitor and take care of certain subsystems to ensure that the operating system runs properly. A printer daemon monitors and takes care of printing services. A network daemon monitors and maintains network communications, and so on.
Having gone over the pronunciation of daemon, I’ll add that, if you want to pronounce it as demon, I won’t complain.
For those people coming to Linux from the Windows world, daemons are known as services. For Mac users, the term, services, has a different use. The Mac’s operating system is really UNIX, so it uses daemons. The term, services is used, but only to label software found under the Services menu.
Daemons perform certain actions at predefined times or in response to certain events. There are many daemons that run on a Linux system, each specifically designed to watch over its own little piece of the system, and because they are not under the direct control of a user, they are effectively invisible, but essential. Because daemons do the bulk of their work in the background, they can appear a little mysterious and so, perhaps difficult to identify them and what they actually do.
What Daemons are Running on Your Machine?
To identify a daemon, look for a process that ends with the letter d. It’s a general Linux rule that the names of daemons end this way.
There are many ways to catch a glimpse of a running daemon. They can be seen in process listings through ps , top , or htop . These are useful programs in their own right – they have a specific purpose, but to see all of the daemons running on your machine, the pstree command will suit our discussion better.
The pstree command is a handy little utility that shows the processes currently running on your system and it show them in a tree diagram. Open up a terminal and type in this command:
You will see a complete listing of all of the processes that are running. You may not know what some of them are, or what they do, they are listed. The pstree output is a pretty good illustration as to what is going on with your machine. There’s a lot going on!
Looking at the screen shot, a few daemons can be seen here: udisksd, gvfsd, systemd, logind and some others.
Our process list was long enough to where the listing couldn’t fit in a single terminal window, but we can scroll up using the mouse or cursor keys:
Spawning Daemons
Again, a daemon is a process that runs in the background and is usually out of the control of the user. It is said that a daemon has no controlling terminal.
A process is a running program. At a particular instant of time, it can be either running, sleeping, or zombie (a process that completed its task, but waiting for its parent process to accept the return value).
In Linux, there are three types of processes: interactive, batch and daemon.
Interactive processes are those which are run by a user at the command line are called interactive processes.
Batch processes are processes that are not associated with the command line and are presented from a list of processes. Think of these as “groups of tasks”. These are best at times when the system usage is low. System backups, for example, are usually run at night since the daytime workers aren’t using the system. When I was a full-time system administrator, I often ran disk usage inventories, system behavior analysis scripts, and so on, at night.
Interactive processes and batch jobs are not daemons even though they can be run in the background and can do some monitoring work. They key is that these two types of processes involve human input through some sort of terminal control. Daemons do not need a person to start them up.
We know that a daemon is a computer program that runs as a background process, rather than being under the direct control of an interactive user. When the system boot is complete, the system initialization process starts spawning (creating) daemons through a method called forking, eliminating the need for a terminal (this is what is meant by no controlling terminal).
I will not go into the full details of process forking, but hopefully, I can be just brief enough to show a little background information to describe what is done. While there are other methods to create processes, traditionally, in Linux, the way to create a process is through making a copy of an existing process in order to create a child process. An exec system call to start another program in then performed.
The term, fork isn’t arbitrary, by the way. It gets its name from the C programming language. One of the libraries that C uses, is called the standard library, containing methods to perform operating services. One of these methods, called fork, is dedicated to creating new processes. The process that initiates a fork is considered to be the parent process of the newly created child process.
The process that creates daemons is the initialization (called init ) process by forking its own process to create new ones. Done this way, the init process is the outright parent process.
There is another way to spawn a daemon and that is for another process to fork a child process and then die (a term often used in place of exit). When the parent dies, the child process becomes an orphan. When a child process is orphaned, it is adopted by the init process.
If you overhear discussions, or read online material, about daemons having “a parent process ID of 1,” this is why. Some daemons aren’t spawned at boot time, but are created later by another process which died, and init adopted it.
It is important that you do not confuse this with a zombie. Remember, a zombie is a child process that has finished its task and is waiting on the parent to accept the exit status.
Examples of Linux Daemons
Again, the most common way to identify a Linux daemon is to look for a service that ends with the letter d. Here are some examples of daemons that may be running on your system. You will be able to see that daemons are created to perform a specific set of tasks:
systemd – the main purpose of this daemon is to unify service configuration and behavior across Linux distributions.
rsyslogd – used to log system messages. This is a newer version of syslogd having several additional features. It supports logging on local systems as well as on remote systems.
udisksd – handles operations such as querying, mounting, unmounting, formatting, or detaching storage devices such as hard disks or USB thumb drives
logind – a tiny daemon that manages user logins and seats in various ways
httpd – the HTTP service manager. This is normally run with Web server software such as Apache.
sshd – Daemon responsible for managing the SSH service. This is used on virtually any server that accepts SSH connections.
ftpd – manages the FTP service – FTP or File Transfer Protocol is a commonly-used protocol for transferring files between computers; one act as a client, the other act as a server.
crond – the scheduler daemon for time-based actions such as software updates or system checks.
What is the origin of the word, daemon?
When I first started writing this article, I planned to only cover what a daemon is and leave it at that. I worked with UNIX before Linux appeared. Back then, I thought of a daemon as it was: a background process that performed system tasks. I really didn’t care how it got its name. With additional talk of other things, like zombies and orphans, I just figured that the creators of the operating system had a warped sense of humor (a lot like my own).
I always perform some research on every piece that I write and I was surprised to learn that apparently, a lot of other people did want to know how the word came to be and why.
The word has certainly generated a bit of curiosity and, after reading through several lively exchanges, I admit that I got curious too. Perform a search on the word’s meaning or etymology (the origin of words) and you’ll find several answers.
In the interest of contributing to the discussion, here’s my take on it.
The earliest form of the word, daemon, was spelled as daimon, a form of guardian angel – attendant spirits that helped form the character of people they assisted. Socrates claimed to have one that served him in a limited way, but correctly. Socrates’ daimon only told him when to keep his mouth shut. Socrates described his daimon during his trial in 399 BC, so the belief in daimons has been around for quite some time. Sometimes, the spelling of daimon is shown as daemon. Daimon and daemon, here, mean the same thing.
While a daemon is an attendant, a demon is an evil character from the Bible. The differences in spelling is intentional and was apparently decided upon in the 16th century. Daemons are the good guys, and demons are the bad ones.
The use of the word, daemon, in computing came about in 1963. Project MAC is shorthand for Project on Mathematics and Computation, and was created at the Massachusetts Institute of Technology. It was here that the word, daemon, came into common use to mean any system process that monitors other tasks and performs predetermined actions depending on their behavior, The word, daemon was named for Maxwell’s daemon.
Maxwell’s daemon is the result of a thought experiment. In 1871, James Clerk Maxwell imagined an intelligent and resourceful being that was able to observe and direct the travel of individual molecules in a specific direction. The purpose of the thought exercise was to show the possibility of contradicting the second law of thermodynamics.
I did see some comments that the word, daemon, was an acronym for Disk And Executive MONitor . The original users of the word, daemon, never used it for that purpose, so the acronym idea, I believe, is incorrect.
Lastly – to end this on a light note – there is the BSD mascot: a daemon that has the appearance of a demon. The BSD daemon was named after the software daemons, but gets is appearance from playing around with the word.
The daemon’s name is Beastie. I haven’t researched this fully (yet), but I did find one comment that states that Beastie comes from slurring the letters, BSD. Try it; I did. Say the letters as fast as you can and out comes a sound very much like beastie.
Beastie is often seen with a trident which is symbolic of a daemon’s forking of processes.
Like what you read? Please share it with others.
Источник