getty linux что это

Getty linux что это

This program does not use the /etc/gettydefs (System V) or /etc/gettytab (SunOS 4) files.

ARGUMENTS

Under System V, a «-» port argument should be preceded by a «—«. baud_rate. A comma-separated list of one or more baud rates. Each time agetty receives a BREAK character it advances through the list, which is treated as if it were circular.

Baud rates should be specified in descending order, so that the null character (Ctrl-@) can also be used for baud rate switching. term The value to be used for the TERM environment variable. This overrides whatever init(8) may have set, and is inherited by login and the shell.

OPTIONS


EXAMPLES

For a hard-wired line or a console tty:
/sbin/agetty 9600 ttyS1

ISSUE ESCAPES

b Insert the baudrate of the current line. d Insert the current date. s Insert the system name, the name of the operating system. l Insert the name of the current tty line. m Insert the architecture identifier of the machine, eg. i486 n Insert the nodename of the machine, also known as the hostname. o Insert the NIS domainname of the machine. O Insert the DNS domainname of the machine. r Insert the release number of the OS, eg. 1.1.9. t Insert the current time. u Insert the number of current users logged in. U Insert the string «1 user» or » users» where is the number of current users logged in. v Insert the version of the OS, eg. the build-date etc. Example: On my system, the following /etc/issue file:

FILES

The text in the /etc/issue file (or other) and the login prompt are always output with 7-bit characters and space parity.

Источник

Getty linux что это

Аргументам программы getty приписан следующий смысл:

линия Имя терминальной линии, к которой программа getty должна подключиться; используется как имя файла в каталоге /dev. Этот файл открывается на чтение и запись.

-t время_ожидания Программа getty завершится, если файл, соответствующий линии, будет успешно открыт, но в течение указанного времени_ожидания (в секундах) в линию не поступит ни одного символа.

-c файл Опция проверки корректности. Указанный файл просматривается, как если бы это был файл /etc/gettydefs, и результаты просмотра поступают на стандартный вывод. Если при этом обнаруживаются какие либо ошибки, то выдаются соответствующие сообщения. Если строки файла корректны, то выводятся значения флагов [см. ioctl(2) по поводу их интерпретации]. Заметим, что некоторые значения добавляются к флагам автоматически.

Если не указан ни один из необязательных аргументов, программа getty устанавливает скорость в 300 бод, бесструктурный режим (реакция на каждый символ), без отображения вводимых символов, без контроля четности, символы перевода строки будут заменяться последовательностью (возврат каретки, переход к новой строке) и символы табуляции будут заменяться пробелами при выдаче их на стандартный вывод. Затем getty выдает приглашение и приступает к посимвольному вводу входного имени пользователя. Если будет получен символ с нулевым кодом (или произойдет нарушение протокола), делается вывод, что пользователь нажал клавишу прерывания. В результате getty произведет попытку использовать следующее значение скорости из серии доступных значений, определенных в файле /etc/gettydefs.

Ввод входного имени пользователя должен завершаться нажатием клавиши перевода строки или возврата каретки. В последнем случае устанавливается соотвестствующая трактовка системой символа возврата каретки [см. ioctl(2)].

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

Наконец, программа getty выполняет системный вызов exec(2) и заменяется программой login с входным именем пользователя в качестве аргумента. После имени пользователя могут быть введены дополнительные аргументы, которые будут переданы программе login, и та поместит их в окружение [см. login(1)].

Источник

Getty linux что это

After the initialization, the line is closed and reopened. This time, however, the line is opened in blocking mode so that the device is not tied up. Detection of the carrier signal will allow the line to be opened.

Next, getty types the issue (or login banner, usually from /etc/issue ) and login prompt. Finally, getty reads the user’s login name and invokes login (1m) with the user’s name as an argument. While reading the name, getty attempts to adapt the system to the speed of the terminal being used, and also sets certain terminal parameters (see termio (7)) to conform with the user’s login procedure.

The speed argument is a label to a entry in the /etc/gettydefs file (see gettydefs (4)). This entry defines to getty the initial speed (baud rate) and tty settings, the login prompt to be used, the final speed and tty settings, and a pointer to another entry to try should the user indicate that the speed is not correct. This is done by sending a
character (actually sequence). Under certain conditions, a carriage-return will perform the same function. This is usually the case when getty is set to a higher speed than the modem or terminal. Getty scans the gettydefs file sequentially looking for a matching entry. If no speed was given or the entry cannot be found, the first entry in the /etc/gettydefs file is used as a default. In the event that the gettydefs file cannot be accessed, there is a compiled-in default entry that is used.

The type argument is a string which names the type of terminal attached to the line. The type should be a valid terminal name listed in the termcap (7) database. Getty uses this value to determine how to clear the video display. It also sets the environment variable TERM to the contents of this value.

As mentioned, getty types the login prompt and then reads the user’s login name. If a null character is received, it is assumed to be the result of the user pressing the
key or the carriage-return key to indicate the speed is wrong. This causes getty to locate the next speed in the series (defined in /etc/gettydefs).

The user’s name is terminated by a new-line or carriage-return character. A carriage-return results in the system being set to map those to new-lines (see ioctl (2)).

The user’s name is scanned to see if it contains only upper-case characters. If so, the system is set to map any future upper-case characters into lower-case.

DEFAULTS FILE

The \A escape marks the place where the digits showing the speed will be seen. See CONNECTION AND AUTOBAUDING for more details. The default is to not perform a connection chat sequence. WAITFOR= string This parameter is similar to WAITCHAR, but defines a string of characters to be waited for. Getty will wait until string is received before issuing the login prompt. This parameter is best used when combined with CONNECT, as in this example:

PROMPT SUBSTITUTIONS


LINE INITIALIZATION

Line initialization is performed just after the line is opened and prior to handling the WAITCHAR and/or WAITFOR options. Initialization is accomplished by placing an

line in the defaults file. String is a series of one or more fields in the form

This resembles the expect/send sequences used in the UUCP L.sys file, with the following exception: A carriage return is NOT appended automatically to sequences that are ‘sent.’ If you want a carriage-return sent, you must explicitly show it, with ‘\r’.

Getty supports subfields in the expect field of the form

CONNECTION AND AUTOBAUDING

The for the connect chat script is exactly the same as that for the INIT script (see LINE INITIALIZATION), with the following addition:
\A Marks the spot where the baud rate will be seen. This mark will match any and all digits 0-9 at that location in the script, and set it’s speed to that value, if possible. Autobauding, therefore, is enabled by placing the \A mark in the chat script. For example, the definition:

would match the string CONNECT 1200 and cause getty to set it’s baud rate to 1200, using the following steps: 1. Having matched the value 1200, getty will attempt to find an entry with the label 1200 in the gettydefs file. If a matching gettydefs entry is found, those values are used. If there is no match, then 2. The gettydefs values currently in use are modified to use the matched speed (e.g. 1200). However, if the matched speed is invalid, then 3. Getty logs a warning message and resumes normal operation. This allows the practice of toggling through linked entries in the gettydefs file to behave as expected.

UUGETTY

When uugetty starts up, if it sees a lock file on the line it intends to use, it will use the pid in the lock file to see if there is an active process holding the lock. If not, uugetty will remove the lock file and continue. If a valid process is found, uugetty will sleep until that process releases the lock and then it will exit, forcing init (1m) to spawn a new uugetty. Once no conflicting process is found, uugetty grabs the line by creating the lock file itself before issuing the login prompt. This prevents other processes from using the line.

Uugetty will normally only lock the name of the line it is running on. On systems where there are two device names referring to the same port (as is the case where one device uses modem control while the other doesn’t), place a line of the form

line in the defaults file. For instance, if uugetty is on /dev/tty1a, and you want to have it lock /dev/tty1A also, use the line ALTLOCK=tty1A in the defaults file.

While waiting for carrier detect, Uugetty will check for lockfiles every 30 seconds. If lockfiles are found, uugetty will exit, and init will respawn another getty. This allows the modem to be reinitialized after another process has used the modem.

Источник

systemd: getty-подобный сервис для htop

htop — это интерактивная программа для наблюдения за процессами; она — альтернатива программы top. Каждый, кто работает за машиной с линуксом на борту, хоть раз использовал её: будь то поиск процесса (и его последующее убийство) или тщательный мониторинг используемых ресурсов.

getty linux что это. Смотреть фото getty linux что это. Смотреть картинку getty linux что это. Картинка про getty linux что это. Фото getty linux что это

Для удобства это программу можно держать всегда запущенной: в отдельном окне терминала, в его вкладках или на каком-нибудь рабочем столе. Но есть ещё одно решение: запускать его на фиксированном VT, на который можно в любой момент переключиться. Преимущество такого подхода заключается в чистом окружении и независимости от иксов/терминала.

Это возможно (и правильно) сделать с помощью системы инициализации, потому что мы фактичесски хотим получить специальный getty-подобный сервис для htop.

Традиционные системы инициализации Linux конфигурируются на запуск фиксированного количества agetty при загрузке. В большинстве случаев рождаются шесть инстансов для шести VT: от tty1 до tty6 соответственно. В systemd используется другой подход.

systemctl cat getty@.service покажет содержимое этого сервиса. Рассматривать подробно мы его не собираемся, поскольку это для нас не столь важно.

Пишем собственный getty-подобный юнит

Теперь переходим в /etc/systemd/system — одна из директорий, где располагаются юниты, — и создаём собственный сервис:

Наличие суффикса ( @ ) означает, что стартует не сам по себе сервис, а один из его инстансов. А суффикс передаётся в него парамметром ( %i и %I ).

Выше уже было отмечено, что содержимое getty@.service для нас не столь важно. Всё так, потому что его можно заинклюдить в наш сервис:

Если учесть, что наш сервис getty-подобный, то эта конструкция избавляет нас от лишнего копирования кода.

Секция Unit

Здесь описываются общие парамметры, применимые к любому типу юнита.

Секция Service

Эта секция задаёт конфигурацию конкретно сервиса. Иными словами, описывает способ запуска процесса.

— это указание systemd запускать htop подсоединённым напрямую к терминалу.

Можно, кстати, добавить не мгновенный запуск, а с ожиданием ввода. Для этого создаём простой скрипт на баше:

Всё что он делает — ожидает ввода и запускает какую-то программу (которой будет являться htop в нашем случае). Помещаем куда угодно, называем как угодно, делаем его исполняемым ( chmod +x ) и правим ExecStart в нашем сервисе:

Ограничиваем права

Итак, создаём новый сервис и новый скрипт на основе двух предыдущих:

И редактируем каждый из них. Для сервиса в секции Service изменяем значение Environment и задаём имя пользователя с его группой:

А в скрипте обращаемся к su(1) :

Установка сервиса

Теперь наш сервис готов, осталось только добавить его в автозагрузку:

Заключение

Теперь перезагружаемся (либо вручную убиваем getty@ и включаем htop@ для инстанса tty2), переключаемся на второй VT и наблюдаем успешно запущенный htop. Продемонстрированный трюк задевает лишь малую часть systemd, как системы инициализации, от всего простора его возможностей, как универсального plumbing layer-а — набора программ для решения совершенно разных задач. Успехов!

Источник

Последовательное оборудование и запрос login:

Когда-то очень распространенным вариантом Unix-систем был такой: одна мощная машина, а вокруг нее много тупых («dumb») символьных терминалов или модемов. Сейчас такая схема очень редкая, что очень радует. А вот модемы сейчас очень распространены, хотя они используются обычно для сервисов SLIP и PPP (описаны в главе 7 и главе 8). Однако, каждая из этих конфигураций может использовать простую программу, названную getty.

Термин getty сокращение от «get tty» Программа getty открывает последовательное устройство, конфигурирует его, факультативно конфигурирует модем и ждет подключение, которое будет сделано. Активное подключение на последовательном устройстве обычно указывается Data Carrier Detect (DCD) штырьком в последовательном шнуре. Когда происходит соединение, getty выдает приглашение login: и затем вызывает программу login, чтобы обработать вход в систему. Каждый из виртуальных терминалов (устройств /dev/tty1 ) в Linux имеет свою копию программы getty, запущенную именно для него.

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

Настройка mgetty Daemon

Пример 4-6. Простой файл /etc/mgetty/mgetty.config

Эта глава дает только общее представлдение о mgetty. Подробные сведения можно найти в Serial-HOWTO.

После правки файла конфигурации, надо перезапустить процесс init, чтобы изменения вступили в силу. Пошлите сигнал hangup процессу init. Он всегда имеет ID процесса равный единице, так что можно использовать команду:

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *