# SOME DESCRIPTIVE TITLE # Copyright (C) YEAR The FreeBSD Project # This file is distributed under the same license as the FreeBSD Documentation package. # Vladlen Popolitov , 2025. msgid "" msgstr "" "Project-Id-Version: FreeBSD Documentation VERSION\n" "POT-Creation-Date: 2025-10-03 18:09+0300\n" "PO-Revision-Date: 2025-10-03 04:45+0000\n" "Last-Translator: Vladlen Popolitov \n" "Language-Team: Russian \n" "Language: ru\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && " "n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n" "X-Generator: Weblate 4.17\n" #. type: Yaml Front Matter Hash Value: description #: documentation/content/en/books/design-44bsd/_index.adoc:1 #, no-wrap msgid "Donated by Addison-Wesley, provides a design overview of 4.4BSD, from which FreeBSD was originally derived" msgstr "Предоставлено издательством Addison-Wesley и предоставляет обзор архитектуры 4.4BSD, от которой изначально произошел FreeBSD" #. type: Title = #: documentation/content/en/books/design-44bsd/_index.adoc:1 #: documentation/content/en/books/design-44bsd/_index.adoc:16 #, no-wrap msgid "The Design and Implementation of the 4.4BSD Operating System" msgstr "Архитектура и реализация операционной системы 4.4BSD" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:50 msgid "'''" msgstr "'''" #. type: Title == #: documentation/content/en/books/design-44bsd/_index.adoc:54 #, no-wrap msgid "Design Overview of 4.4BSD" msgstr "Обзор архитектуры 4.4BSD" #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:57 #, no-wrap msgid "4.4BSD Facilities and the Kernel" msgstr "Подсистемы и ядро 4.4BSD" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:61 msgid "" "The 4.4BSD kernel provides four basic facilities: processes, a filesystem, " "communications, and system startup. This section outlines where each of " "these four basic services is described in this book." msgstr "" "Ядро 4.4BSD предоставляет четыре базовых подсистемы: процессы, файловую " "систему, коммуникации и запуск системы. Этот раздел перечисляет, в каком " "месте этой книги описана каждая из этих подсистем." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:63 msgid "" "Processes constitute a thread of control in an address space. Mechanisms for " "creating, terminating, and otherwise controlling processes are described in " "Chapter 4. The system multiplexes separate virtual-address spaces for each " "process; this memory management is discussed in Chapter 5." msgstr "" "Процессы образуют поток управления в адресном пространстве. Механизмы " "создания, завершения и другие управляющие процессы описаны в Главе 4. Для " "каждого процесса система мультиплексирует отдельное виртуальное адресное " "пространство; такое управление памятью обсуждается в Главе 5." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:64 msgid "" "The user interface to the filesystem and devices is similar; common aspects " "are discussed in Chapter 6. The filesystem is a set of named files, " "organized in a tree-structured hierarchy of directories, and of operations " "to manipulate them, as presented in Chapter 7. Files reside on physical " "media such as disks. 4.4BSD supports several organizations of data on the " "disk, as set forth in Chapter 8. Access to files on remote machines is the " "subject of Chapter 9. Terminals are used to access the system; their " "operation is the subject of Chapter 10." msgstr "" "Механизм доступа пользователя к файловой системе и устройствам один и тот " "же; общие аспекты обсуждаются в Главе 6. Файловая система является набором " "именованных файлов, организованных в древовидную иерархию каталогов, а " "операции по управлению ими представлены в Главе 7. Файлы располагаются на " "таких физических носителях, как диски. 4.4BSD поддерживает несколько типов " "организации данных на диске, как описано далее в Главе 8. Доступ к файлам на " "удаленных машинах является предметом обсуждения в Главе 9. Для доступа к " "системе Терминалы используются терминалы; их функционированию посвящена " "глава 10." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:65 msgid "" "Communication mechanisms provided by traditional UNIX systems include " "simplex reliable byte streams between related processes (see pipes, Section " "11.1), and notification of exceptional events (see signals, Section 4.7). " "4.4BSD also has a general interprocess-communication facility. This " "facility, described in Chapter 11, uses access mechanisms distinct from " "those of the filesystem, but, once a connection is set up, a process can " "access it as though it were a pipe. There is a general networking framework, " "discussed in Chapter 12, that is normally used as a layer underlying the IPC " "facility. Chapter 13 describes a particular networking implementation in " "detail." msgstr "" "Механизмы коммуникаций, предоставляемые традиционными UNIX-системами, " "включают однонаправленные потоки байтов между связанными процессами " "(смотрите материал о конвейерах в Разделе 11.1) и извещение об " "исключительных событиях (смотрите материал о сигналах в Разделе 4.7). В " "4.4BSD имеется также механизм межпроцессного взаимодействия между " "процессами. Этот механизм, описываемый в Главе 11, использует способы " "доступа, отличающиеся от тех, что используются в файловой системе, но, как " "только соединение установлено, процесс может работать с ним, как будто это " "конвейер. Имеется и механизм работы с сетью, описываемый в Главе 12, который " "обычно используется как слой ниже механизма IPC. В Главе 13 дается детальное " "описание конкретной реализации механизма работы с сетью." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:66 msgid "" "Any real operating system has operational issues, such as how to start it " "running. Startup and operational issues are described in Chapter 14." msgstr "" "В любой операционной системе присутствуют вопросы управления, такие, как ее " "запуск. Запуск и вопросы управления обсуждаются в Главе 14." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:70 msgid "" "Sections 2.3 through 2.14 present introductory material related to Chapters " "3 through 14. We shall define terms, mention basic system calls, and " "explore historical developments. Finally, we shall give the reasons for " "many major design decisions." msgstr "" "Разделы с 2.3 по 2.14 представляют собой вводный материал, относящийся к " "главам с 3 по 14. Мы определим понятия, коснемся основных системных вызовов " "и рассмотрим исторические разработки. Наконец, мы расскажем о причинах " "многих ключевых архитектурных решений." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:71 #, no-wrap msgid "The Kernel" msgstr "Ядро" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:78 msgid "" "The _kernel_ is the part of the system that runs in protected mode and " "mediates access by all user programs to the underlying hardware (e.g., CPU, " "disks, terminals, network links) and software constructs (e.g., filesystem, " "network protocols). The kernel provides the basic system facilities; it " "creates and manages processes, and provides functions to access the " "filesystem and communication facilities. These functions, called _system " "calls_ appear to user processes as library subroutines. These system calls " "are the only interface that processes have to these facilities. Details of " "the system-call mechanism are given in Chapter 3, as are descriptions of " "several kernel mechanisms that do not execute as the direct result of a " "process doing a system call." msgstr "" "_Ядро_ является частью системы, которая работает в защищенном режиме и " "управляет доступом всех пользовательских программ к низкоуровнему " "аппаратному обеспечению (к примеру, ЦПУ, дискам, терминалам, сетевым связям) " "и программным компонентам (к примеру, файловой системе, сетевым протоколам). " "Ядро предоставляет основные подсистемы; оно создает процессы и управляет " "ими, предоставляет функции для доступа к файловой системе и службам связи. " "Такие функции, называемые _системными вызовами_, доступны процессам " "пользователей в виде библиотечных подпрограмм. Эти системные вызовы являются " "единственным способом доступа к этим подсистемам. Подробно механизм работы " "системных вызовов дается в Главе 3, вместе с описанием некоторых механизмов " "ядра, работа которых не является прямым результатом процесса, выполняющего " "системный вызов." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:84 msgid "" "A _kernel_ in traditional operating-system terminology, is a small nucleus " "of software that provides only the minimal facilities necessary for " "implementing additional operating-system services. In contemporary research " "operating systems -- such as Chorus crossref:design-44bsd[biblio-rozier, " "[Rozier et al, 1988]], Mach crossref:design-44bsd[biblio-accetta, [Accetta " "et al, 1986]], Tunis crossref:design-44bsd[biblio-ewens, [Ewens et al, " "1985]], and the V Kernel crossref:design-44bsd[biblio-cheriton, [Cheriton, " "1988]] -- this division of functionality is more than just a logical one. " "Services such as filesystems and networking protocols are implemented as " "client application processes of the nucleus or kernel." msgstr "" "_Ядро_, по традиционной терминологии операционных систем, является маленьким " "куском программного обеспечения, которое предоставляет только минимальный " "набор подсистем, необходимый для реализации дополнительных служб " "операционной системы. В современных исследовательских операционных системах " "— таких, как Chorus crossref:design-44bsd[biblio-rozier, [Rozier et al, " "1988]], Mach crossref:design-44bsd[biblio-accetta, [Accetta et al, 1986]], " "Tunis crossref:design-44bsd[biblio-ewens, [Ewens et al, 1985]], и V Kernel " "crossref:design-44bsd[biblio-cheriton, [Cheriton, 1988]] - такое разделение " "функциональности выполнено не только логически. Такие службы, как файловые " "системы и сетевые протоколы, выполнены в виде прикладных процессов клиентов " "ядра или микроядра." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:93 msgid "" "The 4.4BSD kernel is not partitioned into multiple processes. This basic " "design decision was made in the earliest versions of UNIX. The first two " "implementations by Ken Thompson had no memory mapping, and thus made no " "hardware-enforced distinction between user and kernel space " "crossref:design-44bsd[biblio-ritchie, [Ritchie, 1988]]. A message-passing " "system could have been implemented as readily as the actually implemented " "model of kernel and user processes. The monolithic kernel was chosen for " "simplicity and performance. And the early kernels were small; the inclusion " "of facilities such as networking into the kernel has increased its size. " "The current trend in operating-systems research is to reduce the kernel size " "by placing such services in user space." msgstr "" "Ядро 4.4BSD не разбивается на несколько процессов. Это основополагающее " "архитектурное решение было сделано в самых ранних версиях UNIX. В первых " "двух реализациях Кена Томпсона (Ken Thompson) не было отображаемой памяти, и " "поэтому не было аппаратного различия между адресным пространством " "пользователя и ядра crossref:design-44bsd[biblio-ritchie, [Ritchie, 1988]]. " "Могла бы быть придумана система обмена сообщениями как реально реализуемая " "модель процессов ядра и пользователя. Для простоты и увеличения " "производительности было выбрано монолитное ядро. К тому же ранние ядра были " "маленькими; включение таких подсистем, как сетевые коммуникации, в ядро " "увеличило его размер. Современные тенденции в области операционных систем " "сводятся к уменьшению размера ядра за счет перевода таких служб в " "пользовательское адресное пространство." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:97 msgid "" "Users ordinarily interact with the system through a command-language " "interpreter, called a _shell_, and perhaps through additional user " "application programs. Such programs and the shell are implemented with " "processes. Details of such programs are beyond the scope of this book, " "which instead concentrates almost exclusively on the kernel." msgstr "" "Пользователи обычно общаются с системой через интерпретатор языка команд, " "называемый оболочкой (_shell_), и, может быть, через дополнительные " "прикладные пользовательские программы. Такие программы и оболочка " "реализованы в виде процессов. Подробное описание таких программ выходит за " "рамки этой книги, которая практически полностью посвящена работе ядра." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:100 msgid "" "Sections 2.3 and 2.4 describe the services provided by the 4.4BSD kernel, " "and give an overview of the latter's design. Later chapters describe the " "detailed design and implementation of these services as they appear in " "4.4BSD." msgstr "" "В разделах 2.3 и 2.4 описываются сервисы, предоставляемые ядром 4.4BSD, и " "дается обзор их архитектуры. Последующие главы описывают подробности " "архитектуры и реализации этих сервисов в 4.4BSD." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:102 #, no-wrap msgid "Kernel Organization" msgstr "Организация ядра" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:105 msgid "" "In this section, we view the organization of the 4.4BSD kernel in two ways:" msgstr "" "В этом разделе мы рассматриваем организацию ядра 4.4BSD с двух точек зрения:" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:108 msgid "" "As a static body of software, categorized by the functionality offered by " "the modules that make up the kernel" msgstr "" "Как статический блок программного обеспечения, категоризуемый по " "функциональности модулей, составляющих ядро" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:109 msgid "" "By its dynamic operation, categorized according to the services provided to " "users" msgstr "" "В его динамике, категоризуемой по услугам, предоставляемым пользователям" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:112 msgid "" "The largest part of the kernel implements the system services that " "applications access through system calls. In 4.4BSD, this software has been " "organized according to the following:" msgstr "" "Самая большая часть ядра реализует системные услуги, к которым приложения " "обращаются через системные вызовы. В 4.4BSD это программное обеспечение " "организуется по следующим принципам:" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:114 msgid "" "Basic kernel facilities: timer and system-clock handling, descriptor " "management, and process management" msgstr "" "Базовые подсистемы ядра: обработка таймеров и системного таймера, управление " "дескрипторами и процессами" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:115 msgid "Memory-management support: paging and swapping" msgstr "Поддержка управления памятью: подкачка и выгрузка" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:116 msgid "" "Generic system interfaces: the I/O, control, and multiplexing operations " "performed on descriptors" msgstr "" "Общесистемные интерфейсы: ввод/вывод, управление и мультиплексирование " "операций, выполняемых над дескрипторами" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:117 msgid "" "The filesystem: files, directories, pathname translation, file locking, and " "I/O buffer management" msgstr "" "Файловая система: файлы, каталоги, преобразование маршрутов, блокировка " "файлов и управление буфером ввода/вывода" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:118 msgid "" "Terminal-handling support: the terminal-interface driver and terminal line " "disciplines" msgstr "" "Поддержка работы с терминалами: драйвер терминального интерфейса и режимы " "работы терминального канала" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:119 msgid "Interprocess-communication facilities: sockets" msgstr "Подсистемы межпроцессного взаимодействия: сокеты" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:120 msgid "" "Support for network communication: communication protocols and generic " "network facilities, such as routing" msgstr "" "Поддержка сетевых коммуникаций: коммуникационные протоколы и общесетевые " "подсистемы, такие, как маршрутизация" #. type: Block title #: documentation/content/en/books/design-44bsd/_index.adoc:121 #, no-wrap msgid "Machine-independent software in the 4.4BSD kernel" msgstr "Машинно-независимое программное обеспечение в ядре 4.4BSD" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:125 #: documentation/content/en/books/design-44bsd/_index.adoc:165 #, no-wrap msgid "Category" msgstr "Категория" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:125 #: documentation/content/en/books/design-44bsd/_index.adoc:165 #, no-wrap msgid "Lines of code" msgstr "Строк кода" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:126 #: documentation/content/en/books/design-44bsd/_index.adoc:166 #, no-wrap msgid "Percentage of kernel" msgstr "Процент от строк ядра" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:126 #, no-wrap msgid "headers" msgstr "заголовки" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:126 #, no-wrap msgid "9,393" msgstr "9,393" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:127 #, no-wrap msgid "4.6" msgstr "4.6" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:127 #, no-wrap msgid "initialization" msgstr "инициализация" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:127 #, no-wrap msgid "1,107" msgstr "1,107" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:128 #, no-wrap msgid "0.6" msgstr "0.6" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:128 #, no-wrap msgid "kernel facilities" msgstr "подсистемы ядра" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:128 #, no-wrap msgid "8,793" msgstr "8,793" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:129 #, no-wrap msgid "4.4" msgstr "4.4" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:129 #, no-wrap msgid "generic interfaces" msgstr "универсальные интерфейсы" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:129 #, no-wrap msgid "4,782" msgstr "4,782" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:130 #, no-wrap msgid "2.4" msgstr "2.4" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:130 #, no-wrap msgid "interprocess communication" msgstr "межпроцессное взаимодействие" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:130 #, no-wrap msgid "4,540" msgstr "4,540" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:131 #: documentation/content/en/books/design-44bsd/_index.adoc:136 #, no-wrap msgid "2.2" msgstr "2.2" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:131 #, no-wrap msgid "terminal handling" msgstr "работа с терминалом" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:131 #, no-wrap msgid "3,911" msgstr "3,911" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:132 #, no-wrap msgid "1.9" msgstr "1.9" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:132 #: documentation/content/en/books/design-44bsd/_index.adoc:169 #, no-wrap msgid "virtual memory" msgstr "Виртуальная память" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:132 #, no-wrap msgid "11,813" msgstr "11,813" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:133 #, no-wrap msgid "5.8" msgstr "5.8" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:133 #, no-wrap msgid "vnode management" msgstr "управление vnode" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:133 #, no-wrap msgid "7,954" msgstr "7,954" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:134 #, no-wrap msgid "3.9" msgstr "3.9" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:134 #, no-wrap msgid "filesystem naming" msgstr "имена в файловой системы" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:134 #, no-wrap msgid "6,550" msgstr "6,550" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:135 #, no-wrap msgid "3.2" msgstr "3.2" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:135 #, no-wrap msgid "fast filestore" msgstr "быстрое хранилище файлов" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:135 #, no-wrap msgid "4,365" msgstr "4,365" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:136 #, no-wrap msgid "log-structure filestore" msgstr "логическая структура файлового хранилища" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:136 #, no-wrap msgid "4,337" msgstr "4,337" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:137 #: documentation/content/en/books/design-44bsd/_index.adoc:139 #, no-wrap msgid "2.1" msgstr "2.1" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:137 #, no-wrap msgid "memory-based filestore" msgstr "хранилище файлов в памяти" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:137 #, no-wrap msgid "645" msgstr "645" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:138 #, no-wrap msgid "0.3" msgstr "0.3" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:138 #, no-wrap msgid "cd9660 filesystem" msgstr "cd9660 файловая система" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:138 #, no-wrap msgid "4,177" msgstr "4,177" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:139 #, no-wrap msgid "miscellaneous filesystems (10)" msgstr "различные файловые системы (10)" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:139 #, no-wrap msgid "12,695" msgstr "12,695" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:140 #, no-wrap msgid "6.3" msgstr "6.3" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:140 #, no-wrap msgid "network filesystem" msgstr "сетевая файловая система" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:140 #, no-wrap msgid "17,199" msgstr "17,199" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:141 #, no-wrap msgid "8.5" msgstr "8.5" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:141 #, no-wrap msgid "network communication" msgstr "сетевое взаимодействие" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:141 #, no-wrap msgid "8,630" msgstr "8,630" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:142 #, no-wrap msgid "4.3" msgstr "4.3" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:142 #, no-wrap msgid "internet protocols" msgstr "интернет-протоколы" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:142 #, no-wrap msgid "11,984" msgstr "11,984" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:143 #, no-wrap msgid "5.9" msgstr "5.9" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:143 #, no-wrap msgid "ISO protocols" msgstr "протоколы ISO" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:143 #, no-wrap msgid "23,924" msgstr "23,924" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:144 #, no-wrap msgid "11.8" msgstr "11.8" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:144 #, no-wrap msgid "X.25 protocols" msgstr "протоколы X.25" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:144 #, no-wrap msgid "10,626" msgstr "10,626" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:145 #, no-wrap msgid "5.3" msgstr "5.3" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:145 #, no-wrap msgid "XNS protocols" msgstr "протоколы XNS" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:145 #, no-wrap msgid "5,192" msgstr "5,192" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:146 #, no-wrap msgid "2.6" msgstr "2.6" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:149 msgid "" "Most of the software in these categories is machine independent and is " "portable across different hardware architectures." msgstr "" "Большая часть программного обеспечения в этих категориях является машинно-" "независимой и переносима между различными аппаратными архитектурами." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:154 msgid "" "The machine-dependent aspects of the kernel are isolated from the mainstream " "code. In particular, none of the machine-independent code contains " "conditional code for specific architecture. When an architecture-dependent " "action is needed, the machine-independent code calls an architecture-" "dependent function that is located in the machine-dependent code. The " "software that is machine dependent includes" msgstr "" "Машинно-зависимые аспекты ядра отделены от основного кода. В частности, ни в " "одной части машинно-независимого кода не содержится кода, зависимого от " "конкретной архитектуры. Когда требуется произвести действия, зависимые от " "архитектуры, машинно-независимый код вызывает функцию, зависимую от " "архитектуры машины, которая находится в машинно-зависимой части кода. " "Машинно-зависимое программное обеспечение включает в себя" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:156 msgid "Low-level system-startup actions" msgstr "Низкоуровневые действия по запуску системы" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:157 msgid "Trap and fault handling" msgstr "Обработка исключительных ситуаций и прерываний" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:158 msgid "Low-level manipulation of the run-time context of a process" msgstr "Низкоуровневые манипуляции процессом во время работы" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:159 msgid "Configuration and initialization of hardware devices" msgstr "Конфигурация и инициализация аппаратных устройств" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:160 msgid "Run-time support for I/O devices" msgstr "Поддержка устройств ввода/вывода во время работы" #. type: Block title #: documentation/content/en/books/design-44bsd/_index.adoc:161 #, no-wrap msgid "Machine-dependent software for the HP300 in the 4.4BSD kernel" msgstr "Машинно-зависимое программное обеспечение для HP300 в ядре 4.4BSD" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:166 #, no-wrap msgid "machine dependent headers" msgstr "заголовочные файлы, зависимые от машины" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:166 #, no-wrap msgid "1,562" msgstr "1,562" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:167 #, no-wrap msgid "0.8" msgstr "0.8" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:167 #, no-wrap msgid "device driver headers" msgstr "заголовочные файлы драйверов устройств" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:167 #, no-wrap msgid "3,495" msgstr "3,495" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:168 #, no-wrap msgid "1.7" msgstr "1.7" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:168 #, no-wrap msgid "device driver source" msgstr "исходный код драйверов устройств" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:168 #, no-wrap msgid "17,506" msgstr "17,506" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:169 #, no-wrap msgid "8.7" msgstr "8.7" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:169 #, no-wrap msgid "3,087" msgstr "3,087" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:170 #: documentation/content/en/books/design-44bsd/_index.adoc:172 #, no-wrap msgid "1.5" msgstr "1.5" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:170 #, no-wrap msgid "other machine dependent" msgstr "код, зависящий от других машин" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:170 #, no-wrap msgid "6,287" msgstr "6,287" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:171 #, no-wrap msgid "3.1" msgstr "3.1" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:171 #, no-wrap msgid "routines in assembly language" msgstr "подпрограммы на языке ассемблера" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:171 #, no-wrap msgid "3,014" msgstr "3,014" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:172 #, no-wrap msgid "HP/UX compatibility" msgstr "совместимость с HP/UX" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:172 #, no-wrap msgid "4,683" msgstr "4,683" #. type: Table #: documentation/content/en/books/design-44bsd/_index.adoc:173 #, no-wrap msgid "2.3" msgstr "2.3" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:179 msgid "" "crossref:design-44bsd[table-mach-indep, Machine-independent software in the " "4.4BSD kernel] summarizes the machine-independent software that constitutes " "the 4.4BSD kernel for the HP300. The numbers in column 2 are for lines of C " "source code, header files, and assembly language. Virtually all the " "software in the kernel is written in the C programming language; less than 2 " "percent is written in assembly language. As the statistics in " "crossref:design-44bsd[table-mach-dep, Machine-dependent software in the " "4.4BSD kernel] show, the machine-dependent software, excluding HP/UX and " "device support, accounts for a minuscule 6.9 percent of the kernel." msgstr "" "crossref:design-44bsd[table-mach-indep, Машинно-независимое программное " "обеспечение в ядре 4.4BSD] показывает статистику машинно-независимого кода, " "который составляет ядро 4.4BSD для HP300. Числа во второй колонке обозначают " "количество строк исходного кода на языке C, заголовочных файлов и " "ассемблерного кода. Практически весь код ядра написан на языке " "программирования C; менее двух процентов написано на языке ассемблера. Как " "показывает статистика в crossref:design-44bsd[table-mach-dep, Машинно-" "зависимое программное обеспечение для HP300 в ядре 4.4BSD], машинно-" "зависимый код, не включающий поддержку HP/UX и устройств, составляет менее " "6.9 процента ядра." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:185 msgid "" "Only a small part of the kernel is devoted to initializing the system. This " "code is used when the system is _bootstrapped_ into operation and is " "responsible for setting up the kernel hardware and software environment (see " "Chapter 14). Some operating systems (especially those with limited physical " "memory) discard or _overlay_ the software that performs these functions " "after that software has been executed. The 4.4BSD kernel does not reclaim " "the memory used by the startup code because that memory space is barely 0.5 " "percent of the kernel resources used on a typical machine. Also, the " "startup code does not appear in one place in the kernel -- it is scattered " "throughout, and it usually appears in places logically associated with what " "is being initialized." msgstr "" "Лишь малая часть ядра отвечает за инициализацию системы. Этот код " "используется при _начальной загрузке_ системы для перехода в рабочий режим и " "отвечает за настройку аппаратного и программного окружения ядра (обратитесь " "к Главе 14). Некоторые операционные системы (особенно те, что ограничены " "объемом физической памяти) выполняют действия по выгрузке или _перекрытию_ " "программного кода, выполняющего эти функции, после окончания его работы. " "Ядро 4.4BSD не работает повторно с памятью, использованной начальным кодом, " "потому что этот объем памяти составляет менее 0.5 процентов ресурсов ядра, " "используемых на типичной машине. Также начальный код не находится только в " "одном месте ядра - он рассредоточен везде, и обычно появляется там, где " "логически связан с объектом инициализации." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:187 #, no-wrap msgid "Kernel Services" msgstr "Службы ядра" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:197 msgid "" "The boundary between the kernel- and user-level code is enforced by hardware-" "protection facilities provided by the underlying hardware. The kernel " "operates in a separate address space that is inaccessible to user " "processes. Privileged operations -- such as starting I/O and halting the " "central processing unit (CPU) -- are available to only the kernel. " "Applications request services from the kernel with _system calls_. System " "calls are used to cause the kernel to execute complicated operations, such " "as writing data to secondary storage, and simple operations, such as " "returning the current time of day. All system calls appear _synchronous_ to " "applications: The application does not run while the kernel does the actions " "associated with a system call. The kernel may finish some operations " "associated with a system call after it has returned. For example, a _write_ " "system call will copy the data to be written from the user process to a " "kernel buffer while the process waits, but will usually return from the " "system call before the kernel buffer is written to the disk." msgstr "" "Разграничение между кодом уровней ядра и пользователя обеспечивается " "аппаратными методами, предоставляемыми оборудованием. Ядро работает в " "отдельном адресном пространстве, которое недоступно процессам пользователя. " "Привилегированные операции - такие, как осуществление ввода/вывода и " "остановка модуля центрального процессора (CPU) - доступны только ядру. " "Приложения делают запросы ядру на доступ к его сервисам при помощи " "_системных вызовов_. Системные вызовы используются для указания ядру на " "выполнение как сложных операций, таких, как запись данных во вторичный " "носитель, так и простых, таких, как получение текущего времени. Все " "системные вызовы выполняются _синхронно_ с приложением: Приложение не будет " "продолжать работу, пока ядро не выполнит действия, соответствующие " "системному вызову. Ядро может завершить некоторые операции, связанные с " "системным вызовом, после его окончания. Например, системный вызов _write_ " "будет копировать записываемые данные от пользовательского процесса в буфер " "ядра, пока процесс находится в ожидании, но, как правило, будет немедленно " "завершаться до того, как буфер ядра реально будет записан на диск." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:206 msgid "" "A system call usually is implemented as a hardware trap that changes the " "CPU's execution mode and the current address-space mapping. Parameters " "supplied by users in system calls are validated by the kernel before being " "used. Such checking ensures the integrity of the system. All parameters " "passed into the kernel are copied into the kernel's address space, to ensure " "that validated parameters are not changed as a side effect of the system " "call. System-call results are returned by the kernel, either in hardware " "registers or by their values being copied to user-specified memory " "addresses. Like parameters passed into the kernel, addresses used for the " "return of results must be validated to ensure that they are part of an " "application's address space. If the kernel encounters an error while " "processing a system call, it returns an error code to the user. For the C " "programming language, this error code is stored in the global variable " "_errno_, and the function that executed the system call returns the value -1." msgstr "" "Системный вызов обычно реализуется как аппаратное прерывание, которое " "изменяет режим работы CPU и текущее отображение адресного пространства. " "Параметры, передаваемые пользователями системным вызовам, перед " "использованием проверяются ядром. Такая проверка обеспечивает целостность " "системы. Все параметры, передаваемые в ядро, копируются в адресное " "пространство ядра, для того, чтобы проверенные параметры не могли быть " "изменены в результате побочного действия системного вызова. Результаты " "выполнения системного вызова возвращаются ядром либо в аппаратных регистрах, " "либо копированием их значений в области памяти, указанные пользователем. Как " "и параметры, переданные в ядро, адреса, используемые для возвращения " "результатов, должны быть проверены на то, что они являются частью адресного " "пространства приложения. Если при обработке системного вызова ядром " "возникает ошибка, код ошибки возвращается пользователю. В случае языка " "программирования C код этой ошибки сохраняется в глобальной переменной " "_errno_, а функция, соответствующая системному вызову, возвращает в качестве " "результата значение -1." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:211 msgid "" "User applications and the kernel operate independently of each other. " "4.4BSD does not store I/O control blocks or other operating-system-related " "data structures in the application's address space. Each user-level " "application is provided an independent address space in which it executes. " "The kernel makes most state changes, such as suspending a process while " "another is running, invisible to the processes involved." msgstr "" "Пользовательские приложения и ядро работают независимо друг от друга. 4.4BSD " "не хранит управляющие блоки ввода/вывода и другие связанные с операционной " "системой структуры данных в адресном пространстве приложения. Каждому " "пользовательскому приложению предоставляется независимое адресное " "пространство, в котором оно и выполняется. Ядро выполняет большинство " "управляющих действий, таких, как приостановка процесса на время выполнения " "другого, незаметно для участвующих процессов." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:213 #, no-wrap msgid "Process Management" msgstr "Управление процессами" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:222 msgid "" "4.4BSD supports a multitasking environment. Each task or thread of " "execution is termed a _process_. The _context_ of a 4.4BSD process consists " "of user-level state, including the contents of its address space and the run-" "time environment, and kernel-level state, which includes scheduling " "parameters, resource controls, and identification information. The context " "includes everything used by the kernel in providing services for the " "process. Users can create processes, control the processes' execution, and " "receive notification when the processes' execution status changes. Every " "process is assigned a unique value, termed a _process identifier_ (PID). " "This value is used by the kernel to identify a process when reporting status " "changes to a user, and by a user when referencing a process in a system call." msgstr "" "4.4BSD поддерживает многозадачность. Каждая задача или выполняющийся поток " "называется _процессом_. _Контекст_ процесса 4.4BSD состоит из состояния " "пользовательского уровня, включая содержимое его адресного пространства и " "окружения времени выполнения, и состояния уровня ядра, в который включаются " "параметры планировщика задач, управляющие ресурсы и идентифицирующая " "информация. В контекст включается все, что используется ядром при " "предоставлении своих сервисов процессу. Пользователи могут создавать " "процессы, управлять их выполнением и получать уведомления при изменении " "состояния выполнения процессов. Каждому процессу назначается уникальное " "число, называемое _идентификатором процесса_ (PID). Это число используется " "ядром для идентификации процесса при сообщении пользователю об изменении его " "состояния, и пользователем для указания процесса в системном вызове." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:227 msgid "" "The kernel creates a process by duplicating the context of another process. " "The new process is termed a _child process_ of the original _parent process_ " "The context duplicated in process creation includes both the user-level " "execution state of the process and the process's system state managed by the " "kernel. Important components of the kernel state are described in Chapter 4." msgstr "" "Ядро создает процесс, дублируя контекст другого процесса. Новый процесс " "считается _порожденным процессом_ исходного _родительского процесса_. " "Контекст, копируемый в ходе создания процесса, включает как состояние " "выполнения процесса уровня пользователя, так и системное состояние процесса, " "управляемое ядром. Важные компоненты состояния ядра описаны в Главе 4." #. type: Block title #: documentation/content/en/books/design-44bsd/_index.adoc:229 #, no-wrap msgid "Process lifecycle" msgstr "Жизненный цикл процесса" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:231 msgid "image:fig1.png[Process lifecycle]" msgstr "image:fig1.png[Жизненный цикл процесса]" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:238 msgid "" "The process lifecycle is depicted in crossref:design-44bsd[fig-process-" "lifecycle,Process lifecycle]. A process may create a new process that is a " "copy of the original by using the _fork_ system call. The _fork_ call " "returns twice: once in the parent process, where the return value is the " "process identifier of the child, and once in the child process, where the " "return value is 0. The parent-child relationship induces a hierarchical " "structure on the set of processes in the system. The new process shares all " "its parent's resources, such as file descriptors, signal-handling status, " "and memory layout." msgstr "" "Жизненный цикл процесса изображен на рисунке crossref:design-44bsd[fig-" "process-lifecycle,Жизненный цикл процесса]. Процесс может создать новый " "процесс, который является копией исходного процесса с помощью системного " "вызова _fork_. Возврат из вызова _fork_ происходит два раза: один раз в " "родительском процессе, в котором возвращаемое значение является " "идентификатором порожденного процесса, и второй раз в порожденном процессе, " "в котором возвращаемое значение равно 0. Связь родитель-потомок порождает " "иерархическую структуру процессов в системе. Новый процесс имеет доступ ко " "всем ресурсам его родителя, таким, как файловые дескрипторы, состояние " "обработки сигналов и распределение памяти." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:242 msgid "" "Although there are occasions when the new process is intended to be a copy " "of the parent, the loading and execution of a different program is a more " "useful and typical action. A process can overlay itself with the memory " "image of another program, passing to the newly created image a set of " "parameters, using the system call _execve_. One parameter is the name of a " "file whose contents are in a format recognized by the system -- either a " "binary-executable file or a file that causes the execution of a specified " "interpreter program to process its contents." msgstr "" "Хотя есть ситуации, когда процесс должен быть копией своего родителя, " "наиболее типичным и полезным действием является загрузка и выполнение другой " "программы. Процесс может заместить себя образом памяти другой программы, " "передавая вновь созданному образу набор параметров, при помощи системного " "вызова _execve_. Одним из параметров является имя файла, содержимое которого " "имеет формате, распознаваемый системой - это либо двоичный выполняемый файл, " "либо файл, который приводит к запуску указанной программы интерпретации для " "обработки его содержимого." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:246 msgid "" "A process may terminate by executing an _exit_ system call, sending 8 bits " "of exit status to its parent. If a process wants to communicate more than a " "single byte of information with its parent, it must either set up an " "interprocess-communication channel using pipes or sockets, or use an " "intermediate file. Interprocess communication is discussed extensively in " "Chapter 11." msgstr "" "Процесс может завершить работу, выполнив системный вызов _exit_, посылающий " "8-битовое значение состояния завершения своему родителю. Если процесс хочет " "передать родительскому процессу информацию, превышающую один байт, он должен " "либо создать канал межпроцессных коммуникаций при помощи конвейеров или " "сокетов, или при помощи промежуточного файла. Коммуникации между процессами " "подробно обсуждаются в Главе 11." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:251 msgid "" "A process can suspend execution until any of its child processes terminate " "using the _wait_ system call, which returns the PID and exit status of the " "terminated child process. A parent process can arrange to be notified by a " "signal when a child process exits or terminates abnormally. Using the " "_wait4_ system call, the parent can retrieve information about the event " "that caused termination of the child process and about resources consumed by " "the process during its lifetime. If a process is orphaned because its " "parent exits before it is finished, then the kernel arranges for the child's " "exit status to be passed back to a special system process _init_: see " "Sections 3.1 and 14.6)." msgstr "" "Процесс может приостановить выполнение до тех пор, пока не завершит работу " "любой из порожденных им процессов, при помощи системного вызова _wait_, " "который возвращает PID и статус завершения выполненного дочернего процесса. " "Родительский процесс может быть настроен на получение сигнала в случае, " "когда порожденный процесс завершает работу или аварийно прекращает " "выполнение. При помощи системного вызова _wait4_ родитель может получить " "информацию о событии, приведшем к завершению порожденного процесса и о " "ресурсах, использованных процессом за время его работы. Если процесс " "становится сиротой из-за того, что процесс, его породивший, завершил работу " "до окончания работы потомка, то ядро перенаправляет состояние завершения " "порожденного процесса особому системному процессу _init_: обратитесь к " "разделам 3.1 и 14.6)." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:253 msgid "" "The details of how the kernel creates and destroys processes are given in " "Chapter 5." msgstr "" "Подробное описание того, как ядро создает и уничтожает процессы, дается в " "Главе 5." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:257 msgid "" "Processes are scheduled for execution according to a _process-priority_ " "parameter. This priority is managed by a kernel-based scheduling " "algorithm. Users can influence the scheduling of a process by specifying a " "parameter (_nice_) that weights the overall scheduling priority, but are " "still obligated to share the underlying CPU resources according to the " "kernel's scheduling policy." msgstr "" "Планирование выполнения процессов осуществляется согласно параметру " "_приоритетности процесса_. Этот приоритет управляется алгоритмом " "планирования задач в ядре. Пользователи могут влиять на выполнение процесса, " "задавая этот параметр (_nice_), который влияет на суммарный приоритет, но " "ограничен использованием ресурсов CPU согласно алгоритму планировщика задач " "ядра." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:258 #, no-wrap msgid "Signals" msgstr "Сигналы" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:267 msgid "" "The system defines a set of _signals_ that may be delivered to a process. " "Signals in 4.4BSD are modeled after hardware interrupts. A process may " "specify a user-level subroutine to be a _handler_ to which a signal should " "be delivered. When a signal is generated, it is blocked from further " "occurrence while it is being _caught_ by the handler. Catching a signal " "involves saving the current process context and building a new one in which " "to run the handler. The signal is then delivered to the handler, which can " "either abort the process or return to the executing process (perhaps after " "setting a global variable). If the handler returns, the signal is unblocked " "and can be generated (and caught) again." msgstr "" "В системе определен набор _сигналов_, которые могут быть отправлены " "процессу. Сигналы в 4.4BSD сделаны по образу аппаратных прерываний. Процесс " "может определить пользовательскую подпрограмму, которая будет являться " "_обработчиком_, и которой должен будет перенаправляться сигнал. Когда сигнал " "генерируется, он блокируется от повторного появления до тех пор, пока не " "будет _перехвачен_ обработчиком. Перехват сигнала включает в себя сохранение " "контекста текущего процесса и построение нового, в котором запускается " "обработчик. Затем сигнал направляется обработчику, который может либо " "прервать процесс, либо передать управление обратно выполняемому процессу " "(может быть, после установки значения глобальной переменной). Если " "обработчик возвратил управление, сигнал разблокировывается и может быть " "сгенерирован (и получен) снова." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:271 msgid "" "Alternatively, a process may specify that a signal is to be _ignored_, or " "that a default action, as determined by the kernel, is to be taken. The " "default action of certain signals is to terminate the process. This " "termination may be accompanied by creation of a _core file_ that contains " "the current memory image of the process for use in postmortem debugging." msgstr "" "Либо процесс может определить, что сигнал будет _игнорироваться_ или будет " "выполняться действие по умолчанию, определяемое ядром. Действием по " "умолчанию для некоторых сигналов является прекращение процесса. Это " "завершение работы может сопровождаться созданием _файла дампа_, содержащего " "текущий образ памяти процесса для использования в последующей отладке." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:274 msgid "" "Some signals cannot be caught or ignored. These signals include _SIGKILL_, " "which kills runaway processes, and the job-control signal _SIGSTOP_." msgstr "" "Некоторые сигналы не могут быть перехвачены или проигнорированы. К таким " "сигналам относятся _SIGKILL_, прерывающий неуправляемый процесс, и сигнал " "управления заданиями _SIGSTOP_." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:279 msgid "" "A process may choose to have signals delivered on a special stack so that " "sophisticated software stack manipulations are possible. For example, a " "language supporting coroutines needs to provide a stack for each coroutine. " "The language run-time system can allocate these stacks by dividing up the " "single stack provided by 4.4BSD. If the kernel does not support a separate " "signal stack, the space allocated for each coroutine must be expanded by the " "amount of space required to catch a signal." msgstr "" "Процесс может выбрать получение сигналов в специальный стек для выполнения " "хитроумных программных манипуляций стеком. Например, подпрограммам поддержки " "языка нужно иметь стек для каждой подпрограммы. Система времени выполнения " "языка может выделять эти стеки, разделяя единственный стек, предоставляемый " "в 4.4BSD. Если ядро не поддерживает отдельный стек сигналов, то " "пространство, выделяемое каждой подпрограмме, должно быть расширено на " "объем, требуемый для перехвата сигнала." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:284 msgid "" "All signals have the same _priority_. If multiple signals are pending " "simultaneously, the order in which signals are delivered to a process is " "implementation specific. Signal handlers execute with the signal that " "caused their invocation to be blocked, but other signals may yet occur. " "Mechanisms are provided so that processes can protect critical sections of " "code against the occurrence of specified signals." msgstr "" "Все сигналы имеют один и тот же _приоритет_. Если обработки ожидают " "несколько сигналов, то порядок их направления процессу зависит от " "реализации. Обработчики сигналов, выполняемые по сигналу, который их вызвал, " "блокируются, но при этом могут быть сгенерированы дополнительные сигналы. " "Имеется механизм, позволяющий защитить критический участок кода от появления " "заданных сигналов." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:286 msgid "" "The detailed design and implementation of signals is described in Section " "4.7." msgstr "" "Подробное описание архитектуры и реализации механизма сигналов дается в " "Разделе 4.7." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:287 #, no-wrap msgid "Process Groups and Sessions" msgstr "Группы управления и сеансы" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:294 msgid "" "Processes are organized into _process groups_. Process groups are used to " "control access to terminals and to provide a means of distributing signals " "to collections of related processes. A process inherits its process group " "from its parent process. Mechanisms are provided by the kernel to allow a " "process to alter its process group or the process group of its descendants. " "Creating a new process group is easy; the value of a new process group is " "ordinarily the process identifier of the creating process." msgstr "" "Процессы организованы в _группы управления_. Группы управления используются " "для управления доступом к терминалам и для обеспечения передачи сигналов " "наборам связанных процессов. Процесс наследует группу управления от своего " "родительского процесса. Ядром обеспечиваются механизмы, позволяющие процессу " "изменять свою группу управления или группу управления своих наследников. " "Создание новой группы управления просто; значение, соответствующее новой " "группе управления, обычно является идентификатором создающего ее процесса." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:298 msgid "" "The group of processes in a process group is sometimes referred to as a " "_job_ and is manipulated by high-level system software, such as the shell. " "A common kind of job created by a shell is a _pipeline_ of several processes " "connected by pipes, such that the output of the first process is the input " "of the second, the output of the second is the input of the third, and so " "forth. The shell creates such a job by forking a process for each stage of " "the pipeline, then putting all those processes into a separate process group." msgstr "" "Группу процессов в группе управления иногда называют _заданием_ и оно " "управляется высокоуровневым системным программным обеспечением, таким, как " "командный процессор. Типичным примером задания, созданного командным " "процессором, является _конвейер_ из нескольких связанных процессов, так что " "выходной поток первого процесса является входным потоком для второго, " "выходной поток второго процесса является входным потоком для третьего, и так " "далее. Командный процессор создает такое задание, порождая процесс для " "каждого участка конвейера, а затем помещая все эти процессы в отдельную " "группу обработки." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:301 msgid "" "A user process can send a signal to each process in a process group, as well " "as to a single process. A process in a specific process group may receive " "software interrupts affecting the group, causing the group to suspend or " "resume execution, or to be interrupted or terminated." msgstr "" "Пользовательский процесс может послать сигнал как всем процессам в группе " "управления, так и конкретному процессу. Процесс в заданной группе управления " "может получать программные прерывания, отражающиеся на группе, приводящие к " "приостановке или продолжению выполнения, или к прерыванию или завершению " "работы." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:309 msgid "" "A terminal has a process-group identifier assigned to it. This identifier " "is normally set to the identifier of a process group associated with the " "terminal. A job-control shell may create a number of process groups " "associated with the same terminal; the terminal is the _controlling " "terminal_ for each process in these groups. A process may read from a " "descriptor for its controlling terminal only if the terminal's process-group " "identifier matches that of the process. If the identifiers do not match, " "the process will be blocked if it attempts to read from the terminal. By " "changing the process-group identifier of the terminal, a shell can arbitrate " "a terminal among several different jobs. This arbitration is called _job " "control_ and is described, with process groups, in Section 4.8." msgstr "" "Терминалу ставится в соответствие идентификатор группы управления. Этот " "идентификатор обычно равен идентификатору группы управления, соответствующей " "терминалу. Управляющий заданиями командный процессор может создать несколько " "групп управления, связанных с одним и тем же терминалом; терминал является " "_управляющим терминалом_ для каждого процесса в этих группах. Процесс может " "выполнять чтение из дескриптора своего управляющего терминала, если только " "идентификатор группы управления соответствует идентификатору группы этого " "процесса. Если идентификаторы не совпадают, процесс будет блокирован при " "попытке чтения с терминала. Изменяя идентификатор группы управления " "терминала, командный процессор может распределять терминал между несколькими " "различными заданиями. Такое распределение называется _управлением заданиями_ " "и описывается вместе с группами управления в Разделе 4.8." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:312 msgid "" "Just as a set of related processes can be collected into a process group, a " "set of process groups can be collected into a _session_. The main uses for " "sessions are to create an isolated environment for a daemon process and its " "children, and to collect together a user's login shell and the jobs that " "shell spawns." msgstr "" "Так же, как и наборы связанных процессов могут объединяться в группы " "управления, набор групп управления может быть объединен в _сеанс_. Основное " "назначение сеансов заключается создании изолированного окружения для " "процесса-даемона и порожденных им процессов, а также для объединения " "начального командного процессора пользователя и заданий, которые он " "порождает." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:314 #, no-wrap msgid "Memory Management" msgstr "Управление памятью" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:324 msgid "" "Each process has its own private address space. The address space is " "initially divided into three logical segments: _text_, _data_, and _stack_. " "The text segment is read-only and contains the machine instructions of a " "program. The data and stack segments are both readable and writable. The " "data segment contains the initialized and uninitialized data portions of a " "program, whereas the stack segment holds the application's run-time stack. " "On most machines, the stack segment is extended automatically by the kernel " "as the process executes. A process can expand or contract its data segment " "by making a system call, whereas a process can change the size of its text " "segment only when the segment's contents are overlaid with data from the " "filesystem, or when debugging takes place. The initial contents of the " "segments of a child process are duplicates of the segments of a parent " "process." msgstr "" "Каждый процесс имеет собственное адресное пространство. Адресное " "пространство изначально разделяется на три логических сегмента: _код_, " "_данные_ и _стек_. Сегмент кода доступен только для чтения и содержит " "машинные коды программы. Сегменты данных и стека оба доступны как для " "чтения, так и для записи. Сегмент данных содержит как инициализированные, " "так и неинициализированные области данных программы, когда как стековый " "сегмент представляет собой стек программы на этапе выполнения. На " "большинстве машин сегмент стека автоматически расширяется ядром в процессе " "работы программы. Процесс может расширять или уменьшать свой сегмент данных, " "выполняя системный вызов, когда как размер сегмента кода процесс может " "изменить только когда содержимое сегмента перекрывается данными файловой " "системы или в процессе отладки. Начальное содержимое сегментов порожденного " "процесса копируется из сегментов родительского процесса." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:332 msgid "" "The entire contents of a process address space do not need to be resident " "for a process to execute. If a process references a part of its address " "space that is not resident in main memory, the system _pages_ the necessary " "information into memory. When system resources are scarce, the system uses " "a two-level approach to maintain available resources. If a modest amount of " "memory is available, the system will take memory resources away from " "processes if these resources have not been used recently. Should there be a " "severe resource shortage, the system will resort to _swapping_ the entire " "context of a process to secondary storage. The _demand paging_ and " "_swapping_ done by the system are effectively transparent to processes. A " "process may, however, advise the system about expected future memory " "utilization as a performance aid." msgstr "" "Для выполнения процесса вовсе не обязательно постоянно хранить в памяти " "полное содержимое его адресного пространства. Если процесс обращается к " "области адресного пространства, которая не присутствует в оперативной " "памяти, то система _подгружает страницу_ с необходимой информацией в память. " "Когда возникает нехватка системных ресурсов, то система использует " "двухуровневый подход к управлению имеющимися ресурсами. Если не хватает " "памяти, то система будет забирать ресурсы памяти от процессов, если они " "давно не использовались. Если ресурсов не хватает очень сильно, то система " "будет прибегать к _выгрузке_ всего контекста процесса во вторичную " "подсистему хранения данных. _Постраничная подгрузка по требованию_ и " "_выгрузка_ выполняются системой абсолютно незаметно для процессов. Процесс " "может, однако, указать системе объем памяти, который будет использоваться, в " "качестве помощи." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:333 #, no-wrap msgid "BSD Memory-Management Design Decisions" msgstr "Решения BSD по архитектуре управления памятью" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:339 msgid "" "The support of large sparse address spaces, mapped files, and shared memory " "was a requirement for 4.2BSD. An interface was specified, called _mmap_, " "that allowed unrelated processes to request a shared mapping of a file into " "their address spaces. If multiple processes mapped the same file into their " "address spaces, changes to the file's portion of an address space by one " "process would be reflected in the area mapped by the other processes, as " "well as in the file itself. Ultimately, 4.2BSD was shipped without the " "_mmap_ interface, because of pressure to make other features, such as " "networking, available." msgstr "" "В 4.2BSD требовалось реализовать поддержку больших несвязанных адресных " "пространств, отображаемых в память файлов и совместно используемой памяти. " "Был спроектирован интерфейс, который назвали _mmap_, позволяющий несвязанным " "процессам запрашивать отображение в их адресное пространство файла в режиме " "совместного использования. Если несколько процессов отображают в свое " "адресное пространство один и тот же файл, то изменение адресного " "пространства процесса, соответствующего файлу, в одном процессе, будет " "отображено в области отображения этого файла в другом процессе, а также и в " "самом файле. Однако в конце концов 4.2BSD была выпущена без интерфейса " "_mmap_ из-за необходимости сделать в первую очередь другие возможности, " "такие, как работа с сетью." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:346 msgid "" "Further development of the _mmap_ interface continued during the work on " "4.3BSD. Over 40 companies and research groups participated in the " "discussions leading to the revised architecture that was described in the " "Berkeley Software Architecture Manual crossref:design-44bsd[biblio-" "mckusick-1, [McKusick et al, 1994]]. Several of the companies have " "implemented the revised interface crossref:design-44bsd[biblio-gingell, " "[Gingell et al, 1987]]." msgstr "" "Затем разработка интерфейса _mmap_ продолжалась во время работы над 4.3BSD. " "Более 40 компаний и исследовательских групп принимали участие в обсуждениях, " "которые привели к появлению обновленной концепции, описанной в Berkeley " "Software Architecture Manual crossref:design-44bsd[biblio-mckusick-1, " "[McKusick et al, 1994]]. Несколько компаний реализовали этот обновленный " "интерфейс crossref:design-44bsd[biblio-gingell, [Gingell et al, 1987]]." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:353 msgid "" "Once again, time pressure prevented 4.3BSD from providing an implementation " "of the interface. Although the latter could have been built into the " "existing 4.3BSD virtual-memory system, the developers decided not to put it " "in because that implementation was nearly 10 years old. Furthermore, the " "original virtual-memory design was based on the assumption that computer " "memories were small and expensive, whereas disks were locally connected, " "fast, large, and inexpensive. Thus, the virtual-memory system was designed " "to be frugal with its use of memory at the expense of generating extra disk " "traffic. In addition, the 4.3BSD implementation was riddled with VAX memory-" "management hardware dependencies that impeded its portability to other " "computer architectures. Finally, the virtual-memory system was not designed " "to support the tightly coupled multiprocessors that are becoming " "increasingly common and important today." msgstr "" "И снова сроки разработки не позволили включить в 4.3BSD реализацию этого " "интерфейса. Хотя позже она могла быть встроена в имеющуюся подсистему " "виртуальной памяти 4.3BSD, разработчики решили не включать ее сюда. потому " "что этой реализации было уже более 10 лет. Более того, оригинальная " "архитектура виртуальной памяти была основана на предположении, что " "компьютерная память мала и дорога, а диски подключены непосредственно к " "компьютеру, быстры и дешевы. Поэтому подсистема виртуальной памяти была " "разработана с упором на бережное использование памяти ценой более частых " "обращений к диску. Вдобавок реализация в 4.3BSD была пронизана зависимостями " "от аппаратной системы управления памятью машин VAX, что препятствовало ее " "переносу на другие аппаратные платформы. И наконец, подсистема виртуальной " "памяти не была предназначена для поддержки связных многопроцессорных систем, " "которые сейчас становятся все более распространенными и необходимыми." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:364 msgid "" "Attempts to improve the old implementation incrementally seemed doomed to " "failure. A completely new design, on the other hand, could take advantage " "of large memories, conserve disk transfers, and have the potential to run on " "multiprocessors. Consequently, the virtual-memory system was completely " "replaced in 4.4BSD. The 4.4BSD virtual-memory system is based on the Mach " "2.0 VM system crossref:design-44bsd[biblio-tevanian, [Tevanian, 1987]]. with " "updates from Mach 2.5 and Mach 3.0. It features efficient support for " "sharing, a clean separation of machine-independent and machine-dependent " "features, as well as (currently unused) multiprocessor support. Processes " "can map files anywhere in their address space. They can share parts of " "their address space by doing a shared mapping of the same file. Changes " "made by one process are visible in the address space of the other process, " "and also are written back to the file itself. Processes can also request " "private mappings of a file, which prevents any changes that they make from " "being visible to other processes mapping the file or being written back to " "the file itself." msgstr "" "Попытки постепенно усовершенствовать старую реализацию заведомо были " "обречены на неудачу. Полностью новая архитектура, с другой стороны, могла бы " "использовать большие объемы памяти, уменьшить дисковые операции и " "обеспечивать работу с несколькими процессорами. Наконец, система виртуальной " "памяти в 4.4BSD была полностью изменена. Система виртуальной памяти 4.4BSD " "основана на системе виртуальнй памяти (VM) crossref:design-44bsd[biblio-" "tevanian, [Tevanian, 1987]] с заимствованиями из Mach 2.5 и Mach 3.0. В ней " "была эффективная поддержка совместного использования, полное разделение " "машинно-зависимой и машинно-независимой частей, а также (сейчас не " "используемая) поддержка работы с несколькими процессорами. Процессы могут " "отображать файлы в любую область своего адресного пространства. Они могут " "совместно использовать части своих адресных пространств посредством " "отображения в память одного и того же файла. Изменения, сделанные одним " "процессом, видны в адресном пространстве другого процесса, а также " "записываются и в сам файл. Процессы могут также запрашивать эксклюзивное " "отображение файла в память, при котором любые изменения, сделанные " "процессом, не видны другим процессам, которые отображают файл в память и не " "записываются обратно в файл." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:370 msgid "" "Another issue with the virtual-memory system is the way that information is " "passed into the kernel when a system call is made. 4.4BSD always copies " "data from the process address space into a buffer in the kernel. For read " "or write operations that are transferring large quantities of data, doing " "the copy can be time consuming. An alternative to doing the copying is to " "remap the process memory into the kernel. The 4.4BSD kernel always copies " "the data for several reasons:" msgstr "" "Еще одной проблемой с системой виртуальной памяти является способ, которым " "информация передается ядру при выполнении системного вызова. 4.4BSD всегда " "копирует данные из адресного пространства процесса в буфер ядра. Для " "операций чтения и записи, при которых передаются большие объемы данных, " "выполнение копирования может оказаться занимающим время процессом. " "Альтернативным способом является манипуляции с адресным пространством " "процесса в ядре. Ядро 4.4BSD всегда копирует данные о нескольким причинам:" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:372 msgid "" "Often, the user data are not page aligned and are not a multiple of the " "hardware page length." msgstr "" "Зачастую пользовательские данные не выравнены по границе страницы памяти и " "их объем не кратен размеру аппаратной страницы памяти." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:373 msgid "" "If the page is taken away from the process, it will no longer be able to " "reference that page. Some programs depend on the data remaining in the " "buffer even after those data have been written." msgstr "" "Если страница памяти забирается от процесса, он не может больше ссылаться на " "эту страницу. Некоторые программы зависят от данных, остающихся в буфере, " "даже после записи этих данных." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:374 msgid "" "If the process is allowed to keep a copy of the page (as it is in current " "4.4BSD semantics), the page must be made _copy-on-write_. A copy-on-write " "page is one that is protected against being written by being made read-only. " "If the process attempts to modify the page, the kernel gets a write fault. " "The kernel then makes a copy of the page that the process can modify. " "Unfortunately, the typical process will immediately try to write new data to " "its output buffer, forcing the data to be copied anyway." msgstr "" "Если процесс позволяет хранить копию страницы памяти (как это делается в " "существующей 4.4BSD), то страница должна иметь атрибут _копирования-при-" "записи_. Такая страница является одной из таковых, что защищается от записи " "при помощи атрибута только-для-чтения. Если процесс пытается модифицировать " "страницу памяти, в ядре возникает ситуация ошибки записи. После этого ядро " "делает копию страницы, которую процесс может изменять. К несчастью, " "большинство процессов будет немедленно пытаться записать новые данные в свой " "буфер вывода, что приводит в любом случае к копированию данных." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:375 msgid "" "When pages are remapped to new virtual-memory addresses, most memory-" "management hardware requires that the hardware address-translation cache be " "purged selectively. The cache purges are often slow. The net effect is that " "remapping is slower than copying for blocks of data less than 4 to 8 Kbyte." msgstr "" "Когда страницы переносятся в новые адреса виртуальной памяти, большинство " "аппаратных менеджеров памяти требуют, чтобы кэш аппаратного переназначения " "адресов был выборочно очищен. Очистка кэша зачастую выполняется медленно. В " "итоге получается, что переназначение адресов оказывается медленнее, чем " "копирование блоков данных, не превышающих 4 или 8 килобайт." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:378 msgid "" "The biggest incentives for memory mapping are the needs for accessing big " "files and for passing large quantities of data between processes. The " "_mmap_ interface provides a way for both of these tasks to be done without " "copying." msgstr "" "Больше всего отображение памяти нужно для работы к большими файлами и " "передачи больших объемов данных между процессами. Интерфейс _mmap_ дает " "методы для выполнения обеих этих операций без копирования." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:379 #, no-wrap msgid "Memory Management Inside the Kernel" msgstr "Управление памятью внутри ядра" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:388 msgid "" "The kernel often does allocations of memory that are needed for only the " "duration of a single system call. In a user process, such short-term memory " "would be allocated on the run-time stack. Because the kernel has a limited " "run-time stack, it is not feasible to allocate even moderate-sized blocks of " "memory on it. Consequently, such memory must be allocated through a more " "dynamic mechanism. For example, when the system must translate a pathname, " "it must allocate a 1-Kbyte buffer to hold the name. Other blocks of memory " "must be more persistent than a single system call, and thus could not be " "allocated on the stack even if there was space. An example is protocol-" "control blocks that remain throughout the duration of a network connection." msgstr "" "Ядро часто выполняет выделение памяти, которое нужно только для выполнения " "единственного системного вызова. В пользовательском процессе такая " "кратковременно используемая память будет выделяться в стеке во время " "выполнения. Так как ядро имеет ограниченный объем стека времени выполнения, " "то неэффективно выделять в нем даже блоки памяти среднего размера. Таким " "образом, такая память должна выделяться посредством более гибкого механизма. " "Например, когда системный вызов должен преобразовать имя каталога, он должен " "выделить буфер размером 1 Кбайт для хранения имени. Другие блоки памяти " "должны выделяться на более продолжительный срок, чем один системный вызов, и " "поэтому не могут выделяться в стеке, даже если там есть место. В качестве " "примера можно взять блоки управления протоколами, которые существуют на всем " "протяжении сетевого соединения." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:398 msgid "" "Demands for dynamic memory allocation in the kernel have increased as more " "services have been added. A generalized memory allocator reduces the " "complexity of writing code inside the kernel. Thus, the 4.4BSD kernel has a " "single memory allocator that can be used by any part of the system. It has " "an interface similar to the C library routines _malloc_ and _free_ that " "provide memory allocation to application programs " "crossref:design-44bsd[biblio-mckusick-2, [McKusick & Karels, 1988]]. Like " "the C library interface, the allocation routine takes a parameter specifying " "the size of memory that is needed. The range of sizes for memory requests " "is not constrained; however, physical memory is allocated and is not paged. " "The free routine takes a pointer to the storage being freed, but does not " "require the size of the piece of memory being freed." msgstr "" "Необходимость в динамическом выделении памяти в ядре становилась все более " "острой вместе с добавлением количества сервисов. Общий механизм выделения " "памяти уменьшает сложность написания кода в ядре. Поэтому в 4.4BSD ядро " "имеет единый механизм выделения памяти, который может использоваться в любой " "части системы. У него есть интерфейс, похожий на функции библиотеки языка C " "_malloc_ и _free_, которые обеспечивают выделение памяти в прикладных " "программах crossref:design-44bsd[biblio-mckusick-2, [McKusick & Karels, " "1988]]. Как интерфейс библиотеки языка C, функция выделения памяти получает " "параметр, указывающий на размер памяти, который необходим. Диапазон " "запрашиваемых объемов выделяемой памяти не ограничен; однако выделяемая " "физическая память не подвергается постраничной подгрузке. Функции " "освобождения памяти передается указатель на освобождаемый участок памяти, но " "указывать размер освобождаемого участка памяти не нужно." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:400 #, no-wrap msgid "I/O System" msgstr "Система ввода/вывода" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:404 msgid "" "The basic model of the UNIX I/O system is a sequence of bytes that can be " "accessed either randomly or sequentially. There are no _access methods_ and " "no _control blocks_ in a typical UNIX user process." msgstr "" "Базовой моделью системы ввода/вывода UNIX является последовательность байт, " "доступ к которым может осуществляться как последовательно, так и в в " "произвольном порядке. В типичном пользовательском процессе UNIX нет таких " "понятий, как _методы доступа_ или _управляющие блоки_." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:412 msgid "" "Different programs expect various levels of structure, but the kernel does " "not impose structure on I/O. For instance, the convention for text files is " "lines of ASCII characters separated by a single newline character (the ASCII " "line-feed character), but the kernel knows nothing about this convention. " "For the purposes of most programs, the model is further simplified to being " "a stream of data bytes, or an _I/O stream_. It is this single common data " "form that makes the characteristic UNIX tool-based approach work " "crossref:design-44bsd[biblio-kernighan, [Kernighan & Pike, 1984]]. An I/O " "stream from one program can be fed as input to almost any other program. " "(This kind of traditional UNIX I/O stream should not be confused with the " "Eighth Edition stream I/O system or with the System V, Release 3 STREAMS, " "both of which can be accessed as traditional I/O streams.)" msgstr "" "Различные программы используют разнообразные структуры данных, но ядро не " "связывает ввод/вывод с используемыми структурами. Например, текстовым файлом " "считается файл из строк символов набора ASCII, которые разделены одним " "символом новой строки (символ ASCII перевода строки), но ядро не знает " "ничего об этом соглашении. Для удовлетворения потребностей большинства " "программ модель еще более упрощена и сводится к потоку байт данных, или " "_потоку ввода/вывода_. Такое единое представление данных позволяет работать " "характерному для UNIX подходу на основе инструментов " "crossref:design-44bsd[biblio-kernighan, [Kernighan & Pike, 1984]]. Поток " "ввода/вывода одной программы может быть подан в качестве входной информации " "практически любой другой программе. (Этот тип традиционных для UNIX потоков " "ввода/выводы не нужно путать с потоковой системой ввода/вывода из Eighth " "Edition или с потоками из System V, Release 3 (STREAMS), оба из которых " "доступны как обычные потоки ввода/вывода.)" #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:413 #, no-wrap msgid "Descriptors and I/O" msgstr "Дескрипторы и ввод/вывод" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:421 msgid "" "UNIX processes use _descriptors_ to reference I/O streams. Descriptors are " "small unsigned integers obtained from the _open_ and _socket_ system calls. " "The _open_ system call takes as arguments the name of a file and a " "permission mode to specify whether the file should be open for reading or " "for writing, or for both. This system call also can be used to create a " "new, empty file. A _read_ or _write_ system call can be applied to a " "descriptor to transfer data. The _close_ system call can be used to " "deallocate any descriptor." msgstr "" "Процессы UNIX для работы с потоками ввода/вывода используют _дескрипторы_. " "Дескрипторы представляют собой беззнаковые целые числа, получаемые после " "выполнения системных вызовов _open_ и _socket_. Системный вызов _open_ " "получает в качестве аргументов имя файла и режим доступа, который " "определяет, должен ли файл открываться для чтения, для записи или для обеих " "операций. Этот системный вызов может также использоваться для создания " "нового пустого файла. Системные вызовы _read_ и _write_ могут применяться к " "дескриптору для переноса данных. Системный вызов _close_ может " "использоваться для уничтожения любого дескриптора." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:424 msgid "" "Descriptors represent underlying objects supported by the kernel, and are " "created by system calls specific to the type of object. In 4.4BSD, three " "kinds of objects can be represented by descriptors: files, pipes, and " "sockets." msgstr "" "Дескрипторы представляют низкоуровневые объекты, поддерживаемые ядром, и " "создаваемые системными вызовами, специфичными для каждого типа объектов. В " "4.4BSD дескрипторы могут представлять три типа таких объектов: файлы, каналы " "и сокеты." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:426 msgid "" "A _file_ is a linear array of bytes with at least one name. A file exists " "until all its names are deleted explicitly and no process holds a descriptor " "for it. A process acquires a descriptor for a file by opening that file's " "name with the _open_ system call. I/O devices are accessed as files." msgstr "" "_Файл_ представляет собой линейную последовательность байт, имеющую по " "крайней мере одно имя. Файл существует, пока все его имена не удалены и ни " "один из процессов не хранит его дескриптор. Процесс получает дескриптор " "файла, открывая имя файла посредством системного вызова _open_. Работа с " "устройствами ввода/вывода осуществляется как с файлами." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:427 msgid "" "A _pipe_ is a linear array of bytes, as is a file, but it is used solely as " "an I/O stream, and it is unidirectional. It also has no name, and thus " "cannot be opened with _open_. Instead, it is created by the _pipe_ system " "call, which returns two descriptors, one of which accepts input that is sent " "to the other descriptor reliably, without duplication, and in order. The " "system also supports a named pipe or FIFO. A FIFO has properties identical " "to a pipe, except that it appears in the filesystem; thus, it can be opened " "using the _open_ system call. Two processes that wish to communicate each " "open the FIFO: One opens it for reading, the other for writing." msgstr "" "_Каналом_ является линейная последовательность байт, такая же, как файл, но " "используемая исключительно как поток ввода/вывода, причем однонаправленный. " "У канала нет имени, и поэтому он не может быть открыт при помощи _open_. " "Вместо этого он создается посредством системного вызова _pipe_, который " "возвращает два дескриптора, один из которых принимает входные данные, без " "искажений, без повторений и в той же самой последовательности посылаемый на " "другой дескриптор. Система также поддерживает именованный канал, или FIFO. " "FIFO имеет те же самые свойства, что и канал, за исключением того, что он " "располагается в файловой системе; поэтому он может быть открыт системным " "вызовом _open_. Процессы, которые хотят обмениваться данными, открывают " "FIFO: Один процесс открывает его для чтения, а другой для записи." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:428 msgid "" "A _socket_ is a transient object that is used for interprocess " "communication; it exists only as long as some process holds a descriptor " "referring to it. A socket is created by the _socket_ system call, which " "returns a descriptor for it. There are different kinds of sockets that " "support various communication semantics, such as reliable delivery of data, " "preservation of message ordering, and preservation of message boundaries." msgstr "" "_Сокет_ является промежуточным объектом, который используется для " "межпроцессных коммуникаций; он существует, пока какой-либо процесс хранит " "дескриптор, ссылающийся на него. Сокет создается системным вызовом _socket_, " "который возвращает его дескриптор. Имеется несколько типов сокетов, которые " "поддерживают различные коммуникационные возможности, такие, как надежную " "доставку данных, сохранение последовательности передаваемых сообщений, и " "сохранение границ сообщений." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:430 msgid "" "In systems before 4.2BSD, pipes were implemented using the filesystem; when " "sockets were introduced in 4.2BSD, pipes were reimplemented as sockets." msgstr "" "В системах, предшествующих 4.2BSD, каналы были реализованы в файловой " "системе, когда в 4.2BSD появились сокеты, то каналы были повторно " "реализованы как сокеты." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:436 msgid "" "The kernel keeps for each process a _descriptor table_, which is a table " "that the kernel uses to translate the external representation of a " "descriptor into an internal representation. (The descriptor is merely an " "index into this table.) The descriptor table of a process is inherited from " "that process's parent, and thus access to the objects to which the " "descriptors refer also is inherited. The main ways that a process can " "obtain a descriptor are by opening or creation of an object, and by " "inheritance from the parent process. In addition, socket IPC allows passing " "of descriptors in messages between unrelated processes on the same machine." msgstr "" "Для каждого процесса ядро хранит _таблицу дескрипторов_, которая является " "таблицей, используемой ядром для преобразования внешнего представления " "дескриптора в его внутреннее представление. (Дескриптор является просто " "индексом в этой таблице.) Таблица дескрипторов процесса наследуется от " "родительского процесса, и вместе с ней наследуется и доступ к объектам, на " "которые ссылаются дескрипторы. Основными способами, при помощи которых " "процесс может получить дескриптор, является открытие или создание объекта, а " "также наследование от родительского процесса. Кроме того, межпроцессные " "коммуникации при помощи сокетов позволяют передавать дескрипторы в " "сообщениях между несвязанными процессами на одной и той же машине." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:442 msgid "" "Every valid descriptor has an associated _file offset_ in bytes from the " "beginning of the object. Read and write operations start at this offset, " "which is updated after each data transfer. For objects that permit random " "access, the file offset also may be set with the _lseek_ system call. " "Ordinary files permit random access, and some devices do, as well. Pipes " "and sockets do not." msgstr "" "Любой рабочий дескриптор имеет связанное с ним _смещение в файле_ в байтах " "от начала объекта. Операции чтения и записи начинаются от этого смещения, " "который обновляется после каждой передачи данных. Для объектов, к которым " "разрешен произвольный доступ, смещение в файле может быть установлено " "посредством системного вызова _lseek_. Обычные файлы, а также некоторые " "устройства, разрешают произвольный доступ к ним. Каналы и сокеты этого " "делать не позволяют." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:445 msgid "" "When a process terminates, the kernel reclaims all the descriptors that were " "in use by that process. If the process was holding the final reference to " "an object, the object's manager is notified so that it can do any necessary " "cleanup actions, such as final deletion of a file or deallocation of a " "socket." msgstr "" "Когда процесс завершается, ядро освобождает все дескрипторы, которые " "использовались этим процессом. Если процесс хранил последнюю ссылку на " "объект, то менеджер объектов уведомляется для выполнения всех необходимых " "действий, таких, как окончательное удаление файла или уничтожение сокета." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:446 #, no-wrap msgid "Descriptor Management" msgstr "Управление дескрипторами" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:453 msgid "" "Most processes expect three descriptors to be open already when they start " "running. These descriptors are 0, 1, 2, more commonly known as _standard " "input_, _standard output_, and _standard error_, respectively. Usually, all " "three are associated with the user's terminal by the login process (see " "Section 14.6) and are inherited through _fork_ and _exec_ by processes run " "by the user. Thus, a program can read what the user types by reading " "standard input, and the program can send output to the user's screen by " "writing to standard output. The standard error descriptor also is open for " "writing and is used for error output, whereas standard output is used for " "ordinary output." msgstr "" "Большинство процессов ожидают, что перед началом их работы уже будут открыты " "три дескриптора. Это дескрипторы 0, 1 и 2, больше известные как _стандартный " "ввод_, _стандартный вывод_ и _стандартный поток диагностических сообщений_, " "соответственно. Как правило, все они связываются с пользовательским " "терминалом по время входа в систему (смотри Раздел 14.6) и наследуются через " "вызовы _fork_ и _exec_ процессами, запускаемыми пользователем. Таким " "образом, программа может считывать то, что набирает пользователь, из " "стандартного ввода, и программа может выдавать результат на экран " "пользователя, осуществляя запись в стандартный вывод. Дескриптор потока " "диагностических сообщений также открыт для записи и используется для вывода " "ошибок, когда как стандартный вывод используется для обычного вывода." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:457 msgid "" "These (and other) descriptors can be mapped to objects other than the " "terminal; such mapping is called _I/O redirection_, and all the standard " "shells permit users to do it. The shell can direct the output of a program " "to a file by closing descriptor 1 (standard output) and opening the desired " "output file to produce a new descriptor 1. It can similarly redirect " "standard input to come from a file by closing descriptor 0 and opening the " "file." msgstr "" "Эти (и другие) дескрипторы могут отображаться на объекты, отличающиеся от " "терминала; такое отображение называется _перенаправлением ввода/вывода_, и " "все стандартные командные процессоры позволяют пользователю это делать. " "Оболочка может направить вывод программы в файл, закрывая дескриптор 1 " "(стандартный вывод) и открывая выбранный выходной файл для создания нового " "дескриптора 1. Подобным же образом стандартный ввод может браться из файла, " "при этом закрывается дескриптор 0 и открывается файл." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:463 msgid "" "Pipes allow the output of one program to be input to another program without " "rewriting or even relinking of either program. Instead of descriptor 1 " "(standard output) of the source program being set up to write to the " "terminal, it is set up to be the input descriptor of a pipe. Similarly, " "descriptor 0 (standard input) of the sink program is set up to reference the " "output of the pipe, instead of the terminal keyboard. The resulting set of " "two processes and the connecting pipe is known as a _pipeline_. Pipelines " "can be arbitrarily long series of processes connected by pipes." msgstr "" "Каналы позволяют выводу одной программы становиться вводом другой программы " "без переписывания и даже перекомпоновки программ. Вместо того, чтобы " "дескриптор 1 (стандартный вывод) исходной программы был настроен на запись " "на терминал, он настраивается на входной дескриптор канала. Аналогично " "дескриптор 0 (стандартный ввод) принимающей программы настраивается на " "обращение к выводу канала, а не к клавиатуре терминала. Результирующий набор " "двух процессов и соединяющий канал называется _конвейером_. Конвейеры могут " "быть весьма большими последовательностями процессов, соединенных каналами." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:470 msgid "" "The _open_, _pipe_, and _socket_ system calls produce new descriptors with " "the lowest unused number usable for a descriptor. For pipelines to work, " "some mechanism must be provided to map such descriptors into 0 and 1. The " "_dup_ system call creates a copy of a descriptor that points to the same " "file-table entry. The new descriptor is also the lowest unused one, but if " "the desired descriptor is closed first, _dup_ can be used to do the desired " "mapping. Care is required, however: If descriptor 1 is desired, and " "descriptor 0 happens also to have been closed, descriptor 0 will be the " "result. To avoid this problem, the system provides the _dup2_ system call; " "it is like _dup_, but it takes an additional argument specifying the number " "of the desired descriptor (if the desired descriptor was already open, " "_dup2_ closes it before reusing it)." msgstr "" "Системные вызовы _open_, _pipe_ и _socket_ порождают новые дескрипторы с " "наименьшим неиспользуемым номером, подходящим для дескриптора. Для того, " "чтобы конвейеры могли работать, должен существовать механизм для отображения " "таких дескрипторов в 0 и 1. Системный вызов _dup_ создает копию дескриптора, " "которая указывает на ту же самую запись в таблице файлов. Новый дескриптор " "также является наименьшим неиспользуемым, но если нужный дескриптор сначала " "закрыть, то _dup_ можно использовать для выполнения нужного отображения. " "Однако здесь требуется некоторая осторожность: если нужен дескриптор 1, а " "дескриптор 0 уже закрыт, то в результате получится дескриптор 0. Во " "избежание этой проблемы в системе имеется системный вызов _dup2_; он похож " "на _dup_, но воспринимает дополнительный аргумент, указывающий номер нужного " "дескриптора (если нужный дескриптор уже открыт, то _dup2_ его закроет перед " "повторным использованием)." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:471 #, no-wrap msgid "Devices" msgstr "Устройства" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:477 msgid "" "Hardware devices have filenames, and may be accessed by the user via the " "same system calls used for regular files. The kernel can distinguish a " "_device special file_ or _special file_, and can determine to what device it " "refers, but most processes do not need to make this determination. " "Terminals, printers, and tape drives are all accessed as though they were " "streams of bytes, like 4.4BSD disk files. Thus, device dependencies and " "peculiarities are kept in the kernel as much as possible, and even in the " "kernel most of them are segregated in the device drivers." msgstr "" "Аппаратные устройства имеют связанные с ними имена файлов, и к ним может " "обращаться пользователь при помощи тех же самых системных вызовов, что " "используются для обычных файлов. Ядро может различать _специальный файл " "устройства_ или просто _специальный файл_, и может определять, к какому " "устройству он относится, но большинство процессов не выполняют такого " "распознавания. Терминалы, принтеры и стримеры все доступны как " "последовательности байт, как дисковые файлы 4.4BSD. Таким образом, " "особенности работы устройств максимально скрываются ядром, и даже в ядре " "большинство из них отличаются в драйверах." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:482 msgid "" "Hardware devices can be categorized as either _structured_ or " "_unstructured_; they are known as _block_ or _character_ devices, " "respectively. Processes typically access devices through _special files_ in " "the filesystem. I/O operations to these files are handled by kernel-" "resident software modules termed _device drivers_. Most network-" "communication hardware devices are accessible through only the interprocess-" "communication facilities, and do not have special files in the filesystem " "name space, because the _raw-socket_ interface provides a more natural " "interface than does a special file." msgstr "" "Аппаратные устройства могут быть разделены на _структурированные_ или " "_неструктурированные_; они известны под названиями _блочные_ и " "_посимвольные_, соответственно. Как правило, процессы обращаются к " "устройствам посредством _специальных файлов_ в файловой системе. Операции " "ввода/вывода, выполняемые с такими файлами, обрабатываются постоянно " "находящимися в ядре программными модулями, называемыми _драйверами " "устройств_. Большинство аппаратных устройств для сетевых коммуникаций " "доступны только при помощи подсистемы межпроцессного взаимодействия, и не " "имеют специальных устройств в пространстве имен файловой системы, так как " "интерфейс _низкоуровневых сокетов_ дает более естественный интерфейс, чем " "специальный файл." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:486 msgid "" "Structured or block devices are typified by disks and magnetic tapes, and " "include most random-access devices. The kernel supports read-modify-write-" "type buffering actions on block-oriented structured devices to allow the " "latter to be read and written in a totally random byte-addressed fashion, " "like regular files. Filesystems are created on block devices." msgstr "" "Структурированные или блочные устройства разделяются на диски и магнитные " "ленты и включают в себя большинство устройств с произвольным доступом. Ядро " "поддерживает операции буферизации типа чтение-изменение-запись с блочными " "структурированными устройствами для того, чтобы разрешить последним " "осуществлять чтение и запись полностью произвольным образом, как с обычными " "файлами. Файловые системы создаются на блочных устройствах." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:490 msgid "" "Unstructured devices are those devices that do not support a block " "structure. Familiar unstructured devices are communication lines, raster " "plotters, and unbuffered magnetic tapes and disks. Unstructured devices " "typically support large block I/O transfers." msgstr "" "Неструктурированными устройствами являются те, что не поддерживают блочную " "структуру. Типичными неструктурированными устройствами являются линии связи, " "растровые графопостроители и небуферизируемые магнитные ленты и диски. " "Неструктурированные устройства, как правило, поддерживают перенос больших " "объемов данных." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:493 msgid "" "Unstructured files are called _character devices_ because the first of these " "to be implemented were terminal device drivers. The kernel interface to the " "driver for these devices proved convenient for other devices that were not " "block structured." msgstr "" "Неструктурированные файлы называют _символьными устройствами_, потому что " "первые из них являлись драйверами терминальных устройств. Интерфейс ядра к " "драйверу для этих устройств доказал удобство его использования для других " "неструктурированных устройств." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:499 msgid "" "Device special files are created by the _mknod_ system call. There is an " "additional system call, _ioctl_, for manipulating the underlying device " "parameters of special files. The operations that can be done differ for " "each device. This system call allows the special characteristics of devices " "to be accessed, rather than overloading the semantics of other system " "calls. For example, there is an _ioctl_ on a tape drive to write an end-of-" "tape mark, instead of there being a special or modified version of _write_." msgstr "" "Специальные файлы устройств создаются системным вызовом _mknod_. Имеется " "дополнительный системный вызов, _ioctl_, для управления низкоуровневыми " "параметрами специальных файлов. Выполняемые операции для каждого устройства " "различны. Этот системный вызов позволяет осуществлять доступ к специальным " "характеристикам устройств, не перегружая смысл других системных вызовов. " "Например, для стримера существует _ioctl_ для записи метки конца ленты, но " "нет особой или измененной версии функции _write_." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:500 #, no-wrap msgid "Socket IPC" msgstr "Механизм межпроцессных коммуникаций посредством сокетов" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:509 msgid "" "The 4.2BSD kernel introduced an IPC mechanism more flexible than pipes, " "based on _sockets_. A socket is an endpoint of communication referred to by " "a descriptor, just like a file or a pipe. Two processes can each create a " "socket, and then connect those two endpoints to produce a reliable byte " "stream. Once connected, the descriptors for the sockets can be read or " "written by processes, just as the latter would do with a pipe. The " "transparency of sockets allows the kernel to redirect the output of one " "process to the input of another process residing on another machine. A " "major difference between pipes and sockets is that pipes require a common " "parent process to set up the communications channel. A connection between " "sockets can be set up by two unrelated processes, possibly residing on " "different machines." msgstr "" "В ядре 4.2BSD появился механизм межпроцессного взаимодействия, более гибкий, " "чем каналы, основанный на _сокетах_. Сокет является конечной точкой " "коммуникаций, доступный через дескриптор, как файл или канал. Каждый из двух " "процессов может создать сокет, а затем соединить эти конечные точки для " "получения надежного канала передачи потока байт. После соединения процесс " "может выполнять с дескрипторами операции чтения и записи, как это делалось с " "каналами. Прозрачность сокетов позволяет ядру перенаправить вывод одного " "процесса на вход другого, работающего на другой машине. Большим различием " "между каналами и сокетами является то, что каналы требуют наличия общего " "родительского процесса для установки коммуникации. Соединение между сокетами " "может быть установлено двумя несвязанными процессами, возможно, работающими " "на разных машинах." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:516 msgid "" "System V provides local interprocess communication through FIFOs (also known " "as _named pipes_). FIFOs appear as an object in the filesystem that " "unrelated processes can open and send data through in the same way as they " "would communicate through a pipe. Thus, FIFOs do not require a common " "parent to set them up; they can be connected after a pair of processes are " "up and running. Unlike sockets, FIFOs can be used on only a local machine; " "they cannot be used to communicate between processes on different machines. " "FIFOs are implemented in 4.4BSD only because they are required by the " "POSIX.1 standard. Their functionality is a subset of the socket interface." msgstr "" "System V предоставляет механизм локального межпроцессного взаимодействия " "через FIFO (также называемые _именованными каналами_). FIFO отображаются как " "объекты файловой системы, которые могут быть открыты несвязанными " "процессами, и в которые можно открывать и посылать данные так же, как в " "случае каналов. Таким образом, FIFO не требуют общего родительского процесса " "для установки соединения; они могут быть соединены после того, как будут " "запущены два процесса. В отличие от сокетов, FIFO могут быть использованы " "только на локальной машине; они не могут быть использованы для связи между " "процессами, работающими на разных машинах. FIFO реализованы в 4.4BSD, потому " "что это требует стандарт POSIX.1. Их функциональность является подмножеством " "функций интерфейса сокетов." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:523 msgid "" "The socket mechanism requires extensions to the traditional UNIX I/O system " "calls to provide the associated naming and connection semantics. Rather " "than overloading the existing interface, the developers used the existing " "interfaces to the extent that the latter worked without being changed, and " "designed new interfaces to handle the added semantics. The _read_ and " "_write_ system calls were used for byte-stream type connections, but six new " "system calls were added to allow sending and receiving addressed messages " "such as network datagrams. The system calls for writing messages include " "_send_, _sendto_, and _sendmsg_. The system calls for reading messages " "include _recv_, _recvfrom_, and _recvmsg_. In retrospect, the first two in " "each class are special cases of the others; _recvfrom_ and _sendto_ probably " "should have been added as library interfaces to _recvmsg_ and _sendmsg_, " "respectively." msgstr "" "Механизм сокетов требует расширения традиционных для UNIX системных вызовов " "ввода/вывода для обеспечения соответствующих имен и смыслов соединениям. " "Вместо того, чтобы перегружать существующий интерфейс, разработчики " "использовали существующие интерфейсы, расширив их так, что они продолжили " "работать без изменений, и разработали новые интерфейсы для работы с новыми " "возможностями. Системные вызовы _read_ и _write_ использовались для " "соединений типа потока байт, и было добавлено шесть новых системных вызовов, " "что позволило посылать и принимать адресованные сообщения, такие, как " "сетевые датаграммы. Системные вызовы для записи сообщений включают в себя " "_send_, _sendto_ и _sendmsg_. Системные вызовы для чтения сообщений включают " "_recv_, _recvfrom_ и _recvmsg_. В ретроспективе, первые два в каждом классе " "являются особыми случаями других; _recvfrom_ и _sendto_, наверное, должны " "были быть добавлены как библиотечные интерфейсы к _recvmsg_ и _sendmsg_, " "соответственно." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:524 #, no-wrap msgid "Scatter/Gather I/O" msgstr "Множественный ввод/вывод" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:530 msgid "" "In addition to the traditional _read_ and _write_ system calls, 4.2BSD " "introduced the ability to do scatter/gather I/O. Scatter input uses the " "_readv_ system call to allow a single read to be placed in several different " "buffers. Conversely, the _writev_ system call allows several different " "buffers to be written in a single atomic write. Instead of passing a single " "buffer and length parameter, as is done with _read_ and _write_, the process " "passes in a pointer to an array of buffers and lengths, along with a count " "describing the size of the array." msgstr "" "Кроме традиционных системных вызовов _read_ и _write_, в 4.2BSD появилась " "возможность выполнять множественный ввод/вывод. Множественный ввод " "использует системный вызов _readv_ для размещения результата единственной " "операции чтения в нескольких различных буферах. Обратно, системный вызов " "_writev_ позволяет осуществлять запись нескольких различных буферов за одну " "атомарную операцию записи. Вместо передачи одного буфера и его длины в " "качестве параметров, как это делается при использовании системных вызовов " "_read_ и _write_, процесс передает указатель на массив буферов и их длин, а " "также счетчик, определяющий размер массива." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:535 msgid "" "This facility allows buffers in different parts of a process address space " "to be written atomically, without the need to copy them to a single " "contiguous buffer. Atomic writes are necessary in the case where the " "underlying abstraction is record based, such as tape drives that output a " "tape block on each write request. It is also convenient to be able to read " "a single request into several different buffers (such as a record header " "into one place and the data into another). Although an application can " "simulate the ability to scatter data by reading the data into a large buffer " "and then copying the pieces to their intended destinations, the cost of " "memory-to-memory copying in such cases often would more than double the " "running time of the affected application." msgstr "" "Такой механизм позволяет буферам в различных областях адресного пространства " "процесса записываться атомарно, без необходимости копировать их в один " "буфер. Атомарные операции записи необходимы в случае, когда низкоуровневые " "абстракции основаны на записях, например, стримеры, которые выводят блок " "ленты при каждом запросе на запись. Также полезна возможность помещать " "результат одного запроса на чтение в нескольких различных буферах (например, " "заголовок записи в одно место, а данные в другое). Хотя приложение может " "симулировать возможность выполнять множественные операции посредством чтения " "данных в большой буфер с последующим копированием их частей в нужные " "области, и накладные расходы на копирование в памяти в таких случаях часто " "увеличивает время выполнения приложения чуть ли не вдвое." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:538 msgid "" "Just as _send_ and _recv_ could have been implemented as library interfaces " "to _sendto_ and _recvfrom_, it also would have been possible to simulate " "_read_ with _readv_ and _write_ with _writev_. However, _read_ and _write_ " "are used so much more frequently that the added cost of simulating them " "would not have been worthwhile." msgstr "" "Так же, как _send_ и _recv_ могут быть реализованы в виде библиотечных " "интерфейсов к _sendto_ и _recvfrom_, возможно симулирование _read_ через " "_readv_ и _write_ через _writev_. Однако _read_ и _write_ используются столь " "часто, что накладные расходы на такую симуляцию не стоят того." #. type: Title ==== #: documentation/content/en/books/design-44bsd/_index.adoc:539 #, no-wrap msgid "Multiple Filesystem Support" msgstr "Поддержка нескольких файловых систем" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:545 msgid "" "With the expansion of network computing, it became desirable to support both " "local and remote filesystems. To simplify the support of multiple " "filesystems, the developers added a new virtual node or _vnode_ interface to " "the kernel. The set of operations exported from the vnode interface appear " "much like the filesystem operations previously supported by the local " "filesystem. However, they may be supported by a wide range of filesystem " "types:" msgstr "" "Вместе с распространением сетевых вычислений возникла потребность в " "поддержке как локальных, так и удаленных файловых систем. Для облегчения " "поддержки нескольких файловых систем разработчики добавили в ядро интерфейс " "виртуальных узлов файловой системы, или интерфейс _vnode_. Набор операций, " "экспортируемых через интерфейс vnode, похож на операции файловой системы, " "ранее поддерживаемые локальной файловой системой. Однако они могут " "поддерживаться широким спектром типов файловых систем:" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:547 msgid "Local disk-based filesystems" msgstr "Локальные файловые системы, использующие диск" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:548 msgid "Files imported using a variety of remote filesystem protocols" msgstr "" "Файлы, импортируемые при помощи разнообразных протоколов удаленных файловых " "систем" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:549 msgid "Read-only CD-ROM filesystems" msgstr "Файловые системы CD-ROM, доступные только для чтения" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:550 msgid "" "Filesystems providing special-purpose interfaces -- for example, the `/proc` " "filesystem" msgstr "" "Файловые системы, предоставляющие специализированные услуги - к примеру, " "файловая система [.filename]#/proc#" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:553 msgid "" "A few variants of 4.4BSD, such as FreeBSD, allow filesystems to be loaded " "dynamically when the filesystems are first referenced by the _mount_ system " "call. The vnode interface is described in Section 6.5; its ancillary " "support routines are described in Section 6.6; several of the special-" "purpose filesystems are described in Section 6.7." msgstr "" "Некоторые варианты 4.4BSD, такие, как FreeBSD, позволяют выполнять " "динамическую загрузку файловых систем при первом обращении к ним при помощи " "системного вызова _mount_. Интерфейс vnode описан в Разделе 6.5; вдобавок он " "поддерживает функции, описанные в Разделе 6.6; некоторые из файловых систем " "специального назначения описаны в Разделе 6.7." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:555 #, no-wrap msgid "Filesystems" msgstr "Файловые системы" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:560 msgid "" "A regular file is a linear array of bytes, and can be read and written " "starting at any byte in the file. The kernel distinguishes no record " "boundaries in regular files, although many programs recognize line-feed " "characters as distinguishing the ends of lines, and other programs may " "impose other structure. No system-related information about a file is kept " "in the file itself, but the filesystem stores a small amount of ownership, " "protection, and usage information with each file." msgstr "" "Обычный файл представляет собой массив байтов, и может читаться и " "записываться, начиная с произвольного байта файла. Ядро не различает в " "обычных файлах границ записей, хотя многие программы воспринимают символы " "перевода строки в качестве признаков конца строк, но другие программы могут " "предполагать наличие других структур. В самом файле не хранится никакой " "системной информации о файле, но в файловой системе размещается некоторая " "информация о владельце, правах доступа и об использовании каждого файла." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:565 msgid "" "A _filename_ component is a string of up to 255 characters. These filenames " "are stored in a type of file called a _directory_. The information in a " "directory about a file is called a _directory entry_ and includes, in " "addition to the filename, a pointer to the file itself. Directory entries " "may refer to other directories, as well as to plain files. A hierarchy of " "directories and files is thus formed, and is called a _filesystem_;" msgstr "" "Компонент под названием _имя файла_ является строкой длиной до 255 символов. " "Эти имена хранятся в файле особого типа, который называется _каталогом_. " "Информация о файле в каталоге называется _записью каталога_ и включает, " "кроме имени файла, указатель на сам файл. Записи каталога могут ссылаться " "как на другие каталоги, так и на обычные файлы. Таким образом формируется " "иерархия каталогов и файлов, которая и называется файловой системой " "_filesystem_;" #. type: Block title #: documentation/content/en/books/design-44bsd/_index.adoc:566 #, no-wrap msgid "A small filesystem" msgstr "Небольшая файловая система" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:569 msgid "image:fig2.png[A small filesystem]" msgstr "image:fig2.png[Дерево небольшой файловой системы]" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:574 msgid "" "a small one is shown in crossref:design-44bsd[fig-small-fs, A small " "filesystem]. Directories may contain subdirectories, and there is no " "inherent limitation to the depth with which directory nesting may occur. To " "protect the consistency of the filesystem, the kernel does not permit " "processes to write directly into directories. A filesystem may include not " "only plain files and directories, but also references to other objects, such " "as devices and sockets." msgstr "" "Одна небольшая файловая система показана на crossref:design-44bsd[fig-small-" "fs, A small filesystem]. Каталоги могут содержать подкаталоги, и нет " "ограничений вложенности одного каталога в другой по глубине. Для соблюдения " "целостности файловой системы, ядро не позволяет процессу производить запись " "непосредственно в каталоги. Файловая система может хранить не только обычные " "файлы и каталоги, но также ссылки на другие объекты, такие, как устройства и " "сокеты." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:579 msgid "" "The filesystem forms a tree, the beginning of which is the _root directory_, " "sometimes referred to by the name _slash_, spelled with a single solidus " "character (/). The root directory contains files; in our example in Fig " "2.2, it contains `vmunix`, a copy of the kernel-executable object file. It " "also contains directories; in this example, it contains the `usr` " "directory. Within the `usr` directory is the `bin` directory, which mostly " "contains executable object code of programs, such as the files `ls` and `vi`." msgstr "" "Файловая система образует дерево, начало которого находится в _корневом " "каталоге_, иногда называемому по имени _слэш_, которое соответствует символу " "одинарной наклонной черты (/). Корневой каталог содержит файлы; в нашем " "примере на Рисунке 2.2, он содержит [.filename]#vmunix#, копию выполнимого " "объектного файла ядра. В нем также расположены каталоги; в этом примере он " "содержит каталог [.filename]#usr#. Внутри каталога [.filename]#usr# " "располагается каталог [.filename]#bin#, который в основном содержит " "выполнимый объектный код программ, таких, как [.filename]#ls# и " "[.filename]#vi#." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:584 msgid "" "A process identifies a file by specifying that file's _pathname_, which is a " "string composed of zero or more filenames separated by slash (/) " "characters. The kernel associates two directories with each process for use " "in interpreting pathnames. A process's _root directory_ is the topmost " "point in the filesystem that the process can access; it is ordinarily set to " "the root directory of the entire filesystem. A pathname beginning with a " "slash is called an _absolute pathname_, and is interpreted by the kernel " "starting with the process's root directory." msgstr "" "Процесс обращается к файлу, указывая _путь_ до него, который является " "строкой, состоящей из нескольких или ни одного имен файлов, разделенных " "символами слэша (/). С каждым процессом ядро связывает два каталога, при " "помощи которых можно интерпретировать маршруты до файлов. _Корневой каталог_ " "процесса является самой верхней точкой файловой системы, которую может " "достичь процесс; обычно он соответствует корневому каталогу всей файловой " "системы. Маршрут, начинающийся с символа слэша, называется _абсолютным " "маршрутом_, и интерпретируется ядром, начиная с корневого каталога процесса." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:590 msgid "" "A pathname that does not begin with a slash is called a _relative pathname_, " "and is interpreted relative to the _current working directory_ of the " "process. (This directory also is known by the shorter names _current " "directory_ or _working directory_.) The current directory itself may be " "referred to directly by the name _dot_, spelled with a single period (`.`) " "The filename _dot-dot_ (`..`) refers to a directory's parent directory. The " "root directory is its own parent." msgstr "" "Имя пути, которое не начинается со слэша, называется _относительным " "маршрутом_, и интерпретируется относительно _текущего рабочего каталога_ " "процесса. (Этот каталог кратко также называют _текущим каталогом_ или " "_рабочим каталогом_.) Текущий каталог сам по себе можно обозначить " "непосредственно по имени _dot_, что соответствует одной точке (`.`). Имя " "файла _dot-dot_ (`..`) обозначает родительский каталог текущего каталога. " "Корневой каталог является предком самому себе." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:594 msgid "" "A process may set its root directory with the _chroot_ system call, and its " "current directory with the _chdir_ system call. Any process may do _chdir_ " "at any time, but _chroot_ is permitted only a process with superuser " "privileges. _Chroot_ is normally used to set up restricted access to the " "system." msgstr "" "Процесс может задать собственный корневой каталог при помощи системного " "вызова _chroot_, и установить текущий каталог системным вызовом _chdir_. " "Каждый процесс может в любой момент выполнить вызов _chdir_, но _chroot_ " "позволено выполнять только процессу с административными привилегиями. " "_Chroot_ обычно используется для ограничения доступа к системе." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:596 msgid "" "Using the filesystem shown in Fig. 2.2, if a process has the root of the " "filesystem as its root directory, and has `/usr` as its current directory, " "it can refer to the file `vi` either from the root with the absolute " "pathname `/usr/bin/vi`, or from its current directory with the relative " "pathname `bin/vi`." msgstr "" "Взяв файловую систему, изображенную на Рисунке 2.2, и полагая, что процесс " "имеет в качестве корневого каталога корневой каталог файловой системы, и в " "качестве текущего каталога [.filename]#/usr#, он может обратиться к файлу " "[.filename]#vi# либо от корня по абсолютному имени [.filename]#/usr/bin/vi#, " "либо из текущего каталога с относительным именем [.filename]#bin/vi#." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:602 msgid "" "System utilities and databases are kept in certain well-known directories. " "Part of the well-defined hierarchy includes a directory that contains the " "_home directory_ for each user -- for example, `/usr/staff/mckusick` and `/" "usr/staff/karels` in Fig. 2.2. When users log in, the current working " "directory of their shell is set to the home directory. Within their home " "directories, users can create directories as easily as they can regular " "files. Thus, a user can build arbitrarily complex subhierarchies." msgstr "" "Системные утилиты и базы данных располагаются в нескольких всем известных " "каталогах. Частью предопределенной иерархии является каталог, содержащий " "_домашний каталог_ для каждого пользователя - например, [.filename]#/usr/" "staff/mckusick# и [.filename]#/usr/staff/karels# на Рисунке 2.2. Когда " "пользователи регистрируются в системе, то рабочий каталог их командного " "процессора устанавливается в домашний каталог. В своих домашних каталогах " "пользователи могут создавать каталоги так же легко, как и обычные файлы. " "Таким образом, пользователь может строить иерархии каталогов произвольной " "сложности." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:609 msgid "" "The user usually knows of only one filesystem, but the system may know that " "this one virtual filesystem is really composed of several physical " "filesystems, each on a different device. A physical filesystem may not span " "multiple hardware devices. Since most physical disk devices are divided " "into several logical devices, there may be more than one filesystem per " "physical device, but there will be no more than one per logical device. One " "filesystem -- the filesystem that anchors all absolute pathnames -- is " "called the _root filesystem_, and is always available. Others may be " "mounted; that is, they may be integrated into the directory hierarchy of the " "root filesystem. References to a directory that has a filesystem mounted on " "it are converted transparently by the kernel into references to the root " "directory of the mounted filesystem." msgstr "" "Пользователь обычно знает только об одной файловой системе, но система может " "знать, что одна виртуальная файловая система на самом деле состоит из " "нескольких физических файловых систем, каждая из которых расположена на " "отдельном устройстве. Физическая файловая система не может располагаться на " "нескольких физических устройствах. Так как большинство физических дисковых " "устройств разбиваются на несколько логических устройств, то на одном " "физическом устройстве может располагаться более одной файловой системы, но " "не более одной для каждого логического устройства. Одна из файловых систем - " "та, с которой начинаются все абсолютные имена - называется _корневой " "файловой системой_, и она всегда доступна. Другие файловые системы могут " "монтироваться; это значит, что они могут интегрироваться в иерархию " "каталогов корневой файловой системы. Ссылки на каталог, в котором находится " "смонтированная в него файловая системе, прозрачно преобразуются ядром в " "ссылки на корневой каталог смонтированной файловой системы." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:614 msgid "" "The _link_ system call takes the name of an existing file and another name " "to create for that file. After a successful _link_, the file can be " "accessed by either filename. A filename can be removed with the _unlink_ " "system call. When the final name for a file is removed (and the final " "process that has the file open closes it), the file is deleted." msgstr "" "Системный вызов _link_ в качестве параметров принимает имя существующего " "файла и новое имя, которое будет присвоено файлу. После успешного выполнения " "вызова _link_, файл может быть доступен по любому из имен. Имя файла может " "быть удалено при помощи системного вызова _unlink_. Когда удаляется " "последнее имя для файла (и последний процесс, который держал файл открытым, " "закрыл его), удаляется и сам файл." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:621 msgid "" "Files are organized hierarchically in _directories_. A directory is a type " "of file, but, in contrast to regular files, a directory has a structure " "imposed on it by the system. A process can read a directory as it would an " "ordinary file, but only the kernel is permitted to modify a directory. " "Directories are created by the _mkdir_ system call and are removed by the " "_rmdir_ system call. Before 4.2BSD, the _mkdir_ and _rmdir_ system calls " "were implemented by a series of _link_ and _unlink_ system calls being " "done. There were three reasons for adding systems calls explicitly to " "create and delete directories:" msgstr "" "Файлы организованы иерархически в _каталоги_. Каталог является типом файла, " "но, в отличие от обычных файлов, каталог имеет структуру, определяемую " "системой. Процесс может читать каталог, как будто это обычный файл, но " "только ядру разрешено изменять каталог. Каталоги создаются системным вызовом " "_mkdir_ и удаляются системным вызовом _rmdir_. До 4.2BSD системные вызовы " "_mkdir_ и _rmdir_ были реализованы как последовательность системных вызовов " "_link_ и _unlink_. Имелось три причины для добавления системных вызовов " "специально для создания и удаления каталогов:" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:624 msgid "" "The operation could be made atomic. If the system crashed, the directory " "would not be left half-constructed, as could happen when a series of link " "operations were used." msgstr "" "Операция может быть сделана атомарной. Если система завершила работу " "аварийно, то каталог не может оставаться в промежуточном состоянии, что " "может случиться при последовательном вызове серии операций." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:625 msgid "" "When a networked filesystem is being run, the creation and deletion of files " "and directories need to be specified atomically so that they can be " "serialized." msgstr "" "При работе сетевой файловой системы создание и удаление файлов и каталогов " "должны выполняться атомарно, чтобы могли выполняться последовательно." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:626 msgid "" "When supporting non-UNIX filesystems, such as an MS-DOS filesystem, on " "another partition of the disk, the other filesystem may not support link " "operations. Although other filesystems might support the concept of " "directories, they probably would not create and delete the directories with " "links, as the UNIX filesystem does. Consequently, they could create and " "delete directories only if explicit directory create and delete requests " "were presented." msgstr "" "При реализации поддержки не-UNIX файловых систем, таких, как файловая " "система MS-DOS, на другом разделе диска, может оказаться, что эта файловая " "система не поддерживает ссылочных операций. Хотя другие файловые системы " "могут поддерживать концепцию каталогов, скорее всего, они не будут создавать " "и удалять каталоги со ссылками, как это делается в файловой системе UNIX. " "Соответственно они могут создавать и и удалять каталоги только при наличии " "явных запросов на удаление или создание каталогов." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:633 msgid "" "The _chown_ system call sets the owner and group of a file, and _chmod_ " "changes protection attributes. _Stat_ applied to a filename can be used to " "read back such properties of a file. The _fchown_, _fchmod_, and _fstat_ " "system calls are applied to a descriptor, instead of to a filename, to do " "the same set of operations. The _rename_ system call can be used to give a " "file a new name in the filesystem, replacing one of the file's old names. " "Like the directory-creation and directory-deletion operations, the _rename_ " "system call was added to 4.2BSD to provide atomicity to name changes in the " "local filesystem. Later, it proved useful explicitly to export renaming " "operations to foreign filesystems and over the network." msgstr "" "Системный вызов _chown_ устанавливает владельца и группу файла, а _chmod_ " "изменяет атрибуты защиты. Вызов _stat_, примененный к имени файла, может " "использоваться для чтения этих свойств файла. Системные вызовы _fchown_, " "_fchmod_ и _fstat_ применяются с дескрипторами, а не с именами файлов, для " "выполнения того же самого набора операций. Системный вызов _rename_ может " "использоваться для присвоения файлу нового имени в файловой системе с " "заменой старого имени файла. Как и операции по созданию и удалению " "каталогов, системный вызов _rename_ был добавлен в 4.2BSD для придания " "атомарности изменению имен в локальной файловой системе. Позже он оправдал " "свою исключительную полезность для экспортирования операций по " "переименованию в сторонних файловых системах и по сети." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:638 msgid "" "The _truncate_ system call was added to 4.2BSD to allow files to be " "shortened to an arbitrary offset. The call was added primarily in support " "of the Fortran run-time library, which has the semantics such that the end " "of a random-access file is set to be wherever the program most recently " "accessed that file. Without the _truncate_ system call, the only way to " "shorten a file was to copy the part that was desired to a new file, to " "delete the old file, then to rename the copy to the original name. As well " "as this algorithm being slow, the library could potentially fail on a full " "filesystem." msgstr "" "Системный вызов _truncate_ был добавлен в 4.2BSD для того, чтобы файлы могли " "обрезаться по указанному смещению. Вызов был добавлен первоначально для " "поддержки библиотеки времени выполнения языка Fortran, в котором применялось " "понятие конца файла с произвольным доступом, который мог устанавливаться в " "любую позицию, в которой был последний раз доступ к файлу. Без системного " "вызова _truncate_ единственным способом обрезать файл было копирование " "нужной части в новый файл, удаление старого и переименование копии в " "первоначальное имя. Библиотека могла теоретически отказываться работать на " "заполненной файловой системе, к тому же такой алгоритм оказывался медленным." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:641 msgid "" "Once the filesystem had the ability to shorten files, the kernel took " "advantage of that ability to shorten large empty directories. The advantage " "of shortening empty directories is that it reduces the time spent in the " "kernel searching them when names are being created or deleted." msgstr "" "После того, как файловая система получила возможность обрезать файлы, ядро " "применяло эту возможность для уменьшения больших пустых каталогов. " "Преимущество в уменьшении пустых каталогов заключается в сокращении времени " "ядра на поиск в них при создании или удалении имен." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:645 msgid "" "Newly created files are assigned the user identifier of the process that " "created them and the group identifier of the directory in which they were " "created. A three-level access-control mechanism is provided for the " "protection of files. These three levels specify the accessibility of a file " "to" msgstr "" "Вновь создаваемым файлам присваивается идентификатор пользователя процесса, " "который их создал, и идентификатор группы каталога, в котором они были " "созданы. Для защиты файлов применяется трехуровневый механизм управления " "доступом. Эти три уровня определяют доступность файла для" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:648 msgid "The user who owns the file" msgstr "Пользователя, который является владельцем файла" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:649 msgid "The group that owns the file" msgstr "Группы, которая приписана файлу" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:650 msgid "Everyone else" msgstr "Всех остальных" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:652 msgid "" "Each level of access has separate indicators for read permission, write " "permission, and execute permission." msgstr "" "Каждый уровень доступа имеет отдельные индикаторы прав для чтения, записи и " "выполнения." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:662 msgid "" "Files are created with zero length, and may grow when they are written. " "While a file is open, the system maintains a pointer into the file " "indicating the current location in the file associated with the descriptor. " "This pointer can be moved about in the file in a random-access fashion. " "Processes sharing a file descriptor through a _fork_ or _dup_ system call " "share the current location pointer. Descriptors created by separate _open_ " "system calls have separate current location pointers. Files may have " "_holes_ in them. Holes are void areas in the linear extent of the file " "where data have never been written. A process can create these holes by " "positioning the pointer past the current end-of-file and writing. When " "read, holes are treated by the system as zero-valued bytes." msgstr "" "Файлы создаются с нулевым размером, который может увеличиться при выполнении " "операций записи. Пока файл открыт, система отслеживает указатель на файл, " "соответствующий текущему положению в файле, связанном с дескриптором. Этот " "указатель может перемешаться по файлу в произвольном порядке. Процессы, " "использующие один и тот же дескриптор файла посредством системных вызовов " "_fork_ или _dup_, используют одновременно один и тот же указатель текущей " "позиции. Дескрипторы, созданные различными системными вызовами _open_, имеют " "различные указатели текущей позиции. В файлах могут присутствовать _дыры_. " "Дыры представляют собой пустые пространства в теле файла, в которые никаких " "данных не записывалось. Процесс может создать такие дыры, перемещая " "указатель за текущий конец файла и производя запись. При чтении дыры " "интерпретируются системой как заполненные нулевыми байтами." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:668 msgid "" "Earlier UNIX systems had a limit of 14 characters per filename component. " "This limitation was often a problem. For example, in addition to the " "natural desire of users to give files long descriptive names, a common way " "of forming filenames is as `basename.extension`, where the extension " "(indicating the kind of file, such as `.c` for C source or `.o` for " "intermediate binary object) is one to three characters, leaving 10 to 12 " "characters for the basename. Source-code-control systems and editors " "usually take up another two characters, either as a prefix or a suffix, for " "their purposes, leaving eight to 10 characters. It is easy to use 10 or 12 " "characters in a single English word as a basename (e.g., `multiplexer`)." msgstr "" "Ранние версии UNIX имели ограничение в 14 символов на имя файла. Это " "ограничение зачастую вызывало проблемы. Например, кроме естественного " "желания пользователей давать файлам длинные описательные имена, " "распространенным способом формировать имена файлов является использование " "формата [.filename]#basename.extension#, где расширение (указывающее на тип " "файла, скажем, `.c` для исходного года на языке C или `.o` для " "промежуточного двоичного объекта) имеет длину от одного до трех символов, " "оставляя от 10 до 12 символов на имя файла. Системы управления исходным " "кодом и редакторы обычно используют дополнительно два символа для своих " "целей, для префикса или суффикса имени файла, при этом остается от восьми до " "10 символов. В качестве имени файла легко использовать от 10 до 12 символов " "одного английского слова (например, `multiplexer`)." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:673 msgid "" "It is possible to keep within these limits, but it is inconvenient or even " "dangerous, because other UNIX systems accept strings longer than the limit " "when creating files, but then _truncate_ to the limit. A C language source " "file named `multiplexer.c` (already 13 characters) might have a source-code-" "control file with `s.` prepended, producing a filename `s.multiplexer` that " "is indistinguishable from the source-code-control file for `multiplexer.ms`, " "a file containing `troff` source for documentation for the C program. The " "contents of the two original files could easily get confused with no warning " "from the source-code-control system. Careful coding can detect this " "problem, but the long filenames first introduced in 4.2BSD practically " "eliminate it." msgstr "" "Можно смириться с этими ограничениями, но это непоследовательно и даже " "опасно, потому что другие системы UNIX могут работать со строками, " "превышающими этот лимит, при создании файлов, но затем имя будет _обрезано_. " "Исходный файл с именем [.filename]#multiplexer.c#, содержащий исходный код " "на языке C, (уже 13 символов) может иметь соответствующий файл из системы " "управления исходным кодом с префиксом `s.`, при этом получается имя файла " "[.filename]#s.multiplexer#, которое не будет отличаться от файла системы " "управления исходным кодом для файла [.filename]#multiplexer.ms#, содержащего " "исходный код `troff` для документации программы на языке C. Содержимое двух " "оригинальных файлов может оказаться перепутанным без каких-либо " "предупреждений от системы управления исходным кодом. При тщательном " "кодировании эту проблему можно обнаружить, но поддержка длинных имен файлов, " "впервые появившаяся в 4.2BSD, практически полностью ликвидировала эту " "проблему." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:675 #, no-wrap msgid "Filestores" msgstr "Размещение файлов" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:680 msgid "" "The operations defined for local filesystems are divided into two parts. " "Common to all local filesystems are hierarchical naming, locking, quotas, " "attribute management, and protection. These features are independent of how " "the data will be stored. 4.4BSD has a single implementation to provide these " "semantics." msgstr "" "Операции, определенные для локальных файловых систем, делятся на две " "категории. Общими для всех локальных систем являются иерархический принцип " "именования, блокировка, квоты, управление атрибутами и защита. Эти механизмы " "не зависят от того, как хранятся данные. В 4.4BSD имеется единая реализация " "для предоставления этих сервисов." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:683 msgid "" "The other part of the local filesystem is the organization and management of " "the data on the storage media. Laying out the contents of files on the " "storage media is the responsibility of the filestore. 4.4BSD supports three " "different filestore layouts:" msgstr "" "Другой частью локальной файловой системы является организация и управление " "данными на носителях информации. Размещение содержимого файлов на носителях " "является вопросом хранилища файлов. В 4.4BSD поддерживает три различных типа " "хранилищ файлов:" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:685 msgid "The traditional Berkeley Fast Filesystem" msgstr "Традиционная файловая система Berkeley Fast Filesystem" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:687 msgid "" "The log-structured filesystem, based on the Sprite operating-system design " "crossref:design-44bsd[biblio-rosenblum, [Rosenblum & Ousterhout, 1992]]" msgstr "" "Журналируемая файловая система, основанная на архитектуре операционной " "системы Sprite crossref:design-44bsd[biblio-rosenblum, [Rosenblum & " "Ousterhout, 1992]]" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:688 msgid "A memory-based filesystem" msgstr "Файловая система в памяти" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:690 msgid "" "Although the organizations of these filestores are completely different, " "these differences are indistinguishable to the processes using the " "filestores." msgstr "" "Хотя организация этих хранилищ совершенно различна, эти различия скрыты от " "процессов, использующих файловые системы." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:695 msgid "" "The Fast Filesystem organizes data into cylinder groups. Files that are " "likely to be accessed together, based on their locations in the filesystem " "hierarchy, are stored in the same cylinder group. Files that are not " "expected to accessed together are moved into different cylinder groups. " "Thus, files written at the same time may be placed far apart on the disk." msgstr "" "В файловой системе Fast Filesystem организует данные в группы дорожек. " "Файлы, к которым, скорее всего, будет осуществляться доступ одновременно (на " "основе их расположения в иерархии файловой системы), хранятся на одной и той " "же группе дорожек. Файлы, к которым не предполагается одновременный доступ, " "перемещаются на разные группы дорожек. Таким образом, файлы, записываемые в " "одно и то же время, могут располагаться в абсолютно разных областях диска." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:700 msgid "" "The log-structured filesystem organizes data as a log. All data being " "written at any point in time are gathered together, and are written at the " "same disk location. Data are never overwritten; instead, a new copy of the " "file is written that replaces the old one. The old files are reclaimed by a " "garbage-collection process that runs when the filesystem becomes full and " "additional free space is needed." msgstr "" "Файловая система с журнальной организацией организует данные в виде журнала. " "Все данные, записываемые в некоторый момент времени, собираются вместе и " "записываются в одно и то же место диска. Данные никогда не перезаписываются; " "вместо этого записывается новая копия файла, которая заменяет старую. Старые " "файлы уничтожаются процессом-сборщиком мусора, который запускается, когда " "файловая система переполняется и появляется необходимость в свободном " "пространстве." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:704 msgid "" "The memory-based filesystem is designed to store data in virtual memory. It " "is used for filesystems that need to support fast but temporary data, such " "as `/tmp`. The goal of the memory-based filesystem is to keep the storage " "packed as compactly as possible to minimize the usage of virtual-memory " "resources." msgstr "" "Файловая система в памяти предназначена для хранения данных в виртуальной " "памяти. Она используется для файловых систем, в которых должны храниться " "временные данные с обеспечением быстрого доступа к ним, к примеру, " "[.filename]#/tmp#. При организации файловой системы в памяти преследуется " "цель организовать максимально компактное хранение данных для минимизации " "использования ресурсов виртуальной памяти." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:706 #, no-wrap msgid "Network Filesystem" msgstr "Сетевая файловая система" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:712 msgid "" "Initially, networking was used to transfer data from one machine to " "another. Later, it evolved to allowing users to log in remotely to another " "machine. The next logical step was to bring the data to the user, instead " "of having the user go to the data -- and network filesystems were born. " "Users working locally do not experience the network delays on each " "keystroke, so they have a more responsive environment." msgstr "" "Изначально сетевые возможности использовались для передачи данных от одной " "машины к другой. Позже это получило свое развитие в обеспечении подключения " "пользователей удаленно к другим машинам. Следующим логическим шагом было " "предоставление данных пользователю, а не приближение пользователя к данным - " "так родились сетевые файловые системы. Пользователи, работающие локально, не " "ощущают сетевых задержек при каждом нажатии клавиши, так что они получают " "более удобное рабочее окружение." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:718 msgid "" "Bringing the filesystem to a local machine was among the first of the major " "client-server applications. The _server_ is the remote machine that exports " "one or more of its filesystems. The _client_ is the local machine that " "imports those filesystems. From the local client's point of view, a " "remotely mounted filesystem appears in the file-tree name space just like " "any other locally mounted filesystem. Local clients can change into " "directories on the remote filesystem, and can read, write, and execute " "binaries within that remote filesystem identically to the way that they can " "do these operations on a local filesystem." msgstr "" "Подключение файловой системы к локальной машине было одним из первых " "основных клиент-серверных приложений. _Сервер_ является удаленной машиной, " "которая экспортирует одну или более своих файловых систем. _Клиентом_ " "является локальная машина, которая импортирует эти файловые системы. С точки " "зрения локального клиента, смонтированные удаленные файловые системы " "появляются в пространстве имен дерева файлов, как любая другая локально " "смонтированная файловая система. Локальные клиенты могут перемещаться в " "каталоги на удаленной файловой системе, и могут осуществлять чтение, запись " "и выполнение двоичных файлов на удаленной файловой системе точно так же, как " "они выполняют эти операции на локальной файловой системе." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:723 msgid "" "When the local client does an operation on a remote filesystem, the request " "is packaged and is sent to the server. The server does the requested " "operation and returns either the requested information or an error " "indicating why the request was denied. To get reasonable performance, the " "client must cache frequently accessed data. The complexity of remote " "filesystems lies in maintaining cache consistency between the server and its " "many clients." msgstr "" "Когда локальный клиент выполняет операцию на удаленной файловой системе, " "оформляется и посылается запрос к серверу. Сервер выполняет запрошенную " "операцию и возвращает либо запрошенную информацию, либо ошибку, почему " "запрос был отклонен. Для получения удовлетворительной производительности, " "клиент должен кэшировать данные, к которым доступ осуществляется часто. " "Сложность удаленных файловых систем отражается на поддержке соответствия " "между сервером и множеством его клиентов." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:729 msgid "" "Although many remote-filesystem protocols have been developed over the " "years, the most pervasive one in use among UNIX systems is the Network " "Filesystem (NFS), whose protocol and most widely used implementation were " "done by Sun Microsystems. The 4.4BSD kernel supports the NFS protocol, " "although the implementation was done independently from the protocol " "specification crossref:design-44bsd[biblio-macklem, [Macklem, 1994]]. The " "NFS protocol is described in Chapter 9." msgstr "" "Хотя за эти годы было разработано множество протоколов работы с удаленными " "файловыми системами, самой распространенной на системах UNIX является " "сетевая файловая система Network Filesystem (NFS), которая была " "спроектирована и реализована в Sun Microsystems. Ядро 4.4BSD поддерживает " "протокол NFS, хотя его реализация была выполнена независимо от спецификаций " "протокола crossref:design-44bsd[biblio-macklem, [Macklem, 1994]]. Протокол " "NFS описан в Главе 9." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:731 #, no-wrap msgid "Terminals" msgstr "Терминалы" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:736 msgid "" "Terminals support the standard system I/O operations, as well as a " "collection of terminal-specific operations to control input-character " "editing and output delays. At the lowest level are the terminal device " "drivers that control the hardware terminal ports. Terminal input is handled " "according to the underlying communication characteristics, such as baud " "rate, and according to a set of software-controllable parameters, such as " "parity checking." msgstr "" "Терминалы поддерживают стандартные системные операции ввода/вывода, а также " "набор операций, специфичных для терминалов, для управления редактированием " "входных символов и задержек вывода. На самом нижнем уровне находятся " "драйверы терминальных устройств, которые управляют портами аппаратных " "терминалов. Терминальный ввод обрабатывается согласно низлежащим " "характеристикам связи, таким, как скорость передачи, и согласно набору " "программно контролируемых параметров, таких, как контроль четности." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:740 msgid "" "Layered above the terminal device drivers are line disciplines that provide " "various degrees of character processing. The default line discipline is " "selected when a port is being used for an interactive login. The line " "discipline is run in _canonical mode_; input is processed to provide " "standard line-oriented editing functions, and input is presented to a " "process on a line-by-line basis." msgstr "" "Выше уровня драйверов терминальных устройств находятся режимы каналов, " "которые обеспечивают различные уровни обработки символов. По умолчанию режим " "работы канала выбирается, когда порт используется для интерактивного входа в " "систему. Режим работы канала устанавливается в _канонический_; входной поток " "обрабатывается так, что обеспечиваются стандартные функции, ориентированные " "на редактирование строк, и он представляется процессу в виде целых строк." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:744 msgid "" "Screen editors and programs that communicate with other computers generally " "run in _noncanonical mode_ (also commonly referred to as _raw mode_ or " "_character-at-a-time mode_). In this mode, input is passed through to the " "reading process immediately and without interpretation. All special-" "character input processing is disabled, no erase or other line editing " "processing is done, and all characters are passed to the program that is " "reading from the terminal." msgstr "" "Экранные редакторы и программы, которые взаимодействуют с другими машинами, " "обычно работают в _неканоническом режиме_ (часто называемом _raw-режимом_ " "или _посимвольным режимом_). В этом режиме входной поток передается в " "читающий процесс сразу же и без всякой обработки. Выключается вся обработка " "специальных символов, не выполняется удаление символов и другое " "редактирование строк, все символы передаются программе, которая выполняет " "чтение с терминала." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:747 msgid "" "It is possible to configure the terminal in thousands of combinations " "between these two extremes. For example, a screen editor that wanted to " "receive user interrupts asynchronously might enable the special characters " "that generate signals and enable output flow control, but otherwise run in " "noncanonical mode; all other characters would be passed through to the " "process uninterpreted." msgstr "" "Терминал может быть настроен тысячами различных способов, промежуточных " "между этими двумя. Например, экранный редактор, которому необходимо получать " "прерывания от пользователя асинхронно, может разрешить использование " "специальных символов, которые генерируют сигналы и разрешить управление " "выходным потоком, в противном случае работать в неканоническом режиме; все " "остальные символы будут передаваться в процесс необработанными." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:749 msgid "" "On output, the terminal handler provides simple formatting services, " "including" msgstr "" "Что касается выходного потока, то терминальный обработчик предоставляет " "простые службы по его форматированию, включая" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:751 msgid "" "Converting the line-feed character to the two-character carriage-return-line-" "feed sequence" msgstr "" "Преобразование символа перевода строки на двухсимвольную последовательность " "из символов возврата каретки и перевода строки" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:752 msgid "Inserting delays after certain standard control characters" msgstr "Выдерживание пауз после некоторых стандартных управляющих символов" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:753 msgid "Expanding tabs" msgstr "Замещение символов табуляции" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:754 msgid "" "Displaying echoed nongraphic ASCII characters as a two-character sequence of " "the form `^C` (i.e., the ASCII caret character followed by the ASCII " "character that is the character's value offset from the ASCII `@` character)." msgstr "" "Вывод неграфических символов ASCII в виде двухсимвольных последовательностей " "вида `^C` (другими словами, вывод знака вставки, за которым следует символ, " "который находится по смещению от символа `@`, соответствующему значению " "этого символа)." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:756 msgid "" "Each of these formatting services can be disabled individually by a process " "through control requests." msgstr "" "Каждый из этих сервисов преобразования может быть независимо выключен " "процессом при помощи управляющих запросов." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:758 #, no-wrap msgid "Interprocess Communication" msgstr "Межпроцессное взаимодействие" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:762 msgid "" "Interprocess communication in 4.4BSD is organized in _communication " "domains_. Domains currently supported include the _local domain_, for " "communication between processes executing on the same machine; the _internet " "domain_, for communication between processes using the TCP/IP protocol suite " "(perhaps within the Internet); the ISO/OSI protocol family for communication " "between sites required to run them; and the _XNS domain_, for communication " "between processes using the XEROX Network Systems (XNS) protocols." msgstr "" "Межпроцессные коммуникации в 4.4BSD организованы в _коммуникационные " "домены_. К поддерживаемым на данный момент доменам относятся _локальный " "домен_ для взаимодействия между процессами, выполняющимися на одной и той же " "машине; _межсетевой домен_ для связи между процессами посредством набора " "протоколов TCP/IP (возможно, в сети Интернет); семейство протоколов ISO/OSI " "для взаимодействия между сайтами, которым нужна именно такая связь, и _домен " "XNS_ для коммуникаций между процессами при помощи протоколов XEROX Network " "Systems (XNS)." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:766 msgid "" "Within a domain, communication takes place between communication endpoints " "known as _sockets_. As mentioned in Section 2.6, the _socket_ system call " "creates a socket and returns a descriptor; other IPC system calls are " "described in Chapter 11. Each socket has a type that defines its " "communications semantics; these semantics include properties such as " "reliability, ordering, and prevention of duplication of messages." msgstr "" "В пределах домена соединения имеют место между конечными точками связи, " "также называемыми _сокетами_. Как отмечено в Разделе 2.6, системный вызов " "_socket_ создает сокет и возвращает дескриптор; другие системные вызовы IPC " "описаны в Главе 11. Каждый сокет имеет тип, определяющий его " "коммуникационные свойства; к ним относятся такие характеристики, как " "надежность, сохранение последовательности передаваемой информации и " "предупреждение дублирования сообщений." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:770 msgid "" "Each socket has associated with it a _communication protocol_. This " "protocol provides the semantics required by the socket according to the " "latter's type. Applications may request a specific protocol when creating a " "socket, or may allow the system to select a protocol that is appropriate for " "the type of socket being created." msgstr "" "с каждым сокетом связан некоторый _коммуникационный протокол_. Этот протокол " "обеспечивает выполнение операций, требуемых сокету, согласно его типу. " "Приложения могут задавать нужный протокол при создании сокета или могут " "разрешить системе выбрать протокол, который соответствует типу создаваемого " "сокета." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:774 msgid "" "Sockets may have addresses bound to them. The form and meaning of socket " "addresses are dependent on the communication domain in which the socket is " "created. Binding a name to a socket in the local domain causes a file to be " "created in the filesystem." msgstr "" "Сокеты могут иметь адреса, связанные с ними. Формат и смысл адресов сокетов " "зависят от коммуникационного домена, в котором был создан сокет. Привязка " "имени к сокету в локальном домене приводит к созданию файла в файловой " "системе." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:779 msgid "" "Normal data transmitted and received through sockets are untyped. Data-" "representation issues are the responsibility of libraries built on top of " "the interprocess-communication facilities. In addition to transporting " "normal data, communication domains may support the transmission and " "reception of specially typed data, termed _access rights_. The local " "domain, for example, uses this facility to pass descriptors between " "processes." msgstr "" "Обычные данные, передаваемые и получаемые при помощи сокетов, не имеют типа. " "Вопросы представления данных зависят от библиотек, которые находятся на " "верху коммуникационной подсистемы. Вдобавок к передаче обычных данных, " "коммуникационные домены могут поддерживать передачу и прием специальных " "типов данных, которые называются _правами доступа_. Например, локальный " "домен использует эту возможность для передачи дескрипторов между процессами." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:785 msgid "" "Networking implementations on UNIX before 4.2BSD usually worked by " "overloading the character-device interfaces. One goal of the socket " "interface was for naive programs to be able to work without change on stream-" "style connections. Such programs can work only if the _read_ and _write_ " "systems calls are unchanged. Consequently, the original interfaces were " "left intact, and were made to work on stream-type sockets. A new interface " "was added for more complicated sockets, such as those used to send " "datagrams, with which a destination address must be presented with each " "_send_ call." msgstr "" "До 4.2BSD сетевые реализации в UNIX обычно работали через интерфейсы " "символьных устройств. Одной из целей создания интерфейса сокетов было " "обеспечение работы простеньким программам без изменения на потоковых " "соединениях. Такие программы могут работать, если только не меняются " "системные вызовы _read_ и _write_. Соответственно, оригинальные интерфейсы " "не трогались, но были исправлены для работы с потоковыми сокетами. Для более " "сложных сокетов, таких, как те, что используются для посылки датаграмм и в " "которых при каждом вызове _send_ должен указываться адрес назначения, был " "добавлен новый интерфейс." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:790 msgid "" "Another benefit is that the new interface is highly portable. Shortly after " "a test release was available from Berkeley, the socket interface had been " "ported to System III by a UNIX vendor (although AT&T did not support the " "socket interface until the release of System V Release 4, deciding instead " "to use the Eighth Edition stream mechanism). The socket interface was also " "ported to run in many Ethernet boards by vendors, such as Excelan and " "Interlan, that were selling into the PC market, where the machines were too " "small to run networking in the main processor. More recently, the socket " "interface was used as the basis for Microsoft's Winsock networking interface " "for Windows." msgstr "" "Другим достоинством является то, что новый интерфейс легко переносим. Вскоре " "после тестового релиза, полученного из Беркли, интерфейс сокетов был " "перенесен в System III поставщиком UNIX (хотя AT&T не поддерживала интерфейс " "сокетов до выхода System V Release 4, решив использовать вместо него " "механизм потоков из Eighth Edition). Интерфейс сокетов был также перенесен " "для работы на многих адаптерах Ethernet поставщиками, такими, как Excelan и " "Interlan, который продавался на рынке PC, где компьютеры были слишком " "слабыми, чтобы обрабатывать сетевой код на основном процессоре. Сравнительно " "недавно интерфейс сокетов был использован в качестве основы для сетевого " "интерфейса Winsock от Microsoft для Windows." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:792 #, no-wrap msgid "Network Communication" msgstr "Сетевые коммуникации" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:797 msgid "" "Some of the communication domains supported by the _socket_ IPC mechanism " "provide access to network protocols. These protocols are implemented as a " "separate software layer logically below the socket software in the kernel. " "The kernel provides many ancillary services, such as buffer management, " "message routing, standardized interfaces to the protocols, and interfaces to " "the network interface drivers for the use of the various network protocols." msgstr "" "Некоторые из коммуникационных доменов, поддерживаемых IPC-механизмом " "_сокетов_ дают доступ к сетевым протоколам. Эти протоколы реализованы как " "отдельный программный слой, логически находящийся ниже программного " "обеспечения сокетов в ядре. Ядро предоставляет много вспомогательных " "сервисов, таких, как управление буферами, маршрутизация сообщений, " "стандартные интерфейсы к протоколам и интерфейсы к драйверам сетевых " "интерфейсов для использования в различных сетевых протоколах." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:806 msgid "" "At the time that 4.2BSD was being implemented, there were many networking " "protocols in use or under development, each with its own strengths and " "weaknesses. There was no clearly superior protocol or protocol suite. By " "supporting multiple protocols, 4.2BSD could provide interoperability and " "resource sharing among the diverse set of machines that was available in the " "Berkeley environment. Multiple-protocol support also provides for future " "changes. Today's protocols designed for 10- to 100-Mbit-per-second " "Ethernets are likely to be inadequate for tomorrow's 1- to 10-Gbit-per-" "second fiber-optic networks. Consequently, the network-communication layer " "is designed to support multiple protocols. New protocols are added to the " "kernel without the support for older protocols being affected. Older " "applications can continue to operate using the old protocol over the same " "physical network as is used by newer applications running with a newer " "network protocol." msgstr "" "В те времена, когда разрабатывалась 4.2BSD, использовалось или " "разрабатывалось много сетевых протоколов, каждый со своими сильными и " "слабыми сторонами. Не существует единственного подходящего на все случаи " "жизни протокола или набора протоколов. Поддерживая много протоколов, 4.2BSD " "может обеспечить взаимодействие и обмен ресурсами между различными машинами, " "которые были доступны в Беркли. Поддержка многих протоколов необходим также " "для изменений в будущем. Современные протоколы, разработанные для Ethernet " "со скоростями работы 10 и 100 Mbit в секунду, вряд ли будут соответствовать " "для завтрашних оптических сетей пропускной способностью 1 и 10 Gbit в " "секунду. Поэтому уровень сетевых коммуникаций разработан с учетом поддержки " "многих протоколов. Новые протоколы добавляются к ядру, не затрагивая " "поддержку старых протоколов. Старые приложения могут продолжать работать с " "использованием старых протоколов в той же самой физической сети, что " "использовалась для новых приложений, работающих с новым сетевым протоколом." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:808 #, no-wrap msgid "Network Implementation" msgstr "Сетевая реализация" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:815 msgid "" "The first protocol suite implemented in 4.2BSD was DARPA's Transmission " "Control Protocol/Internet Protocol (TCP/IP). The CSRG chose TCP/IP as the " "first network to incorporate into the socket IPC framework, because a 4.1BSD-" "based implementation was publicly available from a DARPA-sponsored project " "at Bolt, Beranek, and Newman (BBN). That was an influential choice: The " "4.2BSD implementation is the main reason for the extremely widespread use of " "this protocol suite. Later performance and capability improvements to the " "TCP/IP implementation have also been widely adopted. The TCP/IP " "implementation is described in detail in Chapter 13." msgstr "" "Первым набором протоколов, реализованным в 4.2BSD, был Transmission Control " "Protocol/Internet Protocol (TCP/IP) от DARPA. CSRG выбрала TCP/IP в качестве " "первого для включения в набор протоколов IPC, потому что реализация на " "основе 4.1 была всем доступна из проекта, спонсируемого DARPA, в Bolt, " "Beranek и Newman (BBN). Это был выбор, повлиявший на многое: Реализация в " "4.2BSD стала основной причиной очень широкой распространенности и " "использования этого набора протоколов. Более поздние усовершенствования " "производительности и возможностей TCP/IP были также широко приняты. " "Реализация TCP/IP подробно описана в Главе 13." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:818 msgid "" "The release of 4.3BSD added the Xerox Network Systems (XNS) protocol suite, " "partly building on work done at the University of Maryland and at Cornell " "University. This suite was needed to connect isolated machines that could " "not communicate using TCP/IP." msgstr "" "В релизе 4.3BSD появился набор протоколов Xerox Network Systems (XNS), " "частично основанный на работе, выполненной в Университете Мэрилэнда и " "Университете Корнелла. Этот набор был нужен для объединения отдельных машин, " "которые не могли работать с протоколом TCP/IP." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:824 msgid "" "The release of 4.4BSD added the ISO protocol suite because of the latter's " "increasing visibility both within and outside the United States. Because of " "the somewhat different semantics defined for the ISO protocols, some minor " "changes were required in the socket interface to accommodate these " "semantics. The changes were made such that they were invisible to clients " "of other existing protocols. The ISO protocols also required extensive " "addition to the two-level routing tables provided by the kernel in 4.3BSD. " "The greatly expanded routing capabilities of 4.4BSD include arbitrary levels " "of routing with variable-length addresses and network masks." msgstr "" "В релиз 4.4BSD был добавлен набор протоколов ISO из-за его все большей " "распространенности как внутри, так и во вне США. По причине использования в " "протоколах ISO несколько другого подхода к сети, в интерфейсе сокетов " "потребовалось сделать некоторые небольшие изменения для реализации этого " "подхода. Изменения были сделаны так, что они были незаметны для клиентов " "других существующих протоколов. Протоколы ISO требуют также большой работы с " "двухуровневыми таблицами маршрутизации, имеющимися в 4.3BSD. К значительно " "расширенным возможностям по маршрутизации в 4.4BSD относятся раздельные " "уровни маршрутизации с адресами переменной длины и сетевыми масками." #. type: Title === #: documentation/content/en/books/design-44bsd/_index.adoc:826 #, no-wrap msgid "System Operation" msgstr "Работа системы" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:834 msgid "" "Bootstrapping mechanisms are used to start the system running. First, the " "4.4BSD kernel must be loaded into the main memory of the processor. Once " "loaded, it must go through an initialization phase to set the hardware into " "a known state. Next, the kernel must do autoconfiguration, a process that " "finds and configures the peripherals that are attached to the processor. " "The system begins running in single-user mode while a start-up script does " "disk checks and starts the accounting and quota checking. Finally, the " "start-up script starts the general system services and brings up the system " "to full multiuser operation." msgstr "" "Механизмы начальной загрузки используются для запуска системы. Сначала ядро " "4.4BSD должно быть загружено в основную память процессора. После загрузки " "оно должно пройти через фазу инициализации для установки аппаратуры в " "известное состояние. Затем ядро должно выполнить автоконфигурацию, в " "процессе которой распознаются и настраиваются периферийные устройства, " "подключенные к процессору. Система начинает работу в однопользовательском " "режиме, пока начальный скрипт выполняет проверку дисков и включает подсчет " "статистики и использования квот. Наконец, начальный скрипт запускает " "общесистемные службы и переводит систему в полностью многопользовательский " "режим." #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:838 msgid "" "During multiuser operation, processes wait for login requests on the " "terminal lines and network ports that have been configured for user access. " "When a login request is detected, a login process is spawned and user " "validation is done. When the login validation is successful, a login shell " "is created from which the user can run additional processes." msgstr "" "При работе в многопользовательском режиме процессы ждут запросов на вход в " "систему с терминальных линий и сетевых портов, которые были настроены на " "вход пользователей. После обнаружения запроса на вход, вызывается процесс " "входа в систему и выполняется аутентификация пользователя. Если она прошла " "успешно, запускается начальная оболочка, из которой пользователь может " "запускать дополнительные процессы." #. type: Title == #: documentation/content/en/books/design-44bsd/_index.adoc:843 #, no-wrap msgid "References" msgstr "Список литературы" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:846 msgid "" "[[biblio-accetta]] Accetta et al, 1986 Mach: A New Kernel Foundation for " "UNIX Development\" M.Accetta R.Baron W.Bolosky D.Golub R.Rashid A.Tevanian " "M.Young 93-113 USENIX Association Conference Proceedings USENIX Association " "June 1986" msgstr "" "[[biblio-accetta]] Accetta et al, 1986 Mach: A New Kernel Foundation for " "UNIX Development\" M.Accetta R.Baron W.Bolosky D.Golub R.Rashid A.Tevanian " "M.Young 93-113 USENIX Association Conference Proceedings USENIX Association " "June 1986" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:848 msgid "" "[[biblio-cheriton]] Cheriton, 1988 The V Distributed System D. R.Cheriton " "314-333 Comm ACM, 31, 3 March 1988" msgstr "" "[[biblio-cheriton]] Cheriton, 1988 The V Distributed System D. R.Cheriton " "314-333 Comm ACM, 31, 3 March 1988" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:850 msgid "" "[[biblio-ewens]] Ewens et al, 1985 Tunis: A Distributed Multiprocessor " "Operating System P.Ewens D. R.Blythe M.Funkenhauser R. C.Holt 247-254 USENIX " "Assocation Conference Proceedings USENIX Association June 1985" msgstr "" "[[biblio-ewens]] Ewens et al, 1985 Tunis: A Distributed Multiprocessor " "Operating System P.Ewens D. R.Blythe M.Funkenhauser R. C.Holt 247-254 USENIX " "Assocation Conference Proceedings USENIX Association June 1985" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:852 msgid "" "[[biblio-gingell]] Gingell et al, 1987 Virtual Memory Architecture in SunOS " "R.Gingell J.Moran W.Shannon 81-94 USENIX Association Conference Proceedings " "USENIX Association June 1987" msgstr "" "[[biblio-gingell]] Gingell et al, 1987 Virtual Memory Architecture in SunOS " "R.Gingell J.Moran W.Shannon 81-94 USENIX Association Conference Proceedings " "USENIX Association June 1987" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:854 msgid "" "[[biblio-kernighan]] Kernighan & Pike, 1984 The UNIX Programming Environment " "B. W.Kernighan R.Pike Prentice-Hall Englewood Cliffs NJ 1984" msgstr "" "[[biblio-kernighan]] Kernighan & Pike, 1984 The UNIX Programming Environment " "B. W.Kernighan R.Pike Prentice-Hall Englewood Cliffs NJ 1984" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:856 msgid "" "[[biblio-macklem]] Macklem, 1994 The 4.4BSD NFS Implementation R.Macklem " "6:1-14 4.4BSD System Manager's Manual O'Reilly & Associates, Inc. Sebastopol " "CA 1994" msgstr "" "[[biblio-macklem]] Macklem, 1994 The 4.4BSD NFS Implementation R.Macklem " "6:1-14 4.4BSD System Manager's Manual O'Reilly & Associates, Inc. Sebastopol " "CA 1994" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:858 msgid "" "[[biblio-mckusick-2]] McKusick & Karels, 1988 Design of a General Purpose " "Memory Allocator for the 4.3BSD UNIX Kernel M. K.McKusick M. J.Karels " "295-304 USENIX Assocation Conference Proceedings USENIX Assocation June 1998" msgstr "" "[[biblio-mckusick-2]] McKusick & Karels, 1988 Design of a General Purpose " "Memory Allocator for the 4.3BSD UNIX Kernel M. K.McKusick M. J.Karels " "295-304 USENIX Assocation Conference Proceedings USENIX Assocation June 1998" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:860 msgid "" "[[biblio-mckusick-1]] McKusick et al, 1994 Berkeley Software Architecture " "Manual, 4.4BSD Edition M. K.McKusick M. J.Karels S. J.Leffler W. N.Joy R. " "S.Faber 5:1-42 4.4BSD Programmer's Supplementary Documents O'Reilly & " "Associates, Inc. Sebastopol CA 1994" msgstr "" "[[biblio-mckusick-1]] McKusick et al, 1994 Berkeley Software Architecture " "Manual, 4.4BSD Edition M. K.McKusick M. J.Karels S. J.Leffler W. N.Joy R. " "S.Faber 5:1-42 4.4BSD Programmer's Supplementary Documents O'Reilly & " "Associates, Inc. Sebastopol CA 1994" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:862 msgid "" "[[biblio-ritchie]] Ritchie, 1988 Early Kernel Design private communication " "D. M.Ritchie March 1988" msgstr "" "[[biblio-ritchie]] Ritchie, 1988 Early Kernel Design private communication " "D. M.Ritchie March 1988" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:864 msgid "" "[[biblio-rosenblum]] Rosenblum & Ousterhout, 1992 The Design and " "Implementation of a Log-Structured File System M.Rosenblum K.Ousterhout " "26-52 ACM Transactions on Computer Systems, 10, 1 Association for Computing " "Machinery February 1992" msgstr "" "[[biblio-rosenblum]] Rosenblum & Ousterhout, 1992 The Design and " "Implementation of a Log-Structured File System M.Rosenblum K.Ousterhout " "26-52 ACM Transactions on Computer Systems, 10, 1 Association for Computing " "Machinery February 1992" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:866 msgid "" "[[biblio-rozier]] Rozier et al, 1988 Chorus Distributed Operating Systems " "M.Rozier V.Abrossimov F.Armand I.Boule M.Gien M.Guillemont F.Herrmann " "C.Kaiser S.Langlois P.Leonard W.Neuhauser 305-370 USENIX Computing Systems, " "1, 4 Fall 1988" msgstr "" "[[biblio-rozier]] Rozier et al, 1988 Chorus Distributed Operating Systems " "M.Rozier V.Abrossimov F.Armand I.Boule M.Gien M.Guillemont F.Herrmann " "C.Kaiser S.Langlois P.Leonard W.Neuhauser 305-370 USENIX Computing Systems, " "1, 4 Fall 1988" #. type: Plain text #: documentation/content/en/books/design-44bsd/_index.adoc:867 msgid "" "[[biblio-tevanian]] Tevanian, 1987 Architecture-Independent Virtual Memory " "Management for Parallel and Distributed Environments: The Mach Approach " "Technical Report CMU-CS-88-106, A.Tevanian Department of Computer Science, " "Carnegie-Mellon University Pittsburgh PA December 1987" msgstr "" "[[biblio-tevanian]] Tevanian, 1987 Architecture-Independent Virtual Memory " "Management for Parallel and Distributed Environments: The Mach Approach " "Technical Report CMU-CS-88-106, A.Tevanian Department of Computer Science, " "Carnegie-Mellon University Pittsburgh PA December 1987"