С and linux programming interface

Linux Programming Interface

The Linux Programming Interface (TLPI) is the definitive guide to the Linux and UNIX programming interface—the interface employed by nearly every application that runs on a Linux or UNIX system.

In this authoritative work, Linux programming expert Michael Kerrisk provides detailed descriptions of the system calls and library functions that you need in order to master the craft of system programming, and accompanies his explanations with clear, complete example programs.

You’ll find descriptions of over 500 system calls and library functions, and more than 200 example programs, 88 tables, and 115 diagrams. You’ll learn how to:

  • Read and write files efficiently
  • Use signals, clocks, and timers
  • Create processes and execute programs
  • Write secure programs
  • Write multithreaded programs using POSIX threads
  • Build and use shared libraries
  • Perform interprocess communication using pipes, message queues, shared memory, and semaphores
  • Write network applications with the sockets API

While The Linux Programming Interface covers a wealth of Linux-specific features, including epoll, inotify, and the /proc file system, its emphasis on UNIX standards (POSIX.1-2001/SUSv3 and POSIX.1-2008/SUSv4) makes it equally valuable to programmers working on other UNIX platforms.

The Linux Programming Interface is the most comprehensive single-volume work on the Linux and UNIX programming interface, and a book that’s destined to become a new classic.

Michael Kerrisk has been using and programming UNIX systems for more than 20 years, and has taught many week-long courses on UNIX system programming. Since 2004, he has maintained the man-pages project (http://www.kernel.org/doc/man-pages/), which produces the manual pages describing the Linux kernel and glibc programming APIs. He has written or co-written more than 250 of the manual pages and is actively involved in the testing and design review of new Linux kernel-userspace interfaces. Michael lives with his family in Munich, Germany.

Chapter 1: History and Standards
Chapter 2: Fundamental Concepts
Chapter 3: System Programming Concepts
Chapter 4: File I/O: The Universal I/O Model
Chapter 5: File I/O: Further Details
Chapter 6: Processes
Chapter 7: Memory Allocation
Chapter 8: Users and Groups
Chapter 9: Process Credentials
Chapter 10: Time
Chapter 11: System Limits and Options
Chapter 12: System and Process Information
Chapter 13: File I/O Buffering
Chapter 14: File Systems
Chapter 15: File Attributes
Chapter 16: Extended Attributes
Chapter 17: Access Control Lists
Chapter 18: Directories and Links
Chapter 19: Monitoring File Events
Chapter 20: Signals: Fundamental Concepts
Chapter 21: Signals: Signal Handlers
Chapter 22: Signals: Advanced Features
Chapter 23: Timers and Sleeping
Chapter 24: Process Creation
Chapter 25: Process Termination
Chapter 26: Monitoring Child Processes
Chapter 27: Program Execution
Chapter 28: Process Creation and Program Execution in More Detail
Chapter 29: Threads: Introduction
Chapter 30: Threads: Thread Synchronization
Chapter 31: Threads: Thread Safety and Per-Thread Storage
Chapter 32: Threads: Thread Cancellation
Chapter 33: Threads: Further Details
Chapter 34: Process Groups, Sessions, and Job Control
Chapter 35: Process Priorities and Scheduling
Chapter 36: Process Resources
Chapter 37: Daemons
Chapter 38: Writing Secure Privileged Programs
Chapter 39: Capabilities
Chapter 40: Login Accounting
Chapter 41: Fundamentals of Shared Libraries
Chapter 42: Advanced Features of Shared Libraries
Chapter 43: Interprocess Communication Overview
Chapter 44: Pipes and FIFOs
Chapter 45: Introduction to System V IPC
Chapter 46: System V Message Queues
Chapter 47: System V Semaphores
Chapter 48: System V Shared Memory
Chapter 49: Memory Mappings
Chapter 50: Virtual Memory Operations
Chapter 51: Introduction to POSIX IPC
Chapter 52: POSIX Message Queues
Chapter 53: POSIX Semaphores
Chapter 54: POSIX Shared Memory
Chapter 55: File Locking
Chapter 56: Sockets: Introduction
Chapter 57: Sockets: UNIX Domain
Chapter 58: Sockets: Fundamentals of TCP/IP Networks
Chapter 59: Sockets: Internet Domains
Chapter 60: Sockets: Server Design
Chapter 61: Sockets: Advanced Topics
Chapter 62: Terminals
Chapter 63: Alternative I/O Models
Chapter 64: Pseudoterminals

Читайте также:  Yandex disk linux manjaro

Appendix A: Tracing System Calls
Appendix B: Parsing Command-Line Options
Appendix C: Casting the NULL Pointer
Appendix D: Kernel Configuration
Appendix E: Further Sources of Information
Appendix F: Solutions to Selected Exercises

View the detailed Table of Contents (PDF)
View the Index (PDF)

«If I had to choose a single book to sit next to my machine when writing software for Linux, this would be it.»
Martin Landers, Software Engineer, Google

«Everything relating to the subject that I could reasonably think of is in the book, in a very thorough and maniacally complete yet enjoyably readable way.»
Federico Lucifredi, Slashdot.org (Read More)

«This book, with its detailed descriptions and examples, contains everything you need to understand the details and nuances of the low-level programming APIs in Linux . . . no matter what the level of reader, there will be something to be learnt from this book.»
Mel Gorman, Author of Understanding the Linux Virtual Memory Manager

«Michael Kerrisk has not only written a great book about Linux programming and how it relates to various standards, but has also taken care that bugs he noticed got fixed and the man pages were (greatly) improved. In all three ways, he has made Linux programming easier. The in-depth treatment of topics in The Linux Programming Interface . . . makes it a must-have reference for both new and experienced Linux programmers.»
Andreas Jaeger, Program Manager, openSUSE, Novell

«Michael’s inexhaustible determination to get his information right, and to express it clearly and concisely, has resulted in a strong reference source for programmers. While this work is targeted at Linux programmers, it will be of value to any programmer working in the UNIX/POSIX ecosystem.»
David Butenhof, Author of Programming with POSIX Threads and Contributor to the POSIX and UNIX Standards

«. . . a very thorough—yet easy to read—explanation of UNIX system and network programming, with an emphasis on Linux systems. It’s certainly a book I’d recommend to anybody wanting to get into UNIX programming (in general) or to experienced UNIX programmers wanting to know ‘what’s new’ in the popular GNU/Linux system.»
Fernando Gont, Network Security Researcher, IETF Participant, and RFC Author

«. . . encyclopedic in the breadth and depth of its coverage, and textbook-like in its wealth of worked examples and exercises. Each topic is clearly and comprehensively covered, from theory to hands-on working code. Professionals, students, educators, this is the Linux/UNIX reference that you have been waiting for.»
Anthony Robins, Associate Professor of Computer Science, The University of Otago

«I’ve been very impressed by the precision, the quality and the level of detail Michael Kerrisk put in his book. He is a great expert of Linux system calls and lets us share his knowledge and understanding of the Linux APIs.»
Christophe Blaess, Author of Programmation système en C sous Linux

«. . . an essential resource for the serious or professional Linux and UNIX systems programmer. Michael Kerrisk covers the use of all the key APIs across both the Linux and UNIX system interfaces with clear descriptions and tutorial examples and stresses the importance and benefits of following standards such as the Single UNIX Specification and POSIX 1003.1.»
Andrew Josey, Director, Standards, The Open Group, and Chair of The POSIX 1003.1 Working Group

Читайте также:  Как установить gcc линукс

«What could be better than an encyclopedic reference to the Linux system, from the standpoint of the system programmer, written by none other than the maintainer of the man pages himself? The Linux Programming Interface is comprehensive and detailed. I firmly expect it to become an indispensable addition to my programming bookshelf.»
Bill Gallmeister, Author of POSIX.4 Programmer’s Guide: Programming for the Real World

«. . . the most complete and up-to-date book about Linux and UNIX system programming. If you’re new to Linux system programming, if you’re a UNIX veteran focused on portability while interested in learning the Linux way, or if you’re simply looking for an excellent reference about the Linux programming interface, then Michael Kerrisk’s book is definitely the companion you want on your bookshelf.»
Loïc Domaigné, Chief Software Architect (Embedded), Corpuls.com

«I found The Linux Programming Interface to be extremely useful and expect to return to it frequently. Anyone who has an interest in programming for Linux will likely feel the same way.»
Jake Edge, LWN.net (Read More)

«Michael Kerrisk’s new book [is] a thing of beauty. A book you’re proud to just have on the shelf, but too useful to stay there.»
Serge Hallyn, Linux Kernel Developer

«If you think you don’t need this book since you know everything already, that’s what I thought too, and I was wrong.»
Bert Hubert, Netherlabs Computer Consulting

Источник

С and linux programming interface

Physics.Math.Code запись закреплена

Linux API исчерпывающее руководство [2019] Майкл Керриск

Linux Programming Interface – исчерпывающее руководство по программированию приложений для Linux и UNIX. Описанный здесь интерфейс применяется практически с любыми приложениями, работающими в операционных системах Linux или UNIX.

В этой авторитетной книге эксперт по Linux Майкл Керриск подробно описывает библиотечные вызовы и библиотечные функции, которые понадобятся вам при системном программировании. Вся теория сопровождается объяснениями на примерах четких и понятных полнофункциональных программ.

В этой книге представлено практически полное описание API системного програм­мирования под управлением Linux. Ее одержимое применимо к широкому диапазону Linux-платформ, начиная с обычных серверов, универсальных компьютеров и настоль­ных систем и заканчивая большим разнообразием встроенных устройств (в том числе работающих под управлением операционной системы Android), на которых в настоящее время запускается ОС Linux.

Англоязычное издание этой книги вышло в конце 2010 года. С того времени было вы пущено несколько обновлений ядра Linux (их было примерно по пять за год). Несмотря на это, содержимое оригинала книги, а следовательно, и данного перевода, не утратило актуальности и сохранит ее еще на долгие годы. Тому есть две причины.

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

Во-вторых, изменения вносятся в виде дополнений к интерфейсам, рассматриваемым в книге, а не модификаций уже существующих функциональных свойств, описанных в ней же. (Хочу еще раз отметить, что это вполне естественный ход разработки ядра Linux: спе­циалисты прилагают большие усилия к тому, чтобы ничего не нарушить в уже существу­ющем API пользовательского пространства.) Со дня выхода оригинала книги в данный API были внесены изменения.

Источник

Книга «Linux API. Исчерпывающее руководство»

Добрый день! Предлагаю вашему вниманию книгу «Linux API. Исчерпывающее руководство»(перевод книги The Linux Programming Interface). Ее можно заказать на сайте издательства, и если применить промокод LinuxAPI , то получите скидку 30%.

Читайте также:  Copy folder to linux from windows

Отрывок из книги для ознакомления:

Сокеты: архитектура сервера

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

Итерационные и параллельные серверы

Существуют две распространенные архитектуры сетевых серверов на основе сокетов:

итерационная: сервер обслуживает клиентов по одному, сначала обрабатывая запрос (или несколько запросов) одного клиента и затем переходя к следующему;

параллельная: сервер спроектирован для обслуживания нескольких клиентов одновременно.

В разделе 44.8 уже был представлен пример итерационного сервера на основе очередей FIFO.

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

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

В следующих разделах мы рассмотрим примеры итерационного и параллельного серверов на основе сокетов интернет-домена. Эти два сервера реализуют упрощенный вариант службы echo (RFC 862), которая возвращает копию любого сообщения, посланного ей клиентом.

Итерационный UDP-сервер echo

В этом и следующем разделе мы представим серверы для службы echo. Она доступна на порте с номером 7 и работает как по UDP, так и по TCP (данный порт зарезервирован, в связи с чем сервер echo необходимо запускать с привилегиями администратора).

UDP-сервер echo постоянно считывает датаграммы и возвращает отправителю их копии. Поскольку серверу нужно обрабатывать только одно сообщение за раз, здесь будет достаточно итерационной архитектуры. Заголовочный файл для серверов показан в листинге 56.1.

Листинг 56.1. Заголовочный файл для программ id_echo_sv.c и id_echo_cl.c

В листинге 56.2 представлена реализация сервера. Стоит отметить следующие моменты:

для перевода сервера в режим демона мы задействуем функцию becomeDaemon() из раздела 37.2;

чтобы сделать программу более компактной, мы используем библиотеку для работы с сокетами интернет-домена, разработанную в разделе 55.12;

если сервер не может вернуть ответ клиенту, то записывает сообщение в журнал, применяя вызов syslog().

В реальном приложении мы бы, скорее всего, ввели определенное ограничение на частоту записи сообщений с помощью syslog(). Это исключило бы возможность переполнения системного журнала злоумышленником. К тому же не стоит забывать, что каждый вызов syslog() довольно затратный, так как по умолчанию использует fsync().

Листинг 56.2. Итерационный сервер, который реализует UDP-службу echo

Для проверки работы сервера мы используем программу из листинга 56.3. В ней тоже применяется библиотека для работы с сокетами интернет-домена, разработанная в разделе 55.12. В качестве первого аргумента командной строки клиентская программа принимает имя сетевого узла, на котором находится сервер. Клиент входит в цикл, где отправляет серверу каждый из оставшихся аргументов в виде отдельных датаграмм, а затем считывает и выводит датаграммы, полученные от сервера в ответ.

Листинг 56.3. Клиент для UDP-службы echo

Ниже показан пример того, что мы увидим при запуске сервера и двух экземпляров клиента:

Источник

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