Operating Systems

Reading map

Previous: C Programming Reading map Next: Networks and Protocols

Volume II: Systems Programming (Chapter 5)Code & tests Chapter diagrams Download editable SVGs

An operating system is the program layer between user programs and the hardware. In this chapter the term mostly means the kernel: the privileged part of the system that controls hardware, handles interrupts, and performs system calls.

Chapter Map

Operating System

The word operating system is used in two related senses:

Term Meaning
Kernel The privileged program loaded at boot, controlling hardware and system calls
Operating environment Kernel plus utilities, configuration tools, libraries, shells, and graphical tools

Here, operating system and kernel mean the same thing unless the context says otherwise.

Kernel and User Programs

The processor supports two important execution modes.

Mode What runs there What is allowed
Privileged mode Kernel All CPU instructions, hardware control, memory management
Restricted mode User programs Only non-privileged instructions

Only the kernel runs in privileged mode. User programs cannot directly control devices, change memory protection, or affect the whole machine. They can only work with their own memory and ask the kernel for services.

Control returns from a user program to the kernel in three main cases:

Event Meaning
Hardware interrupt An external device needs attention
Exception The CPU cannot execute an instruction normally, for example division by zero
System call A user program deliberately asks the kernel for a service

This separation is the basic reason the system can protect tasks from each other and keep one broken program from damaging the whole machine.

Detailed notes - 5.1.1: Kernel and user programs

1

operating system in the narrow sense:

  • the program loaded first for ordinary operation
  • controls hardware
  • handles interrupts
  • provides system calls
  • -> this program is the kernel

2

operating system in the broad sense:

  • kernel plus system utilities
  • configuration and management programs
  • sometimes compilers and language interpreters
  • -> use terms such as distribution or operating environment
  • -> kernel has the unambiguous meaning

3

user task:

  • can transform information only in its assigned memory
  • interacts with the outside world only through the OS
  • -> request for an OS service = system call

4

background needed before studying OS:

  • review volume 1, section 3.1.2 and chapter 3.6
  • understanding basic OS operation is required for further study

5

CPU execution modes:

  • privileged mode: all CPU instructions are available
  • restricted mode: only non-privileged instructions are available
  • kernel starts in privileged mode
  • user task runs after the kernel switches to restricted mode

6

return from a user task to privileged mode also transfers control to a

predefined handler owned by the OS:

  • hardware interrupt: an external device needs attention
  • exception: the CPU cannot execute an instruction correctly (invalid opcode, division by zero, access outside task memory, ...)
  • system call: the task explicitly requests an OS service
  • -> restricted code cannot change the handler addresses

7

only kernel code executes in privileged mode

  • all other programs are user tasks in restricted mode
  • a user task cannot directly affect the whole computing system
  • it can request such an action from the OS

8

multitasking modes:

  • batch: task runs until it finishes or waits for an event/I/O useful on supercomputers where total throughput matters
  • time-sharing: ready tasks receive portions of CPU time useful for interactive and server systems
  • non-preemptive: task keeps CPU until it gives it up mostly obsolete
  • real-time: scheduler aims at predictable completion by a deadline

9

full multitasking needs hardware support for:

  • interrupts
  • memory protection
  • privileged and non-privileged instructions/modes
  • timer generating interrupts at regular intervals

10

OS material had appeared earlier because later programming topics could not be explained without it; earlier treatment was necessarily superficial

11

detailed OS study has 2 aspects:

  • services visible to programs using system calls
  • internal structure and operation of the OS
  • this part and the next two cover the first aspect
  • the final part of the volume covers the second aspect

12

why the OS is needed:

  • manage user tasks:
    • start and stop programs
    • distribute CPU time and RAM
    • allow processes to interact
  • manage the computer hardware
  • -> the OS is the layer coordinating applications and hardware
user program -> system call -> kernel -> hardware or kernel object

Why the Operating System Is Needed

The operating system has two central jobs.

Job Examples
Manage user tasks Start and stop processes, schedule CPU time, allocate memory, protect address spaces
Manage hardware Hide device-specific details, coordinate access to disks, terminals, printers, networks

User programs should not need to know the details of every disk controller, keyboard, screen, or network adapter. The OS gives them a uniform interface.

Detailed notes - 5.1.3: Managing external devices

1

device management has 2 parts: coordination and abstraction

  • coordination prevents tasks from conflicting over one device
  • without it, disk requests can repeatedly move the head in opposite directions and may corrupt each other's results
  • tasks submit device requests through system calls
  • the OS chooses the order in which requests are performed

2

abstraction is needed because devices are numerous and different:

  • controllers use different commands and data formats
  • supporting every possible device in every application is impractical
  • a new or unknown device could otherwise make an application incompatible

3

OS device abstraction:

  • OS handles device-specific details
  • system calls present simpler, often uniform objects to programs
  • tasks see an abstraction instead of a physical device and its quirks

4

physical storage devices differ widely:

  • magnetic diskettes and hard disks use magnetized tracks
  • CD/DVD uses optical changes along a spiral track
  • flash drives, memory cards, and SSDs have no rotating disk

5

OS presents these devices as one disk abstraction:

  • numbered sectors of equal size, commonly 512 bytes
  • disks differ by sector count, read/write capability, and removability
  • most tasks use the higher-level file abstraction instead
  • named files can be opened, read/written, and closed in the same way regardless of whether the storage is optical or flash

Multitasking

A computer usually has more tasks than processors, so the OS must decide which task runs now.

Type Idea Where it is useful
Batch multitasking A task runs until it finishes or waits for input/output Supercomputers and batch jobs
Time sharing Tasks receive short CPU time slices Interactive systems and servers
Non-preemptive multitasking A task keeps the CPU until it voluntarily gives it up Mostly historical
Real-time scheduling Predictable completion time matters more than fairness Control systems and deadlines

Full multitasking requires hardware support:

The timer is what lets the kernel regain control even when the current task does not voluntarily stop.

Detailed notes - 5.1.2: Managing user tasks

1

starting and stopping tasks:

  • only the OS can create a task after it has taken control of the machine
  • only the OS can remove it correctly
  • it must update task structures, scheduling queues, and free memory

2

CPU scheduling:

  • several tasks may exist on one or more CPUs
  • scheduler pauses some tasks and runs others
  • batch mode lets a task run while it has work
  • time-sharing gives tasks time slices and switches at their expiry

3

memory management is part of task management:

  • allocate RAM among tasks
  • configure virtual memory and memory protection
  • manage hardware features related to memory
  • swap data to disk temporarily to free RAM

4

processes need to communicate

  • processes cannot directly change one another
  • -> the OS provides inter-process communication

5

privileges belong to running programs/processes, not directly to human users

  • a process may represent a user task or part of one

6

multi-user systems need access control:

  • unrestricted access would let ordinary mistakes damage shared resources
  • the risk exists even without malicious users

7

giving one user unrestricted privileges on a personal machine is

dangerous:

  • launching a program gives its author control of the machine through that program
  • malware can act against the owner's interests
  • an ordinary programming error can destroy the system and user data

8

the book notes that Unix systems had avoided actively spreading viruses;

it attributes this mainly to privilege separation and Unix design choices

9

Unix administrators normally:

  • work under ordinary user accounts
  • obtain unrestricted privileges only for a specific administrative task
  • leave the privileged session immediately afterward
  • -> everyday programs do not receive administrator privileges

10

Unix interfaces usually expose technical details instead of hiding

them:

  • no generic action that opens an arbitrary file type by executing it
  • an attached executable from mail is not given a convenient launch button
  • -> accidental execution is harder

11

Unix design traditionally favors engineering and security over marketing

claims of convenience:

  • user interface behavior is not forced by the kernel
  • what looks attractive in advertising need not be convenient in daily work

Kernel Responsibility

Kernel code is powerful and dangerous: it runs in privileged mode and usually stays resident in memory. Therefore, the kernel should contain only what really requires kernel privileges.

Appropriate kernel responsibilities:

Usually not kernel responsibilities:

A graphical interface can be part of a complete operating environment without being part of the kernel.

Detailed notes - 5.1.4: Boundaries of kernel responsibility

1

OS responsibilities:

  • user-task management:
    • start and stop processes
    • schedule CPU time
    • allocate RAM
    • provide process interaction
    • separate privileges
  • external-device management:
    • hide differences between device models
    • coordinate several tasks using one device

2

kernel has special costs and risks:

  • kernel memory normally cannot be swapped out
  • -> a larger kernel leaves less physical memory for user tasks
  • kernel code runs privileged
  • -> a kernel error is more damaging and harder to fix than a user error

3

minimal-kernel principle:

  • kernel should contain only work that really needs kernel privileges
  • moving drivers to user programs can reduce kernel size but adds system calls and frequent context switches
  • application-level work has no place in the kernel

4

OS should not provide user communication:

  • no window system or other user interface belongs in the kernel
  • application programs talk to users and request OS services
  • ideally, the end user need not see the OS itself

5

Android and Mac OS X illustrate the distinction:

  • their graphical layers are user-space programs, not the kernel
  • Linux is the kernel under Android
  • Darwin (a BSD-family kernel) is the kernel under Mac OS X
  • programming for these systems mainly uses high-level user-space GUI libraries

Unix as a Way of Thinking

Unix is not just one operating system. It is also a style of system design.

Principle Meaning
Do one thing well Prefer small focused programs
Compose tools Use one program's output as another program's input
Use text streams Text is easy for both humans and programs to inspect
Be quiet on success Print only useful output unless something went wrong
Keep the command line complete Everything important should be possible from scripts
Mechanism, not policy Provide basic tools; avoid forcing one fixed workflow
Everything is a file Represent devices and many kernel objects through file-like interfaces

Text is not always the best representation. Machine code, compressed data, encrypted data, images, sound, and video are usually binary. But where text is reasonable, Unix systems prefer it because it is inspectable, editable, and easy to connect with other tools.

Detailed notes - 5.1.5: Unix: family of systems and a way of thinking

1

Unix names a family of systems built around common principles, not one particular OS; a broader Unix philosophy grew around those principles

2

main Unix design principle:

  • each program should solve one task and solve it well
  • programs should work together
  • text streams should be a universal information representation

3

example setting:

  • a mixed-faculty computer class ran Windows workstations
  • students logged into a remote Linux server
  • the task was to count how many students had logged in successfully

4

program w lists active sessions and their users

  • successive transformations by separate filter programs were connected in one pipeline
  • output of one program became input of the next

5

remove the two header lines with tail -n +3

  • select only the login-name field with cut -d' ' -f 1

6

finish the pipeline:

  • remove the author's own login with grep -v ^avst$
  • sort and remove duplicate student sessions with sort -u
  • count the remaining names with wc -l
  • complete command: w | tail -n +3 | cut -d' ' -f 1 | grep -v ^avst$ | sort -u | wc -l

7

this is an example of six small programs cooperating in one pipeline to solve a real task

8

text representation can use more memory and require parsing than binary,

but it is easy for people to:

  • read and understand
  • edit
  • create
  • combine with many text-processing programs

9

Unix generally prefers text except for:

  • machine-code executables
  • digitized analog data: photographs, video, recorded sound
  • compressed data
  • encrypted data
  • drawings, diagrams, synthesized music, and computer animation can still be represented effectively as text

10

many Internet protocols use text streams:

  • e-mail and Web protocols are examples
  • DNS is a common binary-protocol example

11

"silence is golden":

  • a successful program prints only the output requested by the user
  • NASM and gcc normally finish silently on success

12

Unix user interfaces generally assume that the user knows what they are

doing:

  • commands are not replaced by a supposedly wiser policy
  • every system function should be reachable from the command line
  • graphical and full-screen interfaces may offer alternatives but do not replace the command line
  • alternatives are often implemented by calling command-line utilities

13

graphical interfaces follow "mechanism, not policy":

  • provide mechanisms for building a GUI
  • do not dictate its appearance or behavior
  • users can choose among many window managers

14

"everything is a file":

  • file names identify ordinary files, peripheral devices, virtual devices, and communication channels
  • pseudo-filesystems expose kernel settings and process information
  • there are exceptions, including System V IPC and some Linux devices

15

Unix syscall interfaces also follow the simple-composition philosophy:

  • many calls have no arguments or only one to three
  • four-, five-, and six-argument calls are less common
  • no Unix syscall has more than six arguments
  • complex operations are built from several simple calls

16

"everything is a byte stream" in the syscall interface:

  • files, terminals, pipes, and many network exchanges use byte streams
  • positioned streams allow the current file position to change
  • non-positioned streams deliver bytes sequentially
  • datagram networking is an important exception

17

KISS = "Keep it simple, Stupid!"

  • Unix software favors simple designs

18

Unix software is usually distributed as portable source code:

  • well-written source can be compiled on other Unix systems and platforms
  • binary executables depend on the OS interface and hardware architecture
  • free licenses commonly allow copying, study, modification, and redistribution
  • Linux distributions consequently provide many freely available programs

19

free software is not the same as freeware or merely open source

  • the four freedoms are:
    • run the program for any purpose
    • study and modify it (source code must be available)
    • redistribute copies
    • distribute modified versions (source must remain available)

20

GNU GPL protects these freedoms with a copyleft condition:

  • exact and modified copies, and derivative works containing GPL code, must be distributed under the GPL
  • using GPL software means accepting its license conditions

21

GPL does not require a zero price:

  • a GPL program may be sold
  • the buyer still receives the GPL freedoms
  • an additional agreement cannot remove those freedoms

22

open source and free software are different:

  • BSD-style licenses can allow modified binaries without source
  • source code may be published under a license that still forbids redistribution, so source availability alone does not guarantee freedom

X Window

The X Window System separates display management from applications.

Component Role
X server Controls the screen, keyboard, and mouse
X client Application that asks the X server to draw windows
Window manager Special X client that moves, resizes, decorates, and arranges windows

The word server here names the side that provides the display service. An application can run on one machine while showing its windows on another.

Detailed notes - 5.1.6: Notes on the X Window System

1

Unix architecture was not changed fundamentally by graphical desktops because graphical shells are outside the kernel

2

X Window System:

  • implemented entirely by ordinary user programs
  • kernel support is limited to generic access to the video card
  • other graphical systems can use the same support
  • Mac OS X and Android use different user-space graphical systems

3

an X GUI application remains an ordinary Unix process:

  • it has command-line arguments
  • it has stdin, stdout, and stderr
  • it connects to X and sends requests using the X protocol

4

X server:

  • draws requested objects on the user's screen
  • normally draws only in response to client requests
  • sends events back for keyboard, mouse, and required redraws

5

X connection may be local or over a network

  • an application can run remotely while its window appears locally

6

X uses a stream socket:

  • local connections commonly use AF_UNIX
  • network connections use AF_INET or AF_INET6
  • after connection, both look like bidirectional byte streams

7

X server is also an ordinary process

  • kernel only provides access to the video card, for example by mapping video memory into the server's virtual address space

8

an X server need not use a physical video card:

  • it only has to implement the X protocol
  • Xvfb writes the rendered image to a file
  • Xming and Cygwin/X let Windows users display remote Unix applications

9

to inspect the system directly, start an X server without the usual desktop

wrapper; the classic display mode uses the -retro option

10

if another X server is already running:

  • start the test server on :1 or :1.0
  • on a clean machine, the default is :0.0

11

a bare X server shows an empty screen, a large X-shaped cursor, and its default textured background

12

without clients, the only useful action is moving the cursor

  • return to a text console
  • put X in the background with Ctrl-Z and bg, or use another console
  • console switching uses Alt-F1, Alt-F2, ...

13

start a client and explicitly select its display:

  • DISPLAY=:0.0 xterm
  • use the actual display identifier if the test server is :1.0

14

with only X and xterm running, the xterm window has no border, title, or minimize/maximize/close buttons

15

window decoration is provided by a separate window manager:

  • it is not provided by the X server
  • it is not required from every client
  • -> this preserves both simplicity and user choice

16

some modern Gnome applications take over work traditionally assigned to the window manager, which makes them awkward under other window managers

17

start a lightweight window manager such as twm from xterm

  • fvwm2 or icewm can be used for the same experiment

18

when the window manager runs:

  • windows gain decorations
  • they can be moved, resized, and closed
  • killing the window manager removes decorations but leaves clients running

19

an X window manager is just another X client

  • it uses the same X protocol as other applications

20

an X application may run on the same host as the X server or remotely

  • an X terminal is a specialized machine whose main job is running X
  • user programs run on an application server, which need not have a display

21

X-terminal sessions need remote authentication and session setup:

  • xdm runs on the application server
  • the X server contacts it using XDMCP
  • after login, a session leader or window manager is started

22

terminology is confusing because several levels are involved:

  • an X-terminal is a client workstation toward the application server
  • xdm is an XDMCP server on that application server
  • the program on the terminal is called an X server
  • applications on the application server are X clients

23

at the X protocol level, the X-terminal provides the display service and

is therefore the server; applications requesting display are clients

24

many X terminals plus a few application servers can reduce

administration:

  • terminals need little hardware and usually no disks
  • parameters arrive over the network
  • only the servers need maintenance

25

traditional X terminals carried keyboard/mouse events and graphics

  • sound can be forwarded by programs such as JACK and PulseAudio
  • local hardware can play sound generated by a remote application
Section test (1 file) - 5.1.6: Notes on the X Window System
Section test06 (05-01)In catalog
videocard.cC / 35 lines
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
    int fd = open("/dev/fb0", O_RDWR);

    struct fb_var_screeninfo vinfo;
    struct fb_fix_screeninfo finfo;

    ioctl(fd, FBIOGET_VSCREENINFO, &vinfo);
    ioctl(fd, FBIOGET_FSCREENINFO, &finfo);

    int size = finfo.smem_len;

    unsigned int *fb = mmap(NULL, size,
                PROT_READ | PROT_WRITE,
                MAP_SHARED, fd, 0);

    int pixels = size / 4;

    for (int i = 0; i < pixels; i++)
        fb[i] = 0x00ff0000;

    sleep(3);

    munmap(fb, size);
    close(fd);

    return 0;
}

System Calls and Library Wrappers

A system call is the low-level request from a user task to the kernel. Assembly programs can perform system calls directly, but C programs normally call library wrappers.

fd = open("data.txt", O_RDONLY);
n = read(fd, buf, sizeof(buf));
close(fd);

The C library wrapper hides details such as system-call numbers, CPU-specific calling conventions, and small differences between Unix-like systems.

Most wrappers follow this error convention:

Result Meaning
normal non-negative value Success
-1 Error; details are stored in errno
Detailed notes - 5.1.7: System calls and their wrappers

1

system-call entry is processor-dependent:

  • i386 assembly used software interrupts such as int
  • other processors use different mechanisms
  • the common idea is to transfer control to the kernel with a request

2

C normally uses library wrappers that look like ordinary C functions

  • assembly can bypass wrappers, but this is uncommon
  • syscall numbers and constants differ between Linux, FreeBSD, and other kernels
  • Linux changed and cache-grouped syscall numbers for 64-bit systems; the practical gain is questionable

3

C library wrappers smooth kernel differences:

  • they improve portability
  • a function can be a syscall on one system and a library emulation using other syscalls on another

4

common Unix wrapper error handling:

  • successful calls return their normal non-negative result
  • failure usually returns -1
  • errno receives an error code such as ENOENT, EINVAL, EPERM, or EACCES
  • strerror converts the code to text; perror prints a diagnostic
  • syscall documentation lists the possible error codes

5

with threads, errno is usually a macro selecting a per-thread integer:

  • each independent thread gets its own error value
  • it can still be read, assigned, and addressed like an integer lvalue
  • do not use errno as the name of your own object
Section test (1 file) - 5.1.7: System calls and their wrappers
Section test07 (05-01)In catalog
05-01-07.cC / 33 lines
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main(void) {
    int fd;

    fd = open("no_such_file.txt", O_RDONLY);

    if (fd == -1) {
        printf("open() failed\n");

        printf("errno value: %d\n", errno);

        if (errno == ENOENT) {
            printf("Reason: file does not exist\n");
        } else if (errno == EACCES) {
            printf("Reason: permission denied\n");
        }

        printf("strerror(errno): %s\n", strerror(errno));

        perror("perror says");
        return 1;
    }

    printf("File opened successfully\n");
    close(fd);

    return 0;
}

Privileges

Before performing many system calls, the kernel checks whether the process has the required rights.

Concept Meaning
uid Numeric user identifier
gid Numeric group identifier
root User with uid 0; allowed to bypass many checks
primary group Main group of a user
supplementary groups Additional groups used for access control

In Unix, a user means an account identity, not necessarily a human person. System services often run under their own users.

Name-to-number mappings are stored in ordinary configuration files used by user-space programs:

File Purpose
/etc/passwd User names, uid values, home directories, shells
/etc/group Group names, gid values, group membership
/etc/shadow Password hashes on many systems

The kernel mostly works with numeric uid and gid values.

Detailed notes - 5.1.8: Privilege separation

1

user task alone:

  • can only transform data in its assigned memory

kernel:

  • can use the computer's hardware capabilities
  • spends some of this power servicing user requests
  • -> without kernel services, a task's results would remain invisible in its memory

2

privilege separation is essential:

  • some requests have no system-call interface at all (read kernel memory, reprogram memory protection, disable interrupts)
  • for other requests, the kernel checks whether this particular task is allowed
  • -> a system call is both a request and a permission check

3

requests normally allowed to every task include:

  • _exit to terminate itself
  • reading the system clock
  • obtaining information about itself
  • closing its own open I/O streams

4

many requests depend on user or group identity:

  • a task may normally terminate another task only when both have the same owner
  • opening a file checks the task's owner against the file owner and permissions
  • open fails when the requested access is not allowed
  • changing file permissions is normally restricted to the owner

5

root is the Unix superuser:

  • owner restrictions do not apply to root's tasks
  • they can read/write any file and stop any task
  • many operations, such as changing system time, are reserved for root

6

quantitative limits can also be enforced:

  • maximum virtual memory for a task
  • maximum open files
  • maximum number of tasks for a user
  • kernel rejects a request that would exceed a limit

7

Unix privilege separation uses numeric identifiers:

  • uid = user identifier
  • gid = group identifier
  • both are non-negative integers
  • older systems may use 16-bit values; modern systems commonly use 32-bit values

8

"user" in the kernel does not necessarily mean a human:

  • one person can have several accounts
  • service programs commonly run under separate dummy accounts
  • from the kernel's viewpoint, a user is essentially a uid number

9

uid 0 identifies root

  • the kernel recognizes root by numeric uid, not by the name root

10

users can belong to groups:

  • every user has at least one primary group
  • a user may have several supplementary groups
  • a group can exist even when it has no members

11

groups originally supported cooperation on multi-user systems

  • group membership can allow access to shared files/directories
  • today groups also provide fine-grained rights for service accounts
  • example: create a printer group and give device files to that group

12

/etc/passwd and /etc/group are ordinary readable text files:

  • one line describes each account or group
  • fields are separated by colons
  • administrator rights are not needed just to inspect them

13

fields in /etc/passwd describe:

  • login name
  • password field
  • uid
  • primary gid
  • real name
  • home directory
  • login shell

14

passwords are no longer stored in /etc/passwd:

  • an x usually marks a moved password field
  • public password hashes enabled offline guessing
  • modern systems use /etc/shadow (root-readable) or mechanisms such as /etc/tcb

15

/etc/group has four fields:

  • group name
  • group-password field
  • gid
  • comma-separated supplementary members

16

primary-group membership comes from the fourth /etc/passwd field and need not be repeated in /etc/group

  • gid 0 for a group has no special meaning merely because uid 0 is root

17

kernel does not read /etc/passwd or /etc/group itself:

  • user-space login programs read the files and verify credentials
  • they set uid, primary gid, and supplementary gids on the task
  • they drop administrator privileges and start the user's shell or GUI session
  • the kernel only services the privilege-changing system calls

Input/Output and File Systems

Unix input/output is built around a small set of simple ideas:

Detailed notes - 5.2: Input/Output and File Systems

1

input/output includes:

  • terminal input and output
  • reading and writing disk files
  • standard streams that may be connected to files instead of a keyboard or screen

2

programs under multitasking OSs perform I/O through system calls

  • Pascal hid most of the mechanism
  • assembly made the system-call boundary visible
  • C library functions can do block I/O, but direct system calls are often simpler

3

this chapter fills in file and stream details that were previously left implicit

File System Basics

A file is named stored data. A filesystem can mean either the kernel subsystem that manages files or the on-disk data structures used to store them.

Unix has one directory tree rooted at /.

Additional disks and filesystems are attached to this tree by mounting them at directories called mount points.

Paths can be absolute or relative.

Path Meaning
/home/student/prog/main.c Absolute path from the root
prog/main.c Relative path from the current directory
../main.c Relative path through the parent directory
./program File named program in the current directory
Detailed notes - 5.2.1: File System

1

file:

  • named data stored on an external storage device

filesystem:

  • OS subsystem that stores named files on external devices

2

filesystem can also mean the on-disk data structures:

  • superblock with general filesystem information
  • record of free and used sectors
  • file names and the sectors occupied by each file
  • metadata such as type, permissions, and modification time

3

"filesystem" therefore has 2 meanings:

  • data structures on the disk
  • kernel code that manages those structures

4

early filesystems used short names in one global namespace

  • names had to be unique
  • directories were introduced as storage grew

5

use directory or catalogue, not the informal word folder

6

directory:

  • a special file containing file names, including names of other directories
  • each filesystem starts with a root directory
  • subdirectories can be recorded in the root or in other subdirectories

7

each process has a current directory

  • absolute path: starts at the root /
  • short name: contains no slash and means a name in the current directory
  • relative path: starts at the current directory and may include ..

8

Unix uses one directory tree instead of device letters such as A: or C:

  • one filesystem supplies the root
  • other filesystems are mounted at directories called mount points
  • example: /mnt/flash/work/prog.c

9

Unix directory entry stores only:

  • a file name
  • the number of its inode (index node)
  • type, size, disk location, times, owner, and permissions belong to the inode
  • inode numbers are unique within one filesystem

10

file structure:

  • normally an inode plus data blocks
  • an empty file may have no data blocks
  • some special files never use data blocks
  • a file name is not part of the file; names occur only in directories

11

Unix file names may be about 255 characters and may contain almost any character except NUL and slash

  • avoid spaces, shell metacharacters, control characters, non-ASCII characters, and a leading minus
  • unusual names are possible but make commands difficult to use

12

hard links:

  • several directory entries may refer to one inode
  • all such names are equally valid; there is no privileged original name
  • hard links can cross neither disks nor filesystems
  • inode stores a link count, incremented and decremented with link creation/removal

13

unlink removes a directory entry, not necessarily the data:

  • data is removed only after the last hard link is gone
  • if a process still has the file open, the inode/data remain until it closes it
  • an unlinked open file has no name but remains a disk object temporarily

14

command ln creates a hard link

  • unlike cp, it creates another name and does not copy the file data

15

directory is itself a special kind of file:

  • its data blocks contain names and inode numbers
  • at the low level it differs from an ordinary file mainly by its type field
  • Unix has seven file types; ordinary files and directories are the common ones

16

directory restrictions:

  • rmdir removes a directory only when it is empty
  • hard links to directories are forbidden
  • allowing them could create cycles and make recursive traversal and deletion impossible

17

symbolic link:

  • special file containing the name of another file
  • opening it follows the stored name
  • has its own inode and does not change the target's inode
  • target may be absent or later removed -> dangling link
  • can cross filesystem boundaries because it stores a name, not an inode number

18

create a symbolic link with:

  • ln -s /path/to/old/name new_name

19

short symbolic-link targets may be stored inside the inode's block-pointer area

  • this avoids allocating a separate data block
  • longer targets use a separate block

20

other special files may also occupy no blocks outside the inode

  • a symbolic link can therefore use either only its inode or its inode plus a block
/
|-- bin
|-- dev
|-- etc
|-- home
|   `-- student
`-- tmp
directory name -> inode number -> inode -> data blocks
Hard links share an inode. A symbolic link stores a pathname of its own.
Names lead to inodes; open files can outlive names. Open full size - Editable SVG

Unix separates a file's data from its names.

Object Contains
Directory entry File name and inode number
Inode File type, permissions, owner, size, block locations, timestamps
File data blocks Actual file contents

The inode does not store the file name. A name is only an entry in a directory.

A hard link is another directory entry pointing to the same inode.

ln report.txt copy.txt

After this command, report.txt and copy.txt are equal names for the same file. There is no original and no copy at the filesystem level.

unlink removes a name, not necessarily the file data. The data disappears only when both conditions are true:

A symbolic link is different: it is a small special file containing a path.

ln -s /var/log/syslog log

Symbolic links can cross filesystem boundaries and can point to names that do not currently exist.

File Types

Unix filesystems store several kinds of objects.

Type Meaning
Regular file Ordinary byte sequence
Directory Mapping from names to inode numbers
Symbolic link File containing another path
Character device Byte-oriented device interface
Block device Block-oriented device interface
FIFO / pipe One-way byte stream between processes
Socket Communication endpoint

This is the practical meaning behind the Unix phrase everything is a file: many different objects can be opened and manipulated through a common interface.

File Permissions

Each inode stores an owner uid, a group gid, and permission bits.

Bits Meaning for files Meaning for directories
r Read file contents List directory entries
w Write file contents Create, remove, or rename entries
x Execute program Traverse/search the directory

Permissions are grouped for owner, group, and others.

Octal notation is compact:

Bit Value
r 4
w 2
x 1

Examples:

Mode Meaning
644 Owner can read/write; everyone else can read
600 Only owner can read/write
755 Owner can modify; everyone can read and execute
700 Only owner can access

Special permission bits:

Bit Octal Meaning
SetUID 4000 Executable runs with the file owner's privileges
SetGID 2000 Executable runs with file group; directories pass group to new files
Sticky 1000 In shared directories, users can remove only their own files

Typical shared temporary directory:

/tmp mode: 1777

Commands and calls:

Operation Command System call
Change permissions chmod chmod
Change owner chown chown
Change group chgrp chown
Inspect metadata ls -l, stat stat, lstat, fstat
Detailed notes - 5.2.2: File Permissions

1

file permissions determine which processes, acting for which users, may perform operations on a file

2

inode stores:

  • owner uid
  • owner group gid
  • a 12-bit permission word
  • lower 9 bits are 3 groups of read/write/execute bits for owner, group, others

3

octal notation matches the three-bit groups:

  • three digits normally represent owner, group, others
  • read = 4, write = 2, execute = 1
  • 644: owner read/write, group and others read
  • 751: owner read/write/execute, group read/execute, others execute

4

directory execute permission means access/traversal, not running a

program:

  • read without execute: names can be listed, but files cannot be used
  • execute without read: known names can be used, but names cannot be listed
  • read+execute is usual
  • read without execute is practically useless

5

special permission bits:

  • SetUid 04000: executable runs with file owner's privileges
  • SetGid 02000: executable runs with file group's privileges
  • Sticky 01000: meaning depends on whether the object is a file or directory

6

SetUid is often used on administrator-owned programs

  • passwd is a traditional example
  • some systems no longer make passwd suid

7

Sticky bit originally kept frequently used executable code in memory

  • kernel file caching makes that optimization obsolete
  • today Sticky is meaningful mainly for directories

8

Unix executables can be binary or script files:

  • script begins with a line such as #!/bin/sh
  • system runs the named interpreter and passes the script name
  • any suitable program can be the interpreter, even /bin/cat
  • execute permission lets the script run like an ordinary command

9

SetUid and SetGid are ignored for executable scripts

  • this is an intentional security restriction

10

suid-script threat setup:

  • a normal user can execute a script owned by root
  • the user wants the script to grant broader privileges

11

starting a script involves a race:

  • system first opens the script to read the interpreter name
  • it closes that file and starts the interpreter
  • interpreter opens the script again

12

attacker can exploit the two opens:

  • replace a symbolic link from the trusted script to an attacker script
  • race the interpreter's second open
  • privileged interpreter may execute attacker-controlled code
  • -> SetUid/SetGid are disabled for scripts

13

Sticky bit on a public writable directory:

  • users may remove only their own files
  • 01777 is typical for /tmp

14

SetGid on a directory:

  • new files inherit the directory's group
  • subdirectories inherit both the group and SetGid bit
  • useful for shared mail directories such as /var/spool/mail

15

SetUid on directories is ignored on most systems, including Linux

  • FreeBSD may use it to make new files inherit the directory owner

16

some systems interpret SetGid without group execute as mandatory locking

  • this feature is rarely used

17

permission and ownership tools:

  • ls -l uses stat to inspect permissions
  • chmod changes permissions
  • chown changes owner and group through one system call
  • chgrp changes only the group using chown

18

symlink permissions are normally ignored

  • operations use the target's permissions
  • chmod applied to a symlink changes the target, not the link itself
rwx r-x r--
 owner group others
Mode 754 grants rwx to the owner, r-x to the group, and r-- to others.
Read, write, execute: three bits per class. Open full size - Editable SVG
Tests & experiments (2 files) - 5.2.2: File Permissions
Section test02 (05-02)In catalog
fake_interpreter.pyPython / 11 lines
#!/usr/bin/env python3
import sys
from pathlib import Path

script = sys.argv[1]

print("[interpreter] I was asked to run:", script)
print("[interpreter] Opening that path now...")
print()

print(Path(script).read_text())
fake_kernel.pyPython / 20 lines
#!/usr/bin/env python3
import sys
import time
import subprocess

script = sys.argv[1]

with open(script, "r") as f:
    first_line = f.readline().strip()

print("[kernel] I opened:", script)
print("[kernel] I saw shebang:", first_line)

interpreter = first_line[2:].split()[0]

print("[kernel] Now I will wait before starting the interpreter...")
time.sleep(5)

print("[kernel] Starting interpreter...")
subprocess.run([interpreter, script])

File Descriptors and Byte Streams

Low-level Unix I/O works with file descriptors: small non-negative integers owned by a process.

Descriptor Conventional meaning
0 Standard input
1 Standard output
2 Standard error

These numbers are conventions established when the process starts. The kernel does not treat descriptor 1 as inherently special; it is just an open object.

Basic calls:

int open(const char *name, int flags, ...);
int read(int fd, void *buf, int size);
int write(int fd, const void *buf, int size);
int close(int fd);

Opening flags:

Flag Meaning
O_RDONLY Open for reading
O_WRONLY Open for writing
O_RDWR Open for reading and writing
O_CREAT Create the file if needed
O_TRUNC Truncate existing file
O_APPEND Always write at the end
O_EXCL With O_CREAT, fail if the file already exists
O_NONBLOCK Do not wait when the operation would block

Example:

int fd;
char buf[4096];
int n;

fd = open("input.txt", O_RDONLY);
if (fd == -1) {
    perror("input.txt");
    return 1;
}

n = read(fd, buf, sizeof(buf));
if (n == -1) {
    perror("read");
}

close(fd);

Important rules:

When O_CREAT is used, open also receives requested permissions:

fd = open("out.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);

The process umask removes permission bits from newly created files. For example, with umask 022, requested mode 0666 becomes 0644.

Etude 5.01 finds a file's length by moving the position to the end; lseek returns the resulting offset:

#define _LARGEFILE64_SOURCE

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    int fd;
    long file_size;
    if (argc < 2) {
        fprintf(stderr, "Please enter file name as parameter\n");
        return 1;
    }

    fd = open(argv[1], O_RDONLY);
    if (fd == -1) {
        perror(argv[1]);
        return 1;
    }

    lseek64(fd, 0, SEEK_END);
    file_size = lseek64(fd, 0, SEEK_CUR);
    printf("File size: %ld bytes\n", file_size);

    close(fd);
    return 0;
}
$ printf 'abcdefghij' > ten.txt
$ ./filesize ten.txt
File size: 10 bytes
Detailed notes - 5.2.3: Reading and writing file contents

1

Unix commonly represents transferred data as byte streams

  • C's high-level streams use FILE*
  • block functions in the C library offer little advantage over syscall-level byte-oriented I/O for arbitrary streams

2

C wrappers for the basic I/O calls are named open, read, write, lseek, and close

  • on non-Unix systems they may be library functions rather than syscalls
  • their behavior can still be the same

3

system calls identify streams by file descriptors:

  • small non-negative integers: 0, 1, 2, 3, ...
  • a descriptor can refer to any I/O stream, not only a disk file

4

file descriptor and inode are unrelated:

  • descriptor means an open-stream number
  • inode (index node) is the filesystem object storing file metadata

5

standard descriptors are a convention:

  • 0 = standard input
  • 1 = standard output
  • 2 = standard diagnostic/error output
  • they are normally open at program start
  • kernel does not give these numbers intrinsic meaning; programs agree on the convention

6

number is only an index into a kernel data structure

  • the real descriptor is a complex kernel object
  • descriptor numbers are local to each process
  • descriptor 5 can refer to different objects in different processes

7

open creates a new I/O stream and has two profiles:

  • int open(const char *name, int mode);
  • int open(const char *name, int mode, int perms);

8

open name and mode:

  • name may be short, absolute, or relative
  • mode is a bit mask of options combined with |
  • exactly one basic mode is required: O_RDONLY, O_WRONLY, or O_RDWR

9

common modifying flags:

  • O_APPEND: write at the end of the file
  • O_CREAT: create when absent
  • O_TRUNC: discard old contents and set length to zero
  • O_EXCL with O_CREAT: fail if the file already exists

10

O_NONBLOCK makes reads and writes return immediately instead of waiting

  • an operation may then fail if the stream is not ready
  • other flags exist as well

11

perms is used only when O_CREAT may create a new file

  • ignored for an existing file
  • must be supplied when a new file may be created

12

umask:

  • per-process mask inherited by child processes and launched programs
  • bits set in umask are removed from requested permissions for new files
  • applies to files, directories, and other newly created objects
  • umask(mask) changes the process's mask and returns the previous value
  • only the lower 9 bits matter

13

common umask choices:

  • 022 removes group/other write permission
  • 027 denies access to users outside the group
  • 077 denies all access to everyone except the owner
  • shell umask changes only that shell session and its children

14

new ordinary data files usually request perms 0666

  • read/write for owner, group, and others, with umask removing unwanted bits
  • 0600 is suitable for confidential data
  • execute permission is normally not requested for data files

15

open result:

  • -1 on error
  • a file descriptor for the new stream on success

16

opening must always be checked

  • open has many failures outside the program's control
  • ignoring whether the result equals -1 makes the program incorrect

17

read and write profiles:

  • int read(int fd, void *mem, int len);
  • int write(int fd, const void *data, int len);
  • fd selects the stream, buffer points to memory, len is the requested byte count

18

read behavior:

  • blocks if no data is ready
  • returns as soon as at least one byte is available
  • may return fewer bytes than requested

19

write may block on streams with limited kernel buffers:

  • network output can be slower than the producer
  • a pipe can block when its reader is not consuming data
  • ordinary disk-file writes rarely block for this reason

20

read/write results:

  • -1 means error
  • positive result is the number of bytes transferred, never more than len
  • read returns 0 at end of stream
  • EOF meaning depends on the stream: end of file, Ctrl-D, or peer disconnect

21

always inspect read's result

  • do not discard it with read(fd, buf, sizeof(buf));
  • store it, for example count = read(fd, buf, sizeof(buf));

22

write results should normally be checked too

  • a write may return less than len when a disk fills
  • a nonblocking network stream may accept only what fits in its kernel buffer
  • repeat writes as needed for the remaining bytes

23

without O_NONBLOCK, write usually waits until all supplied data is accepted

  • O_NONBLOCK can be set when open is called
  • fcntl can set it later, including for streams not created by open

24

modern write returns zero only when len is zero, which should not be relied on

  • older Unix systems had rarer zero-return cases

25

lseek changes the current position in an open stream:

  • long lseek(int fd, long offset, int whence);
  • whence = SEEK_SET, SEEK_CUR, or SEEK_END
  • returns the new position measured from the beginning

26

seeking past the end and writing creates a sparse-file hole

  • hole reads as zero bytes
  • zero-filled regions need not occupy physical blocks

27

only some streams are seekable

  • ordinary disk files support lseek
  • pipes, terminals, and other non-positioned streams do not

28

off_t size matters:

  • on old 32-bit systems it was a signed 32-bit value
  • lseek could therefore not address files over 2 GB

29

lseek64 supplies a 64-bit offset and return value

  • on 64-bit systems long and long long may already have the same size

30

close releases a descriptor:

  • descriptors are limited system/process resources
  • int close(int fd) returns 0 on success and -1 on error
  • descriptor is closed even when close reports an error

31

check close especially after writing

  • kernel may buffer output and perform physical I/O later
  • delayed write errors may be reported only by close

32

several descriptor numbers may refer to one kernel stream object

  • close removes only that number
  • the kernel object disappears only after its last descriptor is closed

33

asynchronous output is common:

  • write copies data into kernel memory and returns
  • physical output is scheduled later when the device is available
  • processes can continue without waiting for the device

34

asynchronous output can lose data on a crash or power failure

  • a mail server may read a message from a queue, write the mailbox, then delete the queue copy
  • interruption between these steps can lose the message

35

fsync waits for one file's pending data and required metadata:

  • int fsync(int fd);
  • returns 0 on success and -1 on error
  • physical write is complete before it returns

36

fdatasync is similar to fsync

  • guarantees data and metadata needed to read it correctly
  • need not force irrelevant metadata such as the last-modification time

37

sync requests system-wide writeback:

  • no parameters and no return value
  • waits for all pending filesystem data to be physically written
  • request is accepted by every process, not only root
  • kernel schedules the work normally rather than abandoning all other work

38

fcntl configures descriptor behavior:

  • int fcntl(int fd, int cmd, ...);
  • command determines the number and types of additional arguments

39

open flags have categories:

  • access mode: O_RDONLY, O_WRONLY, O_RDWR
  • creation flags: O_CREAT, O_EXCL, O_TRUNC, O_NOCTTY
  • status flags: O_APPEND, O_NONBLOCK, and others
  • status flags can be changed after open
  • F_GETFL reads the current status flags

40

test a status flag with bitwise and:

  • flags = fcntl(fd, F_GETFL);
  • if (flags & O_APPEND) { ... }

41

F_SETFL changes status flags

  • preserve existing flags while adding O_NONBLOCK: flags = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, flags | O_NONBLOCK);

42

fcntl(fd, F_SETFL, O_NONBLOCK) is enough when no other status flags matter

  • more fcntl commands will be introduced later
dup and fork can create several descriptor references to one open-file description.
File descriptors are references, not file positions. Open full size - Editable SVG
Tests & experiments (2 files) - 5.2.3: Reading and writing file contents
Section test03 (05-02)In catalog
checkfd.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    if (argc != 2) {
        fprintf(stderr, "usage: %s <fd>\n", argv[0]);
        return 1;
    }

    int fd = atoi(argv[1]);

    errno = 0;
    int flags = fcntl(fd, F_GETFD);

    if (flags == -1 && errno == EBADF) {
        printf("fd %d is CLOSED after exec\n", fd);
    } else if (flags == -1) {
        perror("fcntl");
        return 1;
    } else {
        printf("fd %d is STILL OPEN after exec\n", fd);
    }

    return 0;
}
umask.cC / 12 lines
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>

int main(int argc, char **argv)
{
    int fd;
    umask(0022);
    fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
    close(fd);
    return 0;
}

File Position

Each open regular file has a current position. read and write normally move this position forward.

long lseek(int fd, long offset, int whence);
whence Offset is relative to
SEEK_SET Beginning of file
SEEK_CUR Current position
SEEK_END End of file

Seeking past the end and then writing can create a sparse file: missing parts read as zeroes but may not occupy disk blocks.

Synchronizing Output

The kernel often buffers writes in memory and sends them to the device later.

Call Meaning
fsync(fd) Flush file data and metadata
fdatasync(fd) Flush file data and necessary metadata
sync() Ask the system to flush all pending filesystem writes

These calls are needed when physical persistence matters, for example after writing important data that must survive a crash.

Managing Filesystem Objects

Common filesystem operations:

Call Meaning
link(old, new) Create a hard link
unlink(name) Remove a directory entry
rename(old, new) Rename or move within one filesystem
mkdir(name, mode) Create a directory
rmdir(name) Remove an empty directory
symlink(target, name) Create a symbolic link
chmod(path, mode) Change permission bits
chown(path, uid, gid) Change owner and/or group
truncate(path, length) Change file size by path
ftruncate(fd, length) Change file size by descriptor

rename is especially useful because replacement of an existing non-directory target is atomic.

Detailed notes - 5.2.4: Managing filesystem objects

1

filesystem-object calls cover operations besides reading and writing

  • failure convention is usually -1
  • success is another value, commonly 0

2

link creates a hard link:

  • int link(const char *oldpath, const char *newpath);
  • oldpath must name an existing file and newpath the new name
  • both arguments name files, not directories
  • ln can additionally accept a destination directory, but link cannot

3

unlink removes a directory entry:

  • int unlink(const char *name);
  • it does not remove directories

4

unlink deletes file data only after the last link is removed and the file is

closed by the last process using it

  • an orphaned inode may survive an unclean shutdown until the next boot

5

rename changes a file name or moves it within one filesystem:

  • int rename(const char *oldpath, const char *newpath);
  • source and destination may be in different directories
  • moving across filesystems is not supported

6

rename can atomically replace an existing non-directory target

  • directory replacement has stricter rules
  • network filesystems may not provide full atomicity

7

mkdir and rmdir create and remove directories:

  • int mkdir(const char *name, int perms);
  • int rmdir(const char *name);
  • perms is filtered by umask
  • 0777 is common; 0700 protects a sensitive directory

8

symlink creates a symbolic link:

  • int symlink(const char *oldpath, const char *newpath);
  • oldpath must be non-empty but need not exist
  • newpath becomes a symlink, possibly dangling

9

unlink applied to a symbolic link removes the link itself

  • it does not follow the link to remove the target

10

chmod changes permission bits:

  • int chmod(const char *path, int perms);
  • example: chmod("file.txt", 0600);
  • ordinary users may change only files they own; root is unrestricted
  • umask does not affect chmod

11

chown and lchown change ownership:

  • chown follows a symlink; lchown changes the link itself
  • -1 preserves the corresponding uid or gid
  • only root may change an owner
  • owner may change the group only to one of the owner's groups
  • 0 means success, -1 means error

12

stat, lstat, and fstat obtain metadata:

  • stat(path, buf) follows a symbolic link
  • lstat(path, buf) reports the link itself
  • fstat(fd, buf) reports an open object without its name
  • struct stat includes device, inode, mode/type, link count, uid, gid, device id, size, block size/count, and access/modification/status times
  • st_mode contains type and permissions; mask with 07777 to extract permissions

13

truncate and ftruncate change file length:

  • truncate uses a path; ftruncate uses an open descriptor
  • shortening discards data after the new length
  • extending reads as zeroes and may create holes
  • truncate requires write permission; ftruncate requires O_WRONLY or O_RDWR
Section test (1 file) - 5.2.4: Managing filesystem objects
Section test04 (05-02)In catalog
link.cC / 15 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    int res;
    res = link(argv[1], argv[2]);
    if (res == -1) {
        perror("link");
        exit(1);
    }

    return 0;
}

File Metadata

stat, lstat, and fstat fill a struct stat.

Call What it inspects
stat(path, &st) Object named by path; follows symbolic links
lstat(path, &st) The symbolic link itself if path is a symlink
fstat(fd, &st) Already open object

Important fields:

Field Meaning
st_dev Device containing the inode
st_ino Inode number
st_mode File type and permissions
st_nlink Number of hard links
st_uid Owner uid
st_gid Group gid
st_size File size in bytes
st_atime Last access time
st_mtime Last data modification time
st_ctime Last metadata change time

Permission bits can be extracted with:

mode = st.st_mode & 07777;

Device Files

Many devices appear as special files, usually under /dev.

cat /dev/cdrom > image.iso
cat file.ps > /dev/lp0

Device files let programs use familiar calls such as open, read, write, and sometimes lseek.

Device kind Meaning
Character device Byte stream or event stream
Block device Random-access storage divided into blocks
Detailed notes - 5.2.5: Device files and device classes

1

Unix presents many external devices as special files:

  • disks
  • serial and parallel ports
  • virtual terminals
  • -> ordinary file operations become a general device interface

2

device-file examples:

  • cat /dev/cdrom > image.iso reads a CD image
  • cat myfile.ps > /dev/lp0 sends data to a printer port
  • print subsystems normally provide a higher-level interface

3

device files use ordinary system calls:

  • open the disk device
  • lseek to a sector
  • write the sector
  • -> disk formatting can be implemented this way

4

older Linux audio devices could be read and written as files

  • copying bytes from a microphone device to a sound device reproduced sound
  • modern audio subsystems are more complex

5

not every peripheral has a file representation

  • Linux does not provide device files for network interfaces

6

device files are either:

  • character/stream/byte-oriented
    • transfer bytes or sequences of bytes
  • block-oriented
    • transfer fixed-size blocks
  • examples of character devices: terminal, printer port, mouse, sound card

7

pseudo character devices:

  • /dev/null discards writes and returns EOF on reads
  • /dev/zero returns unlimited zero bytes and discards writes
  • /dev/full returns zeros on read and ENOSPC on write
  • /dev/random returns random data

8

block devices usually represent disks

  • physical disks may require whole-sector operations
  • the driver can satisfy an unaligned user request by reading several sectors
  • kernel caching is often associated with block devices

9

device files are special file types alongside directories and symbolic links

  • both classes support open, read, and write
  • block devices support lseek
  • character devices do not support positioning
  • ordinary disk files and block devices are the only seekable streams

10

FreeBSD moved away from a separate block-device type because of cache control

  • all device files there are character-oriented
  • disk-related ones may still support lseek
  • Linux and other BSD systems retain block devices

11

ioctl handles device-specific operations:

  • int ioctl(int fd, int request, ...);
  • examples: open/close a CD tray, set serial speed, format a floppy, control sound volume
  • e.g. ioctl(fd, CDROMEJECT) and ioctl(fd, CDROMCLOSETRAY)
  • additional arguments depend on request; CDROMPLAYTRKIND can select an audio track

Reading Directories

Programs should not read directory bytes directly. Directory layout is filesystem-specific, so C programs use library functions.

DIR *opendir(const char *name);
struct dirent *readdir(DIR *dirp);
int closedir(DIR *dirp);

Example:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char **argv)
{
    DIR *dir;
    struct dirent *dent;
    const char *name = ".";

    if (argc > 1)
        name = argv[1];

    dir = opendir(name);
    if (!dir) {
        perror(name);
        return 1;
    }

    while ((dent = readdir(dir)) != NULL) {
        printf("%s\n", dent->d_name);
    }

    closedir(dir);
    return 0;
}

readdir returns a pointer to an internal structure that can be overwritten by the next readdir call on the same directory stream.

Etude 5.08 searches the current directory tree for files with a given name. lstat tells directories apart without following symbolic links, so a link cannot lead the search into a loop:

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>

enum { file_path_size = 4096 };

static int is_dir(const char *dir_name)
{
    struct stat sb;
    int res;

    res = lstat(dir_name, &sb);
    if (res == -1) {
        perror("lstat");
        return 0;
    }

    return S_ISDIR(sb.st_mode);
}

static void find_file_in_dir(const char *dir_name, const char *file_name)
{
    DIR *dir;
    struct dirent *dent;
    char file_path[file_path_size];

    dir = opendir(dir_name);
    if (!dir) {
        perror(dir_name);
        exit(2);
    }
    while ((dent = readdir(dir)) != NULL) {
        if (strcmp(dent->d_name, ".") != 0 &&
            strcmp(dent->d_name, "..") != 0) {
            sprintf(file_path, "%s/%s", dir_name, dent->d_name);
            if (is_dir(file_path)) {
                find_file_in_dir(file_path, file_name);
            }
            else {
                if (strcmp(file_name, dent->d_name) == 0)
                    printf("%s\n", file_path);
            }
        }
    }
    closedir(dir);
}

int main(int argc, char **argv)
{

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
        return 1;
    }
    find_file_in_dir("." ,argv[1]);

    return 0;
}
$ ./find target
./target
./a/b/target
Detailed notes - 5.2.6: Reading directory contents

1

directory is a special disk file containing names and inode numbers

2

kernel alone changes directory contents:

  • create, remove, or rename files/hard links
  • direct writes are forbidden to preserve filesystem integrity
  • directories may be opened read-only, but read on their descriptor does not work
  • Linux and FreeBSD use getdents internally; direct use is non-portable

3

C library directory interface:

  • DIR *opendir(const char *name);
  • struct dirent *readdir(DIR *dirp);
  • int closedir(DIR *dirp);
  • DIR* is library-managed state, analogous to FILE*

4

readdir returns a pointer to a library-owned struct dirent

  • one state object is used for each open directory
  • the next readdir call may overwrite the previous record

5

when entries are exhausted, readdir returns NULL

  • call closedir to release the descriptor and library state

6

struct dirent is system-dependent:

  • d_name is always present, but its array size is not generally fixed
  • NAME_MAX gives the implementation's maximum name length
  • d_ino usually contains the inode number
  • other fields vary by system

7

sample directory listing program:

  • choose argv[1] or .
  • opendir the directory and report errors with perror
  • loop while readdir returns non-NULL
  • print dent->d_name
  • closedir at the end
Examples & tests (3 files) - 5.2.6: Reading directory contents
Book exampleBook example: poor_ls.cIn catalog
poor_ls.cC / 22 lines
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char **argv)
{
    DIR *dir;
    struct dirent *dent;
    const char *name = ".";
    if(argc > 1)
        name = argv[1];
    dir = opendir(name);
    if(!dir) {
        perror(name);
        return 1;
    }
    while((dent = readdir(dir)) != NULL) {
        printf("%s\n", dent->d_name);
    }
    closedir(dir);
    return 0;
}
Section test06 (05-02)In catalog
poor_ls-00.cC / 22 lines
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char **argv)
{
    DIR *dir;
    struct dirent *dent;
    const char *name = ".";

    if (argc > 1)
        name = argv[1];
    dir = opendir(name);
    if (!dir) {
        perror(name);
        return 1;
    }
    while ((dent = readdir(dir)) != NULL)
        printf("%s\n", dent->d_name);
    closedir(dir);
    return 0;
}
poor_ls-01.cC / 22 lines
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>

int main(int argc, char **argv)
{
    DIR *dir;
    struct dirent *dent;
    const char *name = ".";

    if (argc > 1)
        name = argv[1];
    dir = opendir(name);
    if (!dir) {
        perror(name);
        return 1;
    }
    while ((dent = readdir(dir)) != NULL)
        printf("%ld %s\n", dent->d_ino, dent->d_name);
    closedir(dir);
    return 0;
}

Memory-Mapped Files

mmap maps a file into a process address space. After that, file contents can be accessed like memory.

void *mmap(void *start, int length, int protection,
           int flags, int fd, int offset);
int munmap(void *start, int length);

Common protection flags:

Flag Meaning
PROT_READ Memory can be read
PROT_WRITE Memory can be written
PROT_EXEC Memory can be executed as code
PROT_NONE Memory cannot be accessed

Common mapping flags:

Flag Meaning
MAP_SHARED Writes are shared and may reach the file
MAP_PRIVATE Private copy-on-write mapping
MAP_ANONYMOUS Mapping is not backed by a file

Example:

int fd, size;
char *p;

fd = open("file.dat", O_RDWR);
if (fd == -1) {
    perror("file.dat");
    return 1;
}

size = lseek(fd, 0, SEEK_END);
p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) {
    perror("mmap");
    return 1;
}

Practical rules:

mmap is also used as a general mechanism for allocating virtual memory. An anonymous private mapping gives a process fresh memory directly from the OS.

Detailed notes - 5.2.7: Memory-mapped files

1

mmap maps file contents into a process's virtual address space

  • file data can then be accessed like ordinary memory variables
  • void *mmap(void *start, int length, int protection, int flags, int fd, int offset);

2

before mmap, open the file and pass its descriptor in fd

  • offset and length select the file region
  • mappings use whole pages
  • start, length, and offset are constrained by page size
  • getpagesize() reports the relevant page size
  • length is rounded up; an unaligned offset is an error

3

mmap page size need not equal the virtual-memory page size

  • old Linux versions could report unusual values such as 16

4

protection flags:

  • PROT_READ and PROT_WRITE allow reading/writing
  • PROT_EXEC allows execution, for example for dynamic libraries
  • PROT_NONE forbids all access
  • protection must be compatible with the file's open mode

5

flags select shared or private behavior:

  • MAP_SHARED writes can be reflected in the file
  • MAP_PRIVATE changes are private to the mapping
  • MAP_ANONYMOUS creates memory without a file; fd and offset are ignored

6

MAP_ANONYMOUS|MAP_SHARED creates shared memory across forked processes

  • parent and child see each other's changes
  • shared memory is useful for process interaction but has subtle synchronization problems

7

start is an optional preferred address

  • passing NULL lets the system choose a free virtual area
  • non-NULL placement is outside the basic discussion

8

mmap returns the mapped address

  • failure is MAP_FAILED, equal to -1 converted to void*

9

example mapping:

  • open file.dat read/write
  • get its size with lseek(fd, 0, SEEK_END)
  • map it with PROT_READ|PROT_WRITE and MAP_SHARED
  • p[25] reads the 26th byte; p[25] = 'a' changes that byte

10

file length need not be page-aligned:

  • unused bytes at the end of the last mapped page read as zero
  • writes there do not change the file
  • mapping well beyond the file may fail with MAP_FAILED
  • touching a page wholly beyond the file may cause SIGBUS, even after mmap succeeded

11

munmap cancels mappings:

  • int munmap(void *start, int length);

12

munmap removes every page intersecting the requested range

  • range need not equal one original mapping
  • it can remove part of a mapping or several adjacent mappings
  • start must be page-aligned; length may be any positive value

13

msync can force modified mapped pages to be written to the file

  • details are left for later study

14

mmap is now also a general virtual-memory allocation interface

  • BSD malloc can use MAP_PRIVATE|MAP_ANONYMOUS
  • passing fd = -1 and offset = 0 creates memory directly from the OS
MAP_SHARED and MAP_PRIVATE differ when a process writes through a mapping.
Mapped addresses provide another view of file bytes. Open full size - Editable SVG
Tests & experiments (6 files) - 5.2.7: Memory-mapped files
Section test07 (05-02)In catalog
MakefileMake / 11 lines
PROGRAMS = 05-02-07-mmap-04

CFLAGS = -g -Wall -O0

all: $(PROGRAMS)

$(PROGRAMS): %: %.c
    $(CC) $(CFLAGS) $^ -o $@

clean:
    rm -f *.o $(PROGRAMS)
mmap-00.cC / 69 lines
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define handle_error(msg) \
    do { perror(msg); exit(EXIT_FAILURE); } while (0)

int main(int argc, char *argv[])
{
    int          fd;
    char         *addr;
    off_t        offset, pa_offset;
    size_t       length;
    ssize_t      s;
    struct stat  sb;

    if (argc < 3 || argc > 4) {
        fprintf(stderr, "%s file offset [length]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    fd = open(argv[1], O_RDONLY);
    if (fd == -1)
        handle_error("open");

    if (fstat(fd, &sb) == -1)           /* To obtain file size */
        handle_error("fstat");

    offset = atoi(argv[2]);
    pa_offset = offset & ~(sysconf(_SC_PAGE_SIZE) - 1);
        /* offset for mmap() must be page aligned */

    if (offset >= sb.st_size) {
        fprintf(stderr, "offset is past end of file\n");
        exit(EXIT_FAILURE);
    }

    if (argc == 4) {
        length = atoi(argv[3]);
        if (offset + length > sb.st_size)
            length = sb.st_size - offset;
                /* Can't display bytes past end of file */

    } else {    /* No length arg ==> display to end of file */
        length = sb.st_size - offset;
    }

    addr = mmap(NULL, length + offset - pa_offset, PROT_READ,
                MAP_PRIVATE, fd, pa_offset);
    if (addr == MAP_FAILED)
        handle_error("mmap");
    s = write(STDOUT_FILENO, addr + offset - pa_offset, length);
    if (s != length) {
        if (s == -1)
            handle_error("write");

        fprintf(stderr, "partial write");
        exit(EXIT_FAILURE);
    }

    munmap(addr, length + offset - pa_offset);
    close(fd);

    exit(EXIT_SUCCESS);
}
mmap-01.cC / 10 lines
#include <stdio.h>
#include <unistd.h>

int main()
{
    int size;
    size = getpagesize();
    printf("Page size: %d\n", size);
    return 0;
}
mmap-02.cC / 81 lines
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

void die(const char *msg, int num)
{
    perror(msg);
    exit(num);
}

static void parse_arguments(int argc, char **argv, int fd, int *length,
                            int *offset, int *pa_offset)
{
    int res;
    struct stat sb;

    res = fstat(fd, &sb);
    if (res == -1)              /* To obtain file size */
        die("fstat", 2);

    *offset = atoi(argv[2]);
    *pa_offset = *offset & ~(sysconf(_SC_PAGE_SIZE) - 1); /* page aligned */

    if (*offset >= sb.st_size) {
        fprintf(stderr, "offset is past end of file\n");
        exit(1);
    }

    if (argc == 4) {
        *length = atoi(argv[3]);
        if (*offset + *length > sb.st_size)
            *length = sb.st_size - *offset;
    } else
        *length = sb.st_size - *offset;
}

void write_file(int fd, int length, int offset, int pa_offset)
{
    int delta, count;
    char *addr;

    delta = offset - pa_offset;

    addr = mmap(NULL, length + delta, PROT_READ, MAP_PRIVATE, fd, pa_offset);
    if (addr == MAP_FAILED)
        die("mmap", 2);

    count = write(1, addr + delta, length);
    if (count != length) {
        if (count == -1)
            die("write", 2);
        fprintf(stderr, "partial write");
        exit(1);
    }

    munmap(addr, length + delta);
}

int main(int argc, char **argv)
{
    int fd, length, offset, pa_offset;

    if (argc < 3 || argc > 4) {
        fprintf(stderr, "%s file offset [length]\n", argv[0]);
        exit(1);
    }

    fd = open(argv[1], O_RDONLY);
    if (fd == -1)
        die("open", 2);

    parse_arguments(argc, argv, fd, &length, &offset, &pa_offset);
    write_file(fd, length, offset, pa_offset);

    close(fd);
    return 0;
}
mmap-03.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/mman.h>

static void die(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main(int argc, char **argv)
{
    int fd, size, res;
    char *p;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file name>", argv[0]);
        exit(1);
    }

    fd = open(argv[1], O_RDWR);
    if (fd == -1)
        die("open", 2);
    size = lseek(fd, 0, SEEK_END);

    p = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (p == MAP_FAILED)
        die("mmap", 2);

    memcpy(p, "john  ", 6);

    munmap(p, size);
    res = close(fd);
    if (res == -1)
        die("close", 2);
    return 0;
}
mmap-04.cC / 12 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>

int main(int argc, char **argv)
{
    char *p = mmap(NULL, atoi(argv[1]), PROT_READ | PROT_WRITE,
             MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    printf("%p\n", p);

    return 0;
}

Processes

A process is the kernel object that supports the execution of a user program. Informally, it is a program running under operating-system control, but the process also includes state that is not part of the program text: registers, memory mappings, open descriptors, credentials, current directory, signal settings, and resource accounting.

The kernel itself is not treated as a process, even though it is executable code. Process is a user-level execution concept: the kernel creates and manages processes so that user programs can run safely and independently.

Detailed notes - 5.3.1: What a process is

1

process:

  • an entity created by the OS kernel to execute a user program

2

technical terms can become established before anyone defines them precisely

  • process is one such term
  • simple definitions admit counterexamples

3

first approximation: a program that has been started

  • includes code and execution state: variable values, current instruction, ...
  • can own resources such as open files
  • has permissions

problem with this approximation:

  • the running kernel is also a program
  • the kernel as a whole is not a user process
  • it enforces process permissions and may contain several execution contexts

4

bare-metal firmware is another counterexample:

  • runs directly on hardware, without an OS
  • has execution state but no OS-created process around it

5

working approximation: a program executing under OS control

  • useful for understanding processes, but still incomplete
  • Unix can replace the program while keeping the same process

6

kernel's view of a process:

  • a data structure supporting execution of a user program
  • records assigned memory, permissions, open streams, ...
  • stores register contents while the process is not running
  • switching out: save CPU registers into this structure
  • switching in: restore those registers

Process Properties

Important Unix process properties:

Property Meaning
pid Process identifier
ppid Parent process identifier
pgid Process group identifier
sid Session identifier
uid, gid Real user and group identifiers
euid, egid Effective identifiers used for most permission checks
Address space Virtual memory visible to the process
CPU context Saved register values when the process is not running
File descriptor table Mapping from small integers to open kernel objects
Current directory Base for relative pathnames
Root directory Base for absolute pathnames as seen by this process
umask Permission bits removed from newly created filesystem objects
Signal dispositions What to do when each signal is delivered
Resource limits Quantitative limits inherited by child processes

Command-line arguments and environment variables are also process properties. In C, the environment is available through environ and through library functions:

extern char **environ;

char *getenv(const char *name);
int setenv(const char *name, const char *value, int overwrite);
void unsetenv(const char *name);

getenv may return NULL; even familiar variables such as PATH and HOME must be checked before use.

A process can change only its own current directory and, with sufficient privilege, its own root directory:

int chdir(const char *path);
int chroot(const char *path);

chroot changes what the process and its descendants see as /. It is useful for isolation, but it is not a complete security boundary by itself, especially for privileged processes.

Detailed notes - 5.3.2: Process properties

1

process identifiers:

  • pid: unique identifier of a process currently present in the system
  • ppid: identifier of its parent
  • traditional Unix: orphaned processes are adopted by process 1 Linux can also reparent them to a designated subreaper
  • pgid: process group identifier
  • sid: session identifier

2

permissions belong to the process acting for a user

  • uid, gid: real user and group identifiers
  • euid, egid: effective user and group identifiers
  • real and effective identifiers normally agree
  • set-user-ID programs can execute with the executable owner's permissions

3

query identifiers using getpid(), getppid(), getuid(), getgid(), geteuid(), getegid(), and related calls

  • these no-argument getters return the calling process's corresponding IDs
  • session/group queries have different interfaces: getsid(0), getpgid(0), or getpgrp()
  • cannot assign a new pid or directly set ppid
  • session/group membership and credentials have separate rules for changes

4

process memory consists of regions with different properties

  • called segments or mappings
  • executable-file sections and runtime mappings are related but not identical

5

main memory regions:

  • code: machine instructions, normally read-only and shareable
  • data: global variables and, in the simplified model, the heap
  • heap: dynamically allocated objects
  • stack: local variables, return addresses, and call state
  • other mappings depend on the program and system

6

register state is part of process state:

  • instruction pointer, flags, stack pointer, general-purpose registers
  • saved in the kernel when the process is blocked or waiting for CPU time
  • restored when execution resumes

7

CPU scheduler selects processes to run

  • readiness: whether the process can continue executing
  • priority: influences selection among ready processes
  • some schedulers also use priority to determine time-slice length

book's example scheduler:

  • total priority = static priority + dynamic priority
  • waiting raises the dynamic component
  • running lowers it
  • -> eventually a waiting process can take the CPU

8

static scheduling preference in Unix is usually expressed by nice value

  • adjusted with nice and setpriority
  • background calculations can receive less CPU preference
  • response-sensitive work can receive more
  • the scheduler controls its own dynamic calculations

9

command-line arguments and environment are also process properties

  • Linux exposes initial argument/environment storage through /proc, subject to access permissions
  • environment: NULL-terminated array of pointers to strings
  • each string has the form NAME=value

10

new programs normally inherit the launching program's environment

  • exec library wrappers arrange this inheritance
  • execve receives the environment explicitly
  • C access: extern char **environ;
  • environ points to the first element of the NULL-terminated pointer array
  • declaration availability depends on headers and feature settings

11

some implementations allow a third parameter to main for the environment

  • pointer-array representation like argv
  • this is an implementation extension, not a portable ISO C main signature

12

environment strings live in process memory -> ordinary library functions suffice

  • getenv(name): returns the value string or NULL when absent
  • always check NULL, even for PATH and HOME
  • setenv(name, value, overwrite): creates the variable if missing
  • replaces an existing value only when overwrite != 0
  • unsetenv(name): removes the variable
  • setenv and unsetenv return int status values

13

Linux /proc/PID/environ and the library's current environment can differ

  • setenv/unsetenv can change pointers and heap strings used by environ
  • /proc exposes the initially recorded environment memory region
  • directly overwriting that region can change what /proc displays
  • such overwriting does not itself update the library's environment model

14

some programs change their displayed command line to show current activity

  • overwriting argv storage can affect ps output on Linux
  • storage is limited and may border the original environment strings
  • do not overwrite beyond the available area
  • this technique is platform-specific

15

current working directory:

  • starting point for relative paths
  • affects system calls receiving relative file names
  • a process can change its own current directory

16

root directory:

  • starting point for absolute paths
  • with process root /foo, /bar resolves inside /foo/bar
  • restricts ordinary pathname lookup to a subtree
  • inherited by descendants

17

chroot is not a complete security boundary

  • privileged processes can escape under suitable conditions
  • interaction with same-user processes outside the tree can undermine isolation

18

change directory with chdir(path)

  • path can be absolute or relative
  • .. denotes the parent directory

change process root with chroot(path)

19

chroot changes pathname resolution for this process and its descendants

  • requires the appropriate privilege
  • does not change the current directory automatically
  • existing directory references and privileges matter for isolation
  • current/root directories cannot be changed directly for another process

20

file descriptor table is another process property

  • descriptors are small integers local to a process
  • corresponding kernel objects contain the actual stream state
  • files and sockets require different kernel state
  • descriptor 0 in two processes need not identify the same stream

21

descriptor table maps numbers to kernel I/O objects

  • open creates an entry; close removes one
  • other calls can create streams without open
  • descriptor-manipulation calls can change these mappings directly

22

umask is a process property

  • controls which permission bits are removed when creating files
  • changed with umask()

23

other process properties:

  • signal dispositions: what to do when each signal arrives
  • resource counters: CPU time, memory use, ...
Tests & experiments (15 files) - 5.3.2: Process properties
Section test02 (05-03)In catalog
environ-00.cC / 133 lines
#define _POSIX_C_SOURCE 200112L
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

extern char **environ;

static void die(const char *s)
{
    perror(s);
    exit(1);
}

static char *xstrdup(const char *s)
{
    char *p;

    p = malloc(strlen(s) + 1);
    if (p == NULL)
        die("malloc");
    strcpy(p, s);
    return (p);
}

static void dump_proc(const char *title)
{
    int fd;
    char buf[4096];
    ssize_t n;
    ssize_t i;
    ssize_t start;
    fd = open("/proc/self/environ", O_RDONLY);
    if (fd < 0)
        die("open");
    n = read(fd, buf, sizeof(buf));
    close(fd);
    if (n < 0)
        die("read");
    printf("\n== %s ==\n", title);
    start = 0;
    i = 0;
    while (i < n) {
        if (buf[i] == '\0' && i > start)
            printf("%.*s\n", (int)(i - start), buf + start);
        if (buf[i] == '\0')
            start = i + 1;
        i++;
    }
}

static size_t env_span(char **env, char **out)
{
    char *start;
    char *end;
    char *e;
    int i;

    if (env == NULL || env[0] == NULL)
        return (*out = NULL, 0);
    start = env[0];
    end = env[0] + strlen(env[0]) + 1;
    i = 1;
    while (env[i] != NULL) {
        e = env[i] + strlen(env[i]) + 1;
        if (env[i] < start)
            start = env[i];
        if (e > end)
            end = e;
        i++;
    }
    *out = start;
    return ((size_t)(end - start));
}

static void move_env(void)
{
    char **copy;
    int i;
    int n;

    n = 0;
    while (environ[n] != NULL)
        n++;
    copy = malloc((n + 1) * sizeof(*copy));
    if (copy == NULL)
        die("malloc");
    i = 0;
    while (i < n) {
        copy[i] = xstrdup(environ[i]);
        i++;
    }
    copy[n] = NULL;
    environ = copy;
}

static void put(char *block, size_t len, size_t *pos, const char *s)
{
    size_t n;

    n = strlen(s) + 1;
    if (*pos + n > len)
        return ;
    memcpy(block + *pos, s, n);
    *pos += n;
}

int main(void)
{
    char *old;
    size_t len;
    size_t pos;

    old = NULL;
    len = env_span(environ, &old);
    printf("pid = %ld\n", (long)getpid());
    dump_proc("1) start");
    setenv("ADDED_BY_SETENV", "yes", 1);
    unsetenv("SECOND");
    printf("\ngetenv ADDED_BY_SETENV = %s\n", getenv("ADDED_BY_SETENV"));
    printf("getenv SECOND = %s\n",
        getenv("SECOND") ? getenv("SECOND") : "null");
    dump_proc("2) after setenv/unsetenv");
    move_env();
    memset(old, 0, len);
    pos = 0;
    put(old, len, &pos, "PROC_ENV=changed");
    put(old, len, &pos, "X=1");
    dump_proc("3) after direct overwrite");
    return (0);
}
environ-02.cC / 11 lines
#include <stdio.h>

extern char **environ;

int main()
{
    int i;
    for (i = 0; environ[i]; i++)
        printf("%s\n", environ[i]);
    return 0;
}
environ-03.cC / 21 lines
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv, char **environ)
{
    int i, n;
    char buf[4096];
    for (i = 0, n = 0; environ[i]; i++)
        n += strlen(environ[i]) + 1;
    n -= 1;
    printf("%d\n", n);

    for (i = 0; i < n-20; i++)
        buf[i] = 'l';
    buf[i] = 0;

    memcpy(environ[0], buf, n);
    sleep(20);
    return 0;
}
environ-04.cC / 68 lines
#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

extern char **environ;

int main(void)
{
    /*
       1. Remember the original environment memory.
    */
    char *old_start = environ[0];
    char *old_end = environ[0];

    for (int i = 0; environ[i] != NULL; i++) {
        char *end = environ[i] + strlen(environ[i]) + 1;

        if (environ[i] < old_start)
            old_start = environ[i];

        if (end > old_end)
            old_end = end;
    }

    size_t old_size = old_end - old_start;

    /*
       2. Copy every environment string.
       This is the sentence:
       "form a copy of the environment and put the corresponding
        addresses into the elements of the environ array"
    */
    for (int i = 0; environ[i] != NULL; i++) {
        environ[i] = strdup(environ[i]);
    }

    /*
       Now environ points to heap copies.
       The original environment memory is no longer needed by getenv().
    */

    char fake[] =
        "FAKE=123\0"
        "HELLO=world\0";

    if (sizeof(fake) > old_size) {
        fprintf(stderr, "Not enough space in original environment memory\n");
        return 1;
    }

    /*
       3. Overwrite the old original environment memory.
    */
    memset(old_start, 0, old_size);
    memcpy(old_start, fake, sizeof(fake));

    printf("PID: %d\n", getpid());

    printf("getenv(\"FAKE\") = %s\n", getenv("FAKE"));
    printf("getenv(\"PATH\") = %s\n", getenv("PATH"));

    getchar();

    return 0;
}
environ-05.cC / 13 lines
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{
    printf("PID: %d\n", getpid());
    getchar();
    printf("%s %ld\n", argv[0], strlen(argv[0]));
    strncpy(argv[0], "hello", strlen(argv[0]));
    getchar();
    return 0;
}
environ-06.cC / 30 lines
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    printf("PID: %d\n", getpid());
    printf("Before changing argv[0], run:\n");
    printf("  ps -p %d -o pid,args\n", getpid());

    getchar();

    const char *new_title = "my-program: working";

    /*
       Only use the space already occupied by argv[0].
       Do NOT write more than strlen(argv[0]) bytes.
    */
    size_t space = strlen(argv[0]);

    memset(argv[0], 0, space);
    strncpy(argv[0], new_title, space);

    printf("After changing argv[0], run again:\n");
    printf("  ps -p %d -o pid,args\n", getpid());

    getchar();

    return 0;
}
environ-07.cC / 25 lines
#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char **argv)
{
    printf("PID: %d\n", getpid());
    printf("Check with:\n");
    printf("  ps -p %d -o pid,args\n", getpid());
    printf("  tr '\\0' ' ' < /proc/%d/cmdline; echo\n", getpid());

    getchar();

    size_t space = strlen(argv[0]);
    const char *new_title = "worker: idle";

    memset(argv[0], 0, space);
    strncpy(argv[0], new_title, space);

    printf("Changed argv[0]. Check again.\n");

    getchar();

    return 0;
}
environ-08.cC / 25 lines
#include <stdio.h>
#include <stdlib.h>

extern char **environ;

int main()
{
    char *editor;
    editor = getenv("EDITOR");
    if (editor) {
        printf("%s\n", editor);

        setenv("EDITOR", "vim", 1);
        editor = getenv("EDITOR");
        if (editor)
            printf("%s\n", editor);

        unsetenv("EDITOR");
        editor = getenv("EDITOR");
        if (editor)
            printf("%s\n", editor);
    }
    getchar();
    return 0;
}
environ-09.cC / 44 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

enum { path_size = 64, buf_size = 4096 };

extern char **environ;

static void die(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

static void parse_environ_file()
{
    int pid, fd, res, count, i, j;
    char path[path_size], buf[buf_size];

    pid = getpid();
    sprintf(path, "/%s/%d/%s", "proc", pid, "environ");

    fd = open(path, O_RDONLY);
    if (fd == -1)
        die("open", 2);

    while ((count = read(fd, buf, buf_size)) != 0)
        for (i = 0, j = 0; j < count; j++)
            if (buf[j] == 0) {
                printf("%s\n", buf+i);
                i = j+1;
            }

    res = close(fd);
    if (res == -1)
        die("close", 2);
}

int main()
{
    parse_environ_file();
    return 0;
}
environ-10.cC / 61 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

enum { path_size = 64, buf_size = 4096 };

extern char **environ;

static void die(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

static void parse_environ_file()
{
    int pid, fd, res, count, i, j;
    char path[path_size], buf[buf_size];

    pid = getpid();
    sprintf(path, "/%s/%d/%s", "proc", pid, "environ");

    fd = open(path, O_RDONLY);
    if (fd == -1)
        die("open", 2);

    while ((count = read(fd, buf, buf_size)) != 0)
        for (i = 0, j = 0; j < count; j++)
            if (buf[j] == 0) {
                printf("%s\n", buf+i);
                i = j+1;
            }

    res = close(fd);
    if (res == -1)
        die("close", 2);
}

int main()
{
    char *editor;
    editor = getenv("EDITOR");
    if (editor) {
        printf("%s\n", editor);

        setenv("EDITOR", "vim", 1);
        editor = getenv("EDITOR");
        if (editor)
            printf("%s\n", editor);

    }

    memset(environ[0], 0, 600);
    parse_environ_file();
    editor = getenv("EDITOR");
    if (editor)
        printf("%s\n", editor);
    return 0;
}
environ-11.cC / 12 lines
#include <unistd.h>
#include <string.h>

extern char **environ;

int main(int argc, char **argv)
{
    memcpy(environ[0], "hello there", 11);
    sleep(20);

    return 0;
}
environ-12.cC / 11 lines
#include <unistd.h>
#include <string.h>

int main(int argc, char **argv)
{
    char *str = argv[0];
    strcpy(str, "hello there");
    sleep(10);

    return 0;
}
environ-13.cC / 41 lines
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>

enum { buf_size = 4096 };

extern char **environ;

static void print_environ()
{
    int i;

    for (i = 0; environ[i] != NULL; i++)
        printf("%s,", environ[i]);
    printf("\n");
}

int main(int argc, char **argv)
{
    int i, fd, rc;
    char file_name[buf_size], buf[buf_size];

    char *save = environ[0];

    for (i = 0; environ[i] != NULL; i++)
        environ[i] = strdup(environ[i]);

    strcpy(save, "hello there, how are you doing");

    sprintf(file_name, "/proc/%d/environ", getpid());
    fd = open(file_name, O_RDONLY);
    while ((rc = read(fd, buf, buf_size)) > 0)
        write(1, buf, rc);
    printf("\n");
    close(fd);

    print_environ();

    return 0;
}
environ-14.cC / 7 lines
#include <stdio.h>

int main(int argc, char **argv)
{
    printf("hello\n");
    return 0;
}
process.cC / 41 lines
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>

int main()
{
    int width, pid, priority, res;

    width = 15;
    pid = getpid();
    printf("%*s id: %d\n", width, "Process", pid);
    printf("%*s id: %d\n", width, "Parent process", getppid());
    printf("%*s id: %d\n", width, "User", getuid());
    printf("%*s id: %d\n", width, "Effective User", geteuid());
    printf("%*s id: %d\n", width, "Group", getgid());
    printf("%*s id: %d\n", width, "Effective Group", getegid());
    printf("%*s id: %d\n", width, "Session", getsid(pid));
    printf("%*s id: %d\n", width, "Process group", getpgid(pid));

    priority = getpriority(PRIO_PROCESS, pid);
    printf("%d\n", priority);
    getchar();

    res = setpriority(PRIO_PROCESS, pid, 5);
    if (res == -1) {
        perror("setpriority");
        exit(1);
    }
    priority = getpriority(PRIO_PROCESS, pid);
    printf("%d\n", priority);
    getchar();

    nice(5);

    priority = getpriority(PRIO_PROCESS, pid);
    printf("%d\n", priority);
    getchar();

    return 0;
}

Virtual Address Space

Most modern Unix systems use virtual memory. Machine instructions use virtual addresses, and the MMU translates them to physical addresses according to page tables controlled by the kernel.

Each process normally has its own virtual address space. Different processes can use the same virtual addresses for different physical pages, and the same physical page can be mapped into more than one address space.

On Linux, /proc/PID/maps shows the active mappings of process PID when permissions allow it. Many addresses are intentionally randomized at program start, so code should not depend on exact stack, heap, or mapping addresses.

The stack has a limit. Physical pages for it are usually allocated lazily as the process touches new stack pages, but exceeding the stack limit or total mapping limit terminates the process. Large objects should usually live on the heap, not on the stack.

Detailed notes - 5.3.3: Virtual address space

1

executable sections and runtime memory segments were introduced with assembly

  • now examine the address space seen by a user-mode program

2

virtual addresses are translated to physical addresses by the MMU

  • all possible virtual addresses form the virtual address space
  • translation rules can change
  • paging is the usual translation mechanism
  • each process has its own virtual address space
  • one physical page can appear at different virtual addresses within one process or in several processes

3

memory organization depends on hardware and OS

  • some embedded processors have no MMU
  • systems without virtual memory do not follow this model

4

book's example: a simplified Linux/i386 address space

  • exact layout is architecture-, executable-, and system-dependent
  • unused virtual ranges consume address space, not physical RAM

5

illustrated executable starts at 0x08048000

  • chosen through executable/linker settings, not an immutable kernel rule
  • other architectures and executable types use different addresses
  • leaving addresses near zero unmapped helps detect NULL-pointer bugs
  • also catches some small offsets calculated from NULL

6

code/data regions are mappings in the kernel's memory model

  • mmap is a general mechanism for managing virtual memory
  • mappings need not represent disk files
  • Linux /proc/PID/maps lists a process's mappings, subject to access checks

7

initial mappings:

  • text: executable code mapped from the executable file
  • data: initialized data mapped from that file
  • bss: zero-initialized storage, commonly backed by anonymous memory
  • exact section/page grouping depends on linker layout
  • stack: anonymous memory
  • further mappings can be created while the program runs

8

Linux also provides brk for changing the program break

  • program break marks the end of the traditional heap area
  • increasing it can provide more heap memory
  • book describes the raw Linux syscall: brk(0) reports the current break
  • the C library brk wrapper instead reports success/failure
  • sbrk(0) is the traditional library interface for querying the break

9

address-space randomization introduces unpredictable gaps and positions

  • heap start, stack, and mmap placement can vary between runs
  • makes addresses of runtime objects harder to predict
  • can make exploitation of memory bugs more difficult

10

stack has a configured size limit, often 8 MB in the book's example

  • the virtual limit does not mean all those physical pages exist immediately
  • initial stack contains argument/environment strings and pointer arrays
  • additional pages are supplied as the stack grows
  • access to a not-yet-backed page traps into the kernel
  • kernel can allocate a page and resume the interrupted instruction
  • exceeding stack or address-space limits instead causes failure
  • -> avoid unnecessarily large stack allocations

11

heap and mmap areas can grow into the remaining virtual space

  • illustrated layout lets them grow toward one another
  • growth is bounded by available address space and process resource limits
  • allocation must fail rather than overlap an existing mapping

12

illustrated i386 split reserves 0xC0000000-0xFFFFFFFF for kernel addresses

  • user-mode access to this area is forbidden
  • the kernel also executes through virtual addresses and the MMU
  • system calls must access user buffers, file names, and other arguments
  • having kernel and current-process memory available together simplifies this

13

in the illustrated design:

  • lower 3 GB: current process mappings
  • upper 1 GB: kernel mappings
  • kernel can access both while servicing that process
  • another process's memory needs additional handling

14

traditional implementation includes protected kernel mappings in each process's

page tables

  • user-mode permissions prevent process access
  • kernel mode can use them while retaining access to that process's memory
  • this explains the memory context of a process executing in kernel mode
  • actual kernels may use additional separation mechanisms

15

systems can add special mappings such as Linux vDSO

  • kernel-provided code/data can serve some requests without a syscall
  • reading the time is one example
  • exact mappings and mechanisms are platform- and version-specific

Typical areas in a process address space:

Section test (1 file) - 5.3.3: Virtual address space
Section test03 (05-03)In catalog
chdir.cC / 24 lines
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

static void die(const char *msg)
{
    perror(msg);
    exit(1);
}

int main()
{
    int res;

    res = chdir("..");
    if (res == -1)
        die("chdir");

    res = chroot("/home/m");
    if (res == -1)
        die("chroot");

    return 0;
}

Creating Processes with fork

Unix creates a new process by copying an existing one:

int fork(void);

Return values:

Return value Where Meaning
-1 Parent Process creation failed
0 Child This is the newly created process
positive pid Parent The value is the child's pid

After fork, both processes continue at the instruction after the call. A usual pattern is:

int pid;

pid = fork();
if (pid == -1) {
    perror("fork");
    exit(1);
}

if (pid == 0) {
    /* child */
    _exit(0);
}

/* parent */

The child receives copies of most process properties, with important differences:

Memory is logically copied, but modern systems normally use copy-on-write: parent and child share pages until one of them writes to a page.

Open file descriptors are copied as descriptor-table entries, but the underlying open file objects are shared. If parent and child both refer to the same open regular file, they share the same file position.

After fork, execution order is not predictable. If parent and child both do work immediately, either one may run first. Any result that depends on that ordering is a race condition.

Detailed notes - 5.3.4: Creating a process

1

traditional Unix process creation: duplicate an existing process with fork()

  • declaration uses pid_t fork(void)
  • some systems also expose platform-specific creation interfaces

2

fork results:

  • -1: creation failed
  • parent receives the child's pid
  • child receives 0

child initially resembles parent, with important differences:

  • new pid
  • ppid equals parent's pid
  • resource-use counters start at zero
  • both continue immediately after fork

3

not every property is inherited

  • for example, the child does not inherit a pending alarm() timer

4

three successive successful fork calls produce eight processes

  • 1 -> 2 -> 4 -> 8
  • each process reaches the following printf("Hello\n")
  • -> eight lines are printed

5

parent and child usually need different work

  • test the fork result with if
  • p == 0: child branch
  • p > 0: parent branch
  • child can call exit after its work to avoid falling into parent code

6

also handle p == -1

  • possible causes include process-count limits and insufficient resources
  • an else branch alone does not distinguish parent success from failure

7

parent and child execute concurrently

  • execution order after fork is not guaranteed
  • an example prints one message from each process

8

parent may print first

  • child has not yet been scheduled when parent reaches printf

9

child may print first

  • parent can lose the CPU immediately after fork
  • child can run and print before parent resumes

10

race condition: result depends on the ordering of independent events

  • common when several control flows run concurrently
  • overlooked races can cause incorrect results and security problems

11

ordinary private memory is logically copied by fork

  • child starts with the same variable values
  • later writes in one process do not change the other's variables
  • read-only code can remain shared
  • implementations commonly use copy-on-write: share physical pages until a write requires a private copy
  • descriptor table and signal dispositions are inherited too

12

MAP_SHARED mappings are an exception to private-memory copying

  • create anonymous shared storage before fork
  • example requests 4096 bytes with PROT_READ|PROT_WRITE
  • flags: MAP_SHARED|MAP_ANONYMOUS
  • round requested size up to a multiple of page size
  • check mmap result against MAP_FAILED

13

both processes then access the same mapped storage through ptr

  • 4096 bytes contain 1024 four-byte ints
  • ptr[77] = 120 changes shared storage visible to both

14

shared memory needs synchronization

  • access ordering and concurrent modification require explicit care
  • simply having a shared pointer does not make an algorithm correct

15

fork copies the descriptor table, not the underlying open-file descriptions

  • descriptors are local integer references to kernel objects
  • corresponding parent/child descriptors refer to the same open streams

16

shared open-file descriptions include the current file offset

  • lseek in one process changes where the other next reads or writes
  • several descriptors can refer to one stream in other situations too
Parent and child continue independently after fork. A successful exec never returns to the old program.
fork creates a process; exec replaces its program. Open full size - Editable SVG
Tests & experiments (5 files) - 5.3.4: Creating a process
Section test04 (05-03)In catalog
fork-01.cC / 11 lines
#include <stdio.h>
#include <unistd.h>

int main()
{
    fork();
    fork();
    fork();
    printf("Hello\n");
    return 0;
}
fork-02.cC / 13 lines
#include <stdio.h>
#include <unistd.h>

int main()
{
    int p;
    p = fork();
    if (p == 0)
        printf("I'm the child\n");
    else
        printf("I'm the parent\n");
    return 0;
}
fork-03.cC / 44 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

enum { buf_size = 4096 };

static void die(const char *msg, int code)
{
    perror("msg");
    exit(code);
}

int main(int argc, char **argv)
{
    int fd, res, p, count;
    char buf[buf_size];

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
        exit(1);
    }

    fd = open(argv[1], O_RDONLY);
    if (fd == -1)
        die("open", 2);

    p = fork();
    if (p == -1)
        die("fork", 2);
    else if (p == 0) {
        while ((count = read(fd, buf, buf_size)) != 0)
            write(1, buf, count);
        exit(0);
    }

    lseek(fd, 6, SEEK_SET);

    res = close(fd);
    if (res == -1)
        die("close", 2);

    return 0;
}
fork-04.cC / 34 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>

static void die(const char *msg, int code)
{
    perror("msg");
    exit(code);
}

int main()
{
    int pgs, pid, size;
    int *ptr;
    size = 4096;
    pgs = getpagesize();
    size = ((size - 1) / pgs + 1) * pgs;
    ptr = mmap(NULL, size, PROT_READ|PROT_WRITE,
               MAP_SHARED|MAP_ANONYMOUS, 0, 0);
    if (ptr == MAP_FAILED)
        die("mmap", 1);

    pid = fork();
    if (pid == -1)
        die("fork", 1);

    if (pid == 0)
        printf("%d\n", ptr[77]);
    else
        ptr[77] = 120;

    munmap(ptr, size);
}
fork-05.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void) {
    pid_t pid = fork();

    if (pid < 0) {
        perror("fork");
        exit(1);
    }

    if (pid == 0) {
        printf("child pid=%d: before getchar\n", getpid());
        fflush(stdout);

        int c = getchar();

        printf("child pid=%d: got %d\n", getpid(), c);
        exit(0);
    } else {
        printf("parent pid=%d, child=%d\n", getpid(), pid);
        wait(NULL);
    }

    return 0;
}

Replacing a Program with exec

Unix starts a different program by replacing the current program inside an existing process:

int execve(const char *name, char *const argv[], char *const envp[]);

The process remains the same kernel object, but its program image is replaced. This lets the caller configure process properties first, then execute the target program.

Common library wrappers:

Function Argument form Environment Path search
execve argv[] array explicit envp[] no
execv argv[] array inherited no
execvp argv[] array inherited yes, when name has no /
execl variadic list inherited no
execlp variadic list inherited yes, when name has no /

Example:

char *args[] = { "ls", "-l", "-a", "/var", NULL };
execvp("ls", args);

or:

execlp("ls", "ls", "-l", "-a", "/var", NULL);

On success, exec does not return. There is no old program to return to. Code after exec normally handles failure:

execlp("ls", "ls", "-l", NULL);
perror("ls");
fflush(stderr);
_exit(1);

Open descriptors remain open across exec. A descriptor marked FD_CLOEXEC is closed when exec succeeds.

Detailed notes - 5.3.5: Replacing the running program

1

exec replaces the program inside an existing process

  • new program begins at its entry point
  • the process itself continues to exist
  • process identity and program identity are different things

2

advantage of separating creation and program replacement:

  • configure the process before running the new program
  • inherited properties include many credentials and open descriptors
  • change only what the new program needs changed
  • some properties have special exec rules, including set-ID credentials

3

an interface combining creation and execution must receive more settings at once

  • book contrasts this with Windows process-creation interfaces
  • those take many arguments and configuration structures

4

execve performs program replacement

  • execve(path, argv, envp)
  • argv and envp are NULL-terminated arrays of string pointers

5

execve arguments:

  • path: executable file, absolute or relative to current directory
  • argv: arguments delivered to the new program
  • envp: environment delivered to the new program
  • explicit environment means the kernel need not infer inheritance

6

exec library functions provide convenient wrappers around execve

  • execv(path, argv)

7

execv uses the caller's current environment

  • no explicit environment argument
  • -> environment inheritance

8

execvp(file, argv) has the same argument arrangement as execv

9

execvp can search PATH

  • if file contains no /, search directories listed in PATH
  • if file contains /, use it directly as a pathname
  • "ls" can locate /bin/ls through PATH
  • "./prog" explicitly selects prog in the current directory
  • shell command lookup follows the same general distinction

10

when argument count is known in source code, an argument list is convenient

  • execl(path, argv0, ...)
  • execlp(file, argv0, ...)

11

execl/execlp form argv from their variadic arguments

  • terminate the list with a null pointer, e.g. (char *)NULL
  • argv0 is the program's conventional name, not its first user argument
  • executable path and argv0 are separate arguments
  • execl uses a pathname
  • execlp follows the same PATH/slash rules as execvp

12

example: run ls -l -a /var

  • char *args[] = { "ls", "-l", "-a", "/var", NULL }; execvp("ls", args);
  • or execlp("ls", "ls", "-l", "-a", "/var", (char *)NULL);

13

successful exec never returns to the old program

  • old program image has been replaced
  • any return from exec means failure; return value is -1
  • usual child failure path: report error, then terminate with failure status
  • otherwise child may incorrectly continue the launching program's work

14

exit performs library cleanup before terminating

  • fork can copy unflushed stdio output buffers
  • child exit can flush its copy
  • parent can later flush the same original bytes again
  • -> duplicated output

15

_exit avoids flushing inherited stdio buffers

  • useful after an exec failure in the child
  • any newly buffered diagnostic output must still be delivered deliberately
  • stderr is normally unbuffered; code can change its buffering

16

book's explicit failure sequence:

  • execlp("ls", "ls", "-l", (char *)NULL);
  • perror("ls");
  • fflush(stderr);
  • _exit(1);

17

flush pending parent diagnostics before fork when needed

  • prevents inherited buffered diagnostic text being emitted twice
  • same copying issue applies to other buffered output streams

18

exit, _exit, and return from main are examined in the next subsection

19

open descriptors normally survive exec

  • arrange descriptors before replacement
  • new program inherits the resulting input/output connections
  • -> basis of I/O redirection

20

FD_CLOEXEC is the exception

  • descriptor marked close-on-exec is closed on successful replacement
  • applies to that descriptor, not every reference to the stream

21

descriptor flags and stream status flags are different

  • fcntl F_SETFL changes shared stream flags such as O_APPEND/O_NONBLOCK
  • FD_CLOEXEC belongs to one descriptor-table entry
  • several descriptors can refer to one shared open-file description

22

fcntl descriptor-flag commands:

  • F_GETFD: read descriptor flags
  • F_SETFD: set descriptor flags
  • fcntl(fd, F_SETFD, FD_CLOEXEC) sets close-on-exec

23

query using fcntl(fd, F_GETFD)

  • check for -1 on error
  • otherwise test result & FD_CLOEXEC

24

open(..., O_CLOEXEC, ...) can set close-on-exec at creation

  • avoids a separate fcntl step
  • availability on older target systems must be checked
Tests & experiments (6 files) - 5.3.5: Replacing the running program
Section test05 (05-03)In catalog
exec-01.cC / 11 lines
#include <unistd.h>
#include <stdio.h>

int main()
{
    execlp("ls", "ls", "-la", "exec01.c", NULL);
    perror("execlp");
    exit(1);

    return 0;
}
exec-02.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void die(const char *msg, int code)
{
    perror("msg");
    exit(code);
}

int main()
{
    int pid;

    printf("Hello there");

    pid = fork();
    if (pid == -1)
        die("fork", 1);

    if (pid == 0) {
        execlp("l", "ls", "-la", "exec01.c", NULL);
        perror("execlp");
        exit(1);
    }

    return 0;
}
exec-03.cC / 28 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void die(const char *msg, int code)
{
    perror("msg");
    exit(code);
}

int main()
{
    int pid;

    printf("Some error message");

    pid = fork();
    if (pid == -1)
        die("fork", 1);

    if (pid == 0) {
        execlp("l", "ls", "-l", NULL);
        perror("execlp");
        exit(1); /* _exit(1); */
    }

    return 0;
}
exec-04.cC / 47 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

enum { buf_size = 4096 };

static void die(const char *msg, int code)
{
    perror("msg");
    exit(code);
}

int main()
{
    int fd, res, count;
    char buf[buf_size];

    fd = open("exec04.t", O_RDONLY);
    if (fd == -1)
        die("open", 1);

    int pid;
    pid = fork();
    if (pid == -1) {
        perror("fork");
        exit(1);
    }

    /* fcntl(fd, F_SETFD, FD_CLOEXEC); */
    if (pid == 0) {
        execlp("ls", "ls", "-l", NULL);
        while((count = read(fd, buf, buf_size) != 0)) {
            res = write(1, buf, count);
            if (res == -1)
                die("write", 1);
        }
        perror("ls");
        fflush(stderr);
        _exit(1);
    }

    res = close(fd);
    if (res == -1)
        die("close", 1);
    return 0;
}
exec-05.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
    int use_cloexec = argc > 1;

    int fd = open("example.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    printf("main: opened example.txt as fd %d\n", fd);

    if (use_cloexec) {
        int flags = fcntl(fd, F_GETFD);
        if (flags == -1) {
            perror("fcntl F_GETFD");
            return 1;
        }

        if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
            perror("fcntl F_SETFD");
            return 1;
        }

        printf("main: set FD_CLOEXEC on fd %d\n", fd);
    } else {
        printf("main: did NOT set FD_CLOEXEC on fd %d\n", fd);
    }

    char fd_as_string[32];
    snprintf(fd_as_string, sizeof(fd_as_string), "%d", fd);

    execl("./checkfd", "./checkfd", fd_as_string, NULL);

    perror("execl");
    return 1;
}
exec-06.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

static void die(const char *msg, int code)
{
    perror("msg");
    exit(code);
}

int main()
{
    int pid;

    /* setvbuf(stderr, NULL, _IOFBF, 0); */

    fprintf(stderr, "Some error message\n");

    pid = fork();
    if (pid == -1)
        die("fork", 1);

    if (pid == 0) {
        execlp("l", "ls", "-l", NULL);
        fprintf(stderr, "Some error message");
        perror("execlp");
        _exit(1); /* _exit(1); */
    }

    return 0;
}

Process Termination

A process may terminate voluntarily or because it receives a signal whose action is termination.

Voluntary termination paths:

Mechanism Notes
return from main Equivalent to calling the C library cleanup path
exit(code) Flushes standard I/O buffers and runs library cleanup
_exit(code) System-call level termination; no stdio flushing

The exit code is an eight-bit unsigned value. 0 conventionally means success; small positive values indicate different failures.

Buffered output matters:

printf("Hello, world");
_exit(0);          /* the text may never leave the stdio buffer */

If a process is terminated by a signal, it has no exit code. The kernel records the terminating signal instead.

Detailed notes - 5.3.6: Process termination

1

two main termination paths:

  • voluntary: process asks the kernel to terminate it
  • signal: a terminating signal ends the process

2

ordinary language-level termination eventually requests kernel termination

  • C return from the initial main call performs normal exit processing
  • exit(code) does the same from elsewhere
  • _exit(code) requests termination without that library cleanup
  • declaration: void _exit(int code)

3

exit status convention:

  • 0: success
  • nonzero: failure or another documented outcome
  • traditional wait interfaces expose only the low eight bits
  • -> use values from 0 to 255

exit versus _exit:

  • exit flushes stdio output and runs normal library cleanup
  • _exit does not flush user-space stdio buffers

4

example: printf("Hello, world"); followed by _exit(0)

  • with ordinary buffered stdout, text remains in its buffer and is lost
  • exit(0) or return 0 from main flushes it

5

adding a newline changes the example's behavior when stdout is line-buffered

  • printf("Hello, world\n"); followed by _exit(0)

6

usual terminal output: newline flushes the line -> message appears usual redirected output: fully buffered -> message may remain unflushed

  • ./h prints the message
  • ./h | cat and ./h > file can produce no message

7

newline flushing depends on buffering mode

  • terminal stdout is normally line-buffered
  • redirected stdout is normally fully buffered

second example: print a line, fork, then return from main

8

second example prints once to the terminal but twice when redirected

  • terminal line was flushed before fork
  • redirected line remains buffered at fork

9

explanation of the duplicated redirected output:

  • fork copies the buffer into the child
  • both processes perform normal exit processing
  • both flush the same previously buffered line

10

_exit, exit, and return from main are voluntary termination

  • process supplies an exit status
  • termination by signal is a separate case

11

signal termination has a signal number, not a normal exit status

  • process did not reach a terminating call supplying a status
  • wait status distinguishes these outcomes

12

fatal program errors are commonly reported through signals

  • invalid memory access or certain arithmetic faults cause CPU exceptions
  • kernel identifies a process error and delivers the corresponding signal
  • signal number helps identify the cause

13

termination leaves information that the parent may need

  • normal termination versus signal
  • exit status or terminating signal
  • resource-use counters
  • pid must remain reserved until this information is collected
  • -> terminated process can remain as a zombie
A zombie has finished executing; it retains status until the parent collects it.
Termination and reaping are separate events. Open full size - Editable SVG
Tests & experiments (4 files) - 5.3.6: Process termination
Section test06 (05-03)In catalog
return-00.cC / 4 lines
int main()
{
    return 0;
}
return-01.cC / 8 lines
#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("Hello world");
    _exit(0);
}
return-02.cC / 8 lines
#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("Hello world\n");
    _exit(0);
}
return-03.cC / 9 lines
#include <stdio.h>
#include <unistd.h>

int main()
{
    printf("Hello world\n");
    fork();
    return 0;
}

Wait and Zombies

After termination, Unix keeps a small record containing the exit status, termination signal, and resource counters. Until the parent collects this record, the dead child remains as a zombie process. The pid is not reused until the record is collected.

Waiting calls:

int wait(int *status);
int waitpid(int pid, int *status, int options);
int wait3(int *status, int options, struct rusage *usage);
int wait4(int pid, int *status, int options, struct rusage *usage);

Useful status macros:

Macro Meaning
WIFEXITED(status) Child exited normally
WEXITSTATUS(status) Exit code, if normal
WIFSIGNALED(status) Child was terminated by signal
WTERMSIG(status) Signal number, if signaled

Example:

int status;
int pid;

pid = wait(&status);
if (pid == -1) {
    perror("wait");
} else if (WIFEXITED(status)) {
    printf("pid %d exited with %d\n", pid, WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
    printf("pid %d killed by signal %d\n", pid, WTERMSIG(status));
}

Do not try to kill a zombie process. It is already dead. The parent must wait for it, or the parent must terminate so that process 1 can adopt and clean it up.

Detailed notes - 5.3.7: Waiting for termination; zombie processes

1

parent collects the child's termination information

  • normal exit/status or terminating signal
  • resource usage
  • traditional Unix orphans are adopted by process 1
  • Linux can use a designated subreaper as the adopting ancestor
  • unrelated processes cannot normally reap someone else's child

2

zombie occupies a process-table entry until it is reaped

  • wait-family calls collect status and remove that entry
  • simplest interface: pid_t wait(int *status)

3

wait behavior:

  • no children to wait for: -1, with errno indicating the error
  • living children but no completed child: block
  • completed child available: collect its status and reap it
  • return that child's pid
  • non-NULL status receives encoded termination information
  • wait(NULL) reaps without storing the status

4

decode wait status with macros:

  • WIFEXITED(status): normal termination
  • WEXITSTATUS(status): exit code, only after WIFEXITED is true
  • WIFSIGNALED(status): termination by signal
  • WTERMSIG(status): signal number, only after WIFSIGNALED is true
  • inspect errors before using status
  • -1 can also indicate interruption; it does not always mean no children

5

wait4 offers child selection, options, and resource accounting

  • wait4(pid, status, options, usage)

6

wait4 child selector:

  • positive pid: that specific child
  • -1: any child
  • waiting only for one child can leave other completed children unreaped

7

process-group selectors:

  • 0: any child in the caller's process group
  • less than -1: any child whose group ID equals the negated value
  • -2735 selects group 2735
  • group selection still applies only to children the caller may wait for

8

remaining wait4 arguments:

  • status: encoded outcome, as with wait
  • options = 0: ordinary blocking wait
  • WNOHANG: return immediately if no selected child has a reportable outcome
  • non-NULL usage: receive a struct rusage with resource counters

9

wait4 results:

  • -1: error
  • 0: WNOHANG and no qualifying completed child
  • positive value: pid whose outcome was collected

10

related interfaces:

  • wait3(status, options, usage)
  • waitpid(pid, status, options)

11

in the cases discussed here:

  • wait3 corresponds to wait4 with pid = -1
  • waitpid corresponds to wait4 with usage = NULL
  • the several interfaces reflect historical development

12

cannot kill a zombie: it has already finished executing

  • parent must collect its status
  • if parent disappears, the adopting process can reap it
  • sending signals to the zombie cannot make it run cleanup

13

blocking on one particular child can delay reaping all the others

  • completed siblings may remain zombies for a long time
  • persistent zombies indicate missing or delayed collection

14

when waiting for one target among several children:

  • reap completed children in a loop
  • compare each returned pid with the target
  • preserve any other statuses the program needs
Tests & experiments (3 files) - 5.3.7: Waiting for termination; zombie processes
Section test07 (05-03)In catalog
wait-00.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
    int status, wr, pid;
    pid = fork();
    if (pid == -1) {
        perror("fork");
        return 1;
    }
    if (pid == 0) {
        exit(1);
    }

    getchar();
    wr = wait(&status);
    if (wr == -1)
        printf("There are no child processes at all\n");
    else {
        printf("Process with pid=%d finished.\n", wr);
        if (WIFEXITED(status))
            printf("It has exited with code=%d.\n",
                   WEXITSTATUS(status));
        else
            printf("It was killed by signla %d.\n",
                   WTERMSIG(status));
    }
    return 0;
}
wait-01.cC / 26 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int pid;

    pid = fork();
    if (pid == -1) {    /* error of child process */
        perror("fork");
        exit(1);
    }

    if (pid == 0) {     /* child process */
        execlp("ls", "ls", "-l", "-a", "/var", NULL);
        perror("ls");   /* error if exec returned here */
        exit(1);        /* end with error */
    }
    wait(NULL);         /* wait for child process, kill zombie */

    printf("Ok\n");
    return 0;
}
wait-02.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
    int *status, wr, pid;
    pid = fork();
    if (pid == -1) {
        perror("fork");
        return 1;
    }
    if (pid == 0) {
        exit(1);
    }

    getchar();
    wr = wait(status);
    if (wr == -1)
        printf("There are no child processes at all\n");
    else {
        printf("Process with pid=%d finished.\n", wr);
        if (WIFEXITED(*status))
            printf("It has exited with code=%d.\n",
                   WEXITSTATUS(*status));
        else
            printf("It was killed by signla %d.\n",
                   WTERMSIG(*status));
    }
    return 0;
}

Example: Launching Another Program

Starting an external command usually combines fork, descriptor setup, exec, and wait:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    int pid;

    pid = fork();
    if (pid == -1) {
        perror("fork");
        return 1;
    }

    if (pid == 0) {
        execlp("ls", "ls", "-l", "-a", "/var", NULL);
        perror("ls");
        _exit(1);
    }

    wait(NULL);
    puts("Ok");
    return 0;
}

The child becomes ls. The parent waits for the child and then continues.

Detailed notes - 5.3.8: Example of launching an external program

1

fork + exec + wait:

  • start ls -l -a /var
  • wait for it to finish
  • print "Ok"

creation:

  • pid = fork();
  • pid == -1: perror("fork"), terminate with failure

child, pid == 0:

  • execlp("ls", "ls", "-l", "-a", "/var", (char *)NULL);
  • successful exec replaces child program and never returns
  • returned exec: report the error and terminate the child
  • use the preceding subsection's flushing/_exit precautions as appropriate

parent, pid > 0:

  • wait(NULL) waits for and reaps the child
  • printf("Ok\n"); then return 0
  • this simple example discards child status
  • "Ok" therefore reports reaching the final step, not verified ls success
  • production code must also handle wait errors/interruption
Section test (1 file) - 5.3.8: Example of launching an external program
Section test08 (05-03)In catalog
05-03-08.cC / 73 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void wait_process(int pid)
{
    int wr, status, exit_status;

    do {
        wr = wait(&status);
        if (wr == -1)
            terminate("wait", 1);
    } while (wr != pid);

    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    } else
        printf("killed with signal: %d\n", WTERMSIG(status));
}

int launch_process(char *const cmds[])
{
    int pid;

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        execvp(cmds[0], cmds);
        terminate_exec("execvp", exit_process);
    }

    return pid;
}

int main(int argc, char **argv)
{
    int pid;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s program <args...>\n", argv[0]);
        return 1;
    }
    pid = launch_process(argv+1);
    wait_process(pid);

    return 0;
}

Time and Sleep

Unix time is commonly represented as seconds since 00:00:00 UTC on January 1, 1970:

time_t time(time_t *t);

Library functions convert it to calendar components or text:

struct tm *gmtime(const time_t *timep);
struct tm *localtime(const time_t *timep);
char *ctime(const time_t *timep);
int strftime(char *s, int max, const char *fmt,
             const struct tm *tm);

Higher-resolution current time:

int gettimeofday(struct timeval *tv, struct timezone *tz);

Sleeping calls:

Function Unit Important behavior
sleep(seconds) seconds Returns remaining seconds if interrupted
usleep(usec) microseconds Returns -1 on interruption
nanosleep(req, rem) seconds + nanoseconds Stores remaining time in rem if interrupted

Sleep duration is not exact. The process must enter the kernel, be blocked, and later wait for scheduling again.

Detailed notes - 5.3.9: Process Execution and Time

1

program execution takes time

  • kernel maintains the system clock
  • programs can read the time and arrange work around particular times or intervals

2

time(&t): current time as seconds since the Epoch

  • Epoch = 1 January 1970, 00:00:00 UTC
  • return type: time_t

3

book's historical aside: Unix time passed 1,500,000,000 seconds on 14 July 2017

  • first billion: 2001; second billion: 18 May 2033

4

time also stores its result through the supplied time_t pointer

  • time(NULL): use only the return value; no additional variable is written

5

use time_t for a variable whose address is passed to time

  • its underlying integer type depends on the implementation
  • integer values can be converted on assignment; incompatible pointer types cannot be substituted just because both pointed-to objects hold integers

6

convert seconds since the Epoch to calendar fields:

  • gmtime / gmtime_r: UTC
  • localtime / localtime_r: configured local time zone
  • input: pointer to time_t; result: struct tm

struct tm fields:

  • tm_year: year minus 1900; 2016 -> 116
  • tm_mon: month 0..11; tm_mday: day 1..31
  • tm_hour: hour 0..23; tm_min: minute 0..59
  • tm_sec: seconds, normally 0..59
  • tm_wday: weekday 0..6, Sunday = 0
  • tm_yday: day of year 0..365
  • tm_isdst: daylight-saving-time indication

7

convert a date/time into a fixed-format string:

  • asctime / asctime_r: input is struct tm
  • ctime / ctime_r: input is time_t
  • example result: "Sat Oct 22 00:57:53 2016\n"

8

functions ending in _r write into storage supplied by the caller

  • ordinary versions return pointers to library-owned storage
  • a later call can overwrite an earlier result
  • copy a result that must survive another call, or use caller-owned storage

9

strftime formats a struct tm using a format string

  • caller supplies output buffer and its size
  • useful when the fixed asctime / ctime format is unsuitable

10

one-second resolution is too coarse for many communication timeouts gettimeofday(&tv, NULL): obtain time in struct timeval

  • tv_sec: whole seconds since the Epoch
  • tv_usec: microseconds within that second; 1 microsecond = 10^-6 second
  • obsolete time-zone argument should be NULL

11

sleeping process: temporarily asks for no CPU time

  • sleep(seconds) blocks the caller for the requested number of seconds
  • sleep(60): request a one-minute pause
  • after the interval, the process becomes eligible to run again

12

sleep is a library function that can be implemented through other system calls

  • a separate kernel operation specifically named sleep is unnecessary

13

sleep return value:

  • 0: requested interval completed
  • positive: seconds remaining when a handled signal interrupted the sleep
  • includes a remaining fraction of a second in the returned whole-second count

14

usleep requests a pause in microseconds

  • some implementations require an argument below 1,000,000
  • sleep(3), then usleep(500000), attempts a 3.5-second pause

15

combining sleep and usleep adds overhead and reduces timing precision

  • entering/leaving the kernel takes time
  • becoming runnable does not mean immediately receiving CPU time
  • other runnable processes may delay actual execution

16

usleep returns 0 on completion or -1 on failure/interruption

  • does not directly report the remaining interval
  • book measures elapsed time by reading the clock before and after the call

17

nanosleep(&requested, &remaining): request a pause using struct timespec

  • tv_sec: whole seconds
  • tv_nsec: nanoseconds, 0..999,999,999; 1 nanosecond = 10^-9 second
  • requested specifies the interval
  • on interruption, remaining can receive the unexpired part
  • provides one interface for intervals both shorter and longer than a second
  • can also underlie the library sleep functions

18

nanosecond units do not guarantee nanosecond timing accuracy

  • actual clock resolution and scheduling delays depend on the system
  • the book's 1000 timer interrupts/second is an illustrative historical model, not a universal limit on modern timer resolution

19

priority affects how a process receives CPU time

  • book separates a user-controlled static priority from scheduler calculations
  • Linux nice values: -20 = highest priority, 19 = lowest
  • some Unix systems use an upper endpoint of 20
  • ordinary starting nice value: 0, unless inherited or explicitly changed

20

nice(increment): add to the current nice value

  • positive increment -> larger number -> lower scheduling priority
  • values are limited to the supported range
  • nice(1000) therefore requests the lowest available priority
  • returns the new nice value; nice(0) can read the current value

21

negative nice increment requests a higher scheduling priority

  • requires the appropriate privilege or permission
  • book describes the traditional rule allowing this only to superuser processes

22

-1 from nice may mean either failure or a legitimate nice value of -1

  • set errno = 0 before the call
  • if the result is -1, inspect errno to distinguish error from success
  • requesting an unauthorized priority increase is an error

23

nice value survives exec and is inherited through fork

  • set it before executing an external program to control that program's priority
  • a login process can establish a priority inherited by the user's session
  • raising priority still requires permission

24

getpriority(which, who) / setpriority(which, who, priority):

  • PRIO_PROCESS: who identifies a process by pid
  • PRIO_USER: who identifies a user's processes by uid
  • PRIO_PGRP: who identifies a process group by pgid

getpriority:

  • returns the nice value for the selected processes
  • if values differ, returns the smallest number / highest priority

setpriority:

  • assigns the requested nice value to selected processes
  • ordinary users can generally change only their own processes
  • increasing scheduling priority requires permission

25

getpriority has the same -1 ambiguity as nice

  • clear errno before calling; check it when the result is -1
Tests & experiments (8 files) - 5.3.9: Process Execution and Time
Section test09 (05-03)In catalog
priority-00.cC / 29 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>

int main(int argc, char **argv)
{
    int pid, old, new;

    if (argc != 3) {
        fprintf(stderr, "Usage: %s <process id> <priority: -20 to 19>\n",
                argv[0]);
        return 1;
    }

    pid = atoi(argv[1]);
    new = atoi(argv[2]);

    old = getpriority(PRIO_PROCESS, pid);
    if (new < old) {
        fprintf(stderr, "Cannot elevate priority as non-root user\n");
        return 1;
    }
    setpriority(PRIO_PROCESS, pid, new);
    new = getpriority(PRIO_PROCESS, pid);

    printf("%d %d\n", old, new);

    return 0;
}
priority-01.cC / 43 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main(int argc, char **argv)
{
    int pid, old, new;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <priority: -20 to 19>\n", argv[0]);
        return 1;
    }

    new = atoi(argv[1]);

    pid = fork();
    if (pid == -1)
        terminate("fork", 1);

    if (pid == 0) {
        getchar();
    } else {
        old = getpriority(PRIO_PROCESS, pid);
        if (new < old) {
            fprintf(stderr, "Cannot elevate priority as non-root user\n");
            return 1;
        }
        setpriority(PRIO_PROCESS, pid, new);
        new = getpriority(PRIO_PROCESS, pid);
        printf("%d %d\n", old, new);
        wait(NULL);

    }
    return 0;
}
time-00.cC / 9 lines
#include <stdio.h>
#include <time.h>

int main()
{
    long t;
    t = time(NULL);
    printf("%ld\n", t);
}
time-01.cC / 18 lines
#include <stdio.h>
#include <time.h>

int main()
{
    char *s1, *s2;
    time_t t1, t2;

    t1 = time(NULL);
    s1 = ctime(&t1);
    getchar();

    t2 = time(NULL);
    s2 = ctime(&t2);

    printf("%s", s1);
    printf("%s", s2);
}
time-02.cC / 20 lines
#include <stdio.h>
#include <time.h>

enum { time_size = 26 };

int main()
{
    char s1[time_size], s2[time_size];
    time_t t1, t2;

    t1 = time(NULL);
    ctime_r(&t1, s1);
    getchar();

    t2 = time(NULL);
    ctime_r(&t2, s2);

    printf("%s", s1);
    printf("%s", s2);
}
time-03.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

enum { time_size = 200 };

int main(int argc, char **argv)
{
    char outstr[time_size];
    time_t t;
    struct tm *tmp;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <string format for time>\n", argv[0]);
        exit(1);
    }

    t = time(NULL);
    tmp = localtime(&t);
    if (tmp == NULL) {
        perror("localtime");
        exit(1);
    }

    if (strftime(outstr, time_size, argv[1], tmp) == 0) {
        fprintf(stderr, "strftime returned 0");
        exit(2);
    }

    printf("Result string is is \"%s\"\n", outstr);
    return 0;
}
time-04.cC / 18 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

int main()
{
    int r, i;
    struct timeval tv;
    for (i = 0; i < 100; i++) {
        r = gettimeofday(&tv, NULL);
        if (r == -1) {
            perror("gettimeofday");
            exit(1);
        }
        printf("%ld %ld\n", tv.tv_sec, tv.tv_usec);
    }
    return 0;
}
time-05.cC / 36 lines
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main()
{
    int r;
    struct timespec duration, rem;
    struct timeval tv;

    duration.tv_sec = 3;
    duration.tv_nsec = 5e8;

    r = gettimeofday(&tv, NULL);
    if (r == -1)
        terminate("gettimeofday", 1);
    printf("%ld %ld\n", tv.tv_sec, tv.tv_usec);

    r = nanosleep(&duration, &rem);
    if (r == -1)
        terminate("nanosleep", 1);

    r = gettimeofday(&tv, NULL);
    if (r == -1)
        terminate("gettimeofday", 1);
    printf("%ld %ld\n", tv.tv_sec, tv.tv_usec);

    return 0;
}

Priority

Process priority is controlled by the static priority component, traditionally called the nice value. On Linux, lower numbers mean higher priority:

Nice value Meaning
-20 Highest ordinary priority
0 Default
19 Lowest ordinary priority

Calls:

int nice(int inc);
int getpriority(int which, int who);
int setpriority(int which, int who, int prio);

Unprivileged processes may lower their own priority. Raising priority normally requires superuser privileges.

Descriptor Redirection

Descriptor duplication calls:

int dup(int fd);
int dup2(int fd, int new_fd);

dup creates a new descriptor for the same open file object. dup2 creates or replaces a descriptor with a chosen number. The duplicated descriptors share the same file position and file-status flags because they refer to the same kernel object.

Redirect standard output for a child before exec:

int fd, pid;

fd = open("flist", O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fd == -1) {
    perror("flist");
    exit(1);
}

pid = fork();
if (pid == 0) {
    dup2(fd, 1);
    close(fd);
    execlp("ls", "ls", "-l", "-a", "-R", "/", NULL);
    perror("ls");
    _exit(1);
}

close(fd);
wait(NULL);
Detailed notes - 5.3.10: Redirecting Input and Output

1

file descriptors can refer to files, pipes, sockets, and other kernel objects

  • open and similar descriptor-allocating operations choose the lowest free number
  • after close(0), the next successful open normally obtains descriptor 0
  • close releases a descriptor regardless of the kind of object behind it

2

standard descriptor numbers are a convention used by programs and

libraries:

  • 0: standard input
  • 1: standard output
  • 2: standard error
  • kernel does not give these numbers a special file type

redirecting stdout by closing and reopening:

  • close(1)
  • open("file.txt", O_WRONLY|O_CREAT|O_TRUNC, 0666)
  • if 0 remains open, successful open gets descriptor 1
  • printf / putchar then write to that file through the usual stdout stream

3

closing stdout before opening its replacement is fragile:

  • if open fails, descriptor 1 remains closed
  • a later unrelated open may accidentally become stdout

dup(fd): duplicate an existing descriptor using the lowest free number

  • both descriptors refer to the same open file description
  • does not create an independent I/O stream or file position
  • lseek through either descriptor changes their shared offset
  • same sharing occurs when fork copies the descriptor table

4

dup2(fd, new_fd): duplicate fd at a specified descriptor number

  • if new_fd is open, it is replaced by the duplicate
  • closing the old destination and replacing it are one operation
  • if the two descriptor numbers are identical and valid, nothing changes

5

temporarily redirect a library that always writes to stdout:

  • open file.dat for writing, creating/truncating it; handle failure first
  • fflush(stdout): send any previously buffered output to its original destination
  • save1 = dup(1): keep a descriptor for the original stdout
  • dup2(fd, 1): make the file the new stdout
  • close(fd): remove the redundant descriptor; descriptor 1 still holds the file
  • run the library operations that produce the required output
  • fflush(stdout) before restoring, so buffered file output reaches the file
  • dup2(save1, 1): restore original stdout; redirected descriptor is replaced
  • close(save1): release the saved duplicate
  • check dup / dup2 failures as well as open failures in complete code

6

shell redirections (<, >, >>) usually happen when launching a program

  • child performs dup2 before exec, then closes the redundant descriptor
  • exec preserves ordinary open descriptors unless marked close-on-exec
  • executed program inherits the redirected standard stream

7

example: reproduce ls -l -a -R / > flist

  • fork; handle failure

child:

  • open flist with O_CREAT|O_WRONLY|O_TRUNC, mode 0666
  • on failure: report error and terminate
  • dup2(fd, 1), then close the redundant fd
  • execlp("ls", "ls", "-l", "-a", "-R", "/", NULL)
  • if exec returns: report its error and terminate unsuccessfully

parent:

  • wait for child and collect status
  • !WIFEXITED(status) or WEXITSTATUS(status) != 0 -> unsuccessful execution
  • all directory-listing output goes to flist; stderr remains separate

8

alternative: open flist in the parent before fork

  • parent can report an open error without creating a child
  • child inherits fd, redirects stdout, closes its redundant copy, and executes ls
  • parent must close its own copy of fd before waiting
  • closing one process's copy does not invalidate the other's copy
  • examples assume fd differs from 1; do not close descriptor 1 after a no-op dup2

9

fcntl(fd, F_DUPFD, minimum): duplicate fd at the first free number >= minimum

  • dup(fd) is equivalent to fcntl(fd, F_DUPFD, 0)
  • fcntl(fd, F_DUPFD, 20): use 20 if free, otherwise the next free number above it
  • unlike dup2, does not replace an already open target descriptor
The new program still writes to descriptor 1; the shell chooses what descriptor 1 refers to.
Redirection rewires a descriptor before exec. Open full size - Editable SVG
Tests & experiments (4 files) - 5.3.10: Redirecting Input and Output
Section test10 (05-03)In catalog
redirect-00.cC / 35 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main(int argc, char **argv)
{
    int r, fd;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
        return 1;
    }

    r = close(1);
    if (r == -1)
        terminate("close", 2);
    fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if (fd == -1)
        terminate("open", 2);

    printf("hello there\n");

    fflush(stdout);
    r = close(fd);
    if (r == -1)
        terminate("close", 2);
    return 0;
}
redirect-01.cC / 40 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main(int argc, char **argv)
{
    int r, fd, save1;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
        return 1;
    }

    fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if (fd == -1)
        terminate("open", 2);
    fflush(stdout);

    save1 = dup(1);
    dup2(fd, 1);
    r = close(fd);
    if (r == -1)
        terminate("close", 2);

    printf("hello there\n");
    fflush(stdout);

    dup2(save1, 1);
    r = close(save1);
    if (r == -1)
        terminate("close", 2);
    return 0;
}
redirect-02.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main(int argc, char **argv)
{
    int fd, pid, status;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
        return 1;
    }

    pid = fork();
    if (pid == -1)
        terminate("pid", 2);

    if (pid == 0) {
        fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
        if (fd == -1)
            terminate("open", 2);
        dup2(fd, 1);
        close(fd);
        execlp("ls", "ls", "-l", "-a", "-R", "./", NULL);
        terminate("ls", 2);
    }

    wait(&status);
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
        terminate("wait", 2);

    return 0;
}
redirect-03.cC / 42 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main(int argc, char **argv)
{
    int fd, pid, status;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
        return 1;
    }

    fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
    if (fd == -1)
        terminate("open", 2);

    pid = fork();
    if (pid == -1)
        terminate("pid", 2);
    if (pid == 0) {
        dup2(fd, 1);
        close(fd);
        execlp("ls", "ls", "-l", "-a", "-R", "./", NULL);
        terminate("ls", 2);
    }

    close(fd);      /* don't forget to close descriptor in parent */
    wait(&status);
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
        terminate("wait", 2);

    return 0;
}

Credentials and Privileges

Unix permission checks are made for processes, not abstract users. A process has several user and group identifiers.

Identifier Meaning
real uid/gid Identity of the user/group that started the process
effective uid/gid Identity used for most permission checks
saved uid/gid Stored identity used to regain a previous effective id
supplementary groups Additional groups used in access checks

SetUID and SetGID executable files change the effective and saved identifiers on exec. This lets a program temporarily run with the file owner's or file group's privileges.

Calls:

int getuid(void);
int geteuid(void);
int getgid(void);
int getegid(void);
int getgroups(int size, gid_t *list);

int setuid(int uid);
int seteuid(int euid);
int setgid(int gid);
int setegid(int egid);
int setgroups(int size, const gid_t *list);

For an unprivileged process, seteuid and setegid can usually switch only among the real, effective, and saved identifiers. A process with effective uid 0 can set identifiers much more freely. Dropping privileges permanently must be done deliberately.

Detailed notes - 5.3.11: Process Credentials

1

process credentials include:

  • real uid / gid: normally identify the user who started the process
  • effective uid / gid: used for most permission checks
  • saved user ID / saved group ID
  • supplementary group IDs

Linux also has:

  • fsuid / fsgid for filesystem permission checks, usually matching effective IDs
  • capabilities: individual privileges separate from the simple root/non-root model

2

book's ordinary user-process model starts with PID 1, traditionally /sbin/init

  • starts with root credentials; other user processes descend from it
  • fork copies the parent's real, effective, saved, and supplementary group IDs
  • credentials therefore remain unchanged until a process explicitly changes them

3

privileged login programs establish the user's session credentials

  • set supplementary groups while still privileged
  • set real, effective, and saved group IDs to the user's primary group
  • set real, effective, and saved user IDs to the user's uid
  • then run the shell or window manager
  • dropping all root user IDs removes the saved route back to root
  • merely changing the effective ID need not make a privilege drop permanent

4

executing a SetUid / SetGid program can separate real and effective

IDs:

  • real IDs remain those of the calling process
  • SetUid: effective uid becomes the executable owner's uid
  • SetGid: effective gid becomes the executable's group ID
  • resulting effective IDs are copied to the saved IDs
  • supplementary groups are preserved

5

real and saved IDs allow controlled switching of effective credentials

  • a SetUid program can use the invoking user's rights for some operations and the program owner's rights for others
  • unprivileged changes are restricted to already held identity values
  • a sufficiently privileged process can choose other IDs

6

example: Vasya uid 1003 owns SetUid program vasyaprog; Petya uid 1012 runs it

  • real uid = 1012
  • effective uid = 1003; saved uid = 1003
  • initially performs permission-checked work with Vasya's rights
  • setting effective uid to 1012 temporarily uses Petya's rights
  • saved uid remains 1003, allowing effective uid to switch back to Vasya

7

read process IDs:

  • getuid(): real uid
  • geteuid(): effective uid
  • getgid(): real gid
  • getegid(): effective gid
  • these calls return the requested ID and do not fail

8

actual return types are uid_t and gid_t, not necessarily int

  • preserve these types when storing IDs
  • converting an unsigned ID above INT_MAX to int can lose the intended value

9

getresuid / getresgid retrieve real, effective, and saved IDs together

  • available on Linux and some other systems
  • book distinguishes these extensions from the more portable basic getters

10

getgroups(size, array): retrieve supplementary group IDs

  • array elements must have type gid_t
  • size gives array capacity; insufficient space produces an error
  • getgroups(0, NULL): ask how many entries are needed
  • allocate n * sizeof(gid_t), then call getgroups(n, array)
  • complete code must handle call/allocation failures and later free the array
  • effective primary gid may or may not appear in the returned list
  • -> use getgroups together with getegid for the full group information

11

seteuid / setegid change only the effective user/group ID

  • an unprivileged process can select its corresponding real, effective, or saved ID; requesting its current ID is an allowed no-op
  • selecting an unrelated ID fails
  • privileged callers can choose IDs outside that restricted set
  • use uid_t / gid_t arguments in actual declarations

12

setuid / setgid also primarily affect the effective ID

  • unprivileged caller: can switch within the IDs permitted by the system
  • privileged caller: changes real, effective, and saved IDs together
  • seteuid / setegid still change only the effective ID when called with privilege
  • -> setuid away from root can permanently discard the saved root identity

13

setgroups(size, list): replace the supplementary group list

  • privileged operation
  • list points to size elements of type gid_t
  • old supplementary group membership is replaced, not extended
  • real, effective, and saved primary group IDs do not change

14

other interfaces can change or retrieve several IDs together:

  • setreuid / setregid
  • setresuid / setresgid
  • getresuid / getresgid
  • exact availability and semantics depend on the system
Tests & experiments (4 files) - 5.3.11: Process Credentials
Section test11 (05-03)In catalog
permissions-00.cC / 64 lines
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/fsuid.h>

static int get_fsuid_now(void)
{
    /*
       setfsuid(-1) fails, but returns the current fsuid.
       This is the usual Linux trick for reading fsuid.
    */
    return setfsuid((uid_t)-1);
}

static void show_ids(void)
{
    FILE *f = fopen("/proc/self/status", "r");
    char line[256];

    if (!f) {
        perror("fopen");
        exit(1);
    }

    while (fgets(line, sizeof line, f)) {
        if (strncmp(line, "Uid:", 4) == 0 ||
            strncmp(line, "Gid:", 4) == 0) {
            fputs(line, stdout);
        }
    }

    fclose(f);
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s <new-fsuid>\n", argv[0]);
        return 1;
    }

    uid_t target = atoi(argv[1]);

    printf("Before:\n");
    show_ids();
    printf("current fsuid = %d\n\n", get_fsuid_now());

    int old = setfsuid(target);
    int now = get_fsuid_now();

    printf("setfsuid(%d) returned old fsuid = %d\n", target, old);

    printf("After:\n");
    show_ids();
    printf("current fsuid = %d\n", now);

    if (now != target) {
        printf("\nfsuid did NOT change. You probably lack CAP_SETUID, "
               "or target UID is not allowed.\n");
    }

    return 0;
}
permissions-01.cC / 49 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <grp.h>

enum { width = 10, group_size = 64 };

static void print_group_ids()
{
    int n, i;
    gid_t *p;

    n = getgroups(0, NULL);
    p = malloc(n * sizeof(gid_t));
    getgroups(n, p);
    printf("%*s ids: ", width-1, "Group");
    for (i = 0; i < n; i++)
        printf("%d ", p[i]);
    printf("\n");
}

int main()
{
    int n;
    gid_t *p;

    printf("%*s id: %d\t", width, "User", getuid());
    printf("%*s id: %d\n", width, "Effective User", geteuid());
    printf("%*s id: %d\t", width, "Group", getgid());
    printf("%*s id: %d\n", width, "Effective Group", getegid());
    print_group_ids();

    setgid(1004);
    /* setuid(1004); */

    n = 2;
    p = malloc(n * sizeof(gid_t));
    p[0] = 1;
    p[1] = 2;
    setgroups(n, p);

    printf("%*s id: %d\t", width, "User", getuid());
    printf("%*s id: %d\n", width, "Effective User", geteuid());
    printf("%*s id: %d\t", width, "Group", getgid());
    printf("%*s id: %d\n", width, "Effective Group", getegid());
    print_group_ids();

    return 0;
}
permissions-02.cC / 49 lines
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <grp.h>

enum { width = 15 };

static void print_id(const char *name, int id)
{
    printf("%*s id: %d\n", width, name, id);
}

int main()
{
    uid_t ruid, euid, suid;
    gid_t rgid, egid, sgid;

    getresuid(&ruid, &euid, &suid);
    getresgid(&rgid, &egid, &sgid);

    print_id("User", ruid);
    print_id("Effective User", euid);
    print_id("Saved User", suid);
    printf("\n");
    print_id("Group", rgid);
    print_id("Effective Group", egid);
    print_id("Saved Group", sgid);

    printf("\n");
    printf("-------------------------------------------------\n");
    printf("\n");

    euid = ruid;
    egid = rgid;

    setresuid(ruid, euid, suid);
    setresgid(rgid, egid, sgid);

    print_id("User", ruid);
    print_id("Effective User", euid);
    print_id("Saved User", suid);
    printf("\n");
    print_id("Group", rgid);
    print_id("Effective Group", egid);
    print_id("Saved Group", sgid);

    return 0;
}
permissions-03.cC / 47 lines
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <grp.h>

enum { width = 15 };

static void print_id(const char *name, int id)
{
    printf("%*s id: %d\n", width, name, id);
}

int main()
{
    uid_t ruid, euid, suid;
    gid_t rgid, egid, sgid;

    getresuid(&ruid, &euid, &suid);
    getresgid(&rgid, &egid, &sgid);

    print_id("User", ruid);
    print_id("Effective User", euid);
    print_id("Saved User", suid);
    printf("\n");
    print_id("Group", rgid);
    print_id("Effective Group", egid);
    print_id("Saved Group", sgid);

    printf("\n");
    printf("-------------------------------------------------\n");
    printf("\n");

    euid = ruid;
    egid = rgid;

    setreuid(ruid, euid);
    setregid(rgid, egid);

    print_id("User", ruid);
    print_id("Effective User", euid);
    printf("\n");
    print_id("Group", rgid);
    print_id("Effective Group", egid);

    return 0;
}

Resource Limits

Resource limits are inherited by children and preserved across exec. A shell's ulimit -a command shows many current limits.

Each limit has two values:

Limit value Meaning
Soft limit Enforced by the kernel
Hard limit Maximum value to which the soft limit may be raised

Unprivileged processes may lower hard limits but cannot raise them again.

Calls:

int getrlimit(int resource, struct rlimit *rlim);
int setrlimit(int resource, const struct rlimit *rlim);

Common resources:

Resource Meaning
RLIMIT_AS Virtual address space size
RLIMIT_CORE Maximum core file size
RLIMIT_CPU CPU time limit
RLIMIT_FSIZE Maximum file size created by the process
RLIMIT_NOFILE Maximum descriptor number plus one
RLIMIT_NPROC Process count limit for a user, checked for descendants
RLIMIT_STACK Stack size

RLIM_INFINITY means no limit for that resource.

The current limits, then a one-second CPU limit that the spinning loop soon exceeds. -1 is RLIM_INFINITY:

#include <stdio.h>
#include <sys/resource.h>

static void print_entry(const char *name, int resource)
{
    struct rlimit rlim;
    getrlimit(resource, &rlim);
    printf("%s: soft %ld, hard %ld\n",
           name, rlim.rlim_cur, rlim.rlim_max);
}

int main()
{
    struct rlimit rlim;

    print_entry("virtual memory", RLIMIT_AS);
    print_entry("core file size", RLIMIT_CORE);
    print_entry("cpu time", RLIMIT_CPU);
    print_entry("file size", RLIMIT_FSIZE);
    print_entry("open files", RLIMIT_NOFILE);
    print_entry("max user processes", RLIMIT_NPROC);
    print_entry("stack size", RLIMIT_STACK);

    rlim.rlim_cur = 1;
    rlim.rlim_max = 10;
    setrlimit(RLIMIT_CPU, &rlim);
    print_entry("cpu time", RLIMIT_CPU);

    while (1)
        {}

    return 0;
}
$ ./limit
virtual memory: soft -1, hard -1
core file size: soft -1, hard -1
cpu time: soft -1, hard -1
file size: soft -1, hard -1
open files: soft 524288, hard 524288
max user processes: soft 122192, hard 122192
stack size: soft 8388608, hard -1
cpu time: soft 1, hard 10
CPU time limit exceeded (core dumped)

The last line comes from the shell: the kernel sent SIGXCPU, whose default action ends the process.

Detailed notes - 5.3.12: Resource Limits

1

resource limits restrict how much of a permitted resource a process may use

  • examples: virtual memory, open descriptors, processes for a user
  • different from permission checks that simply allow or forbid an operation

2

ulimit -a displays the calling shell's current resource limits

  • examples: file size, core size, open files, stack, CPU time, user processes
  • units depend on the displayed resource and shell interface

3

limits belong to individual processes

  • inherited by fork; preserved by exec
  • setting a limit affects the caller and descendants that inherit it
  • does not change limits of unrelated processes or the system as a whole

user-process-count limit:

  • caller's limit is checked against the user's total process count
  • at the limit, fork fails with -1 and errno = EAGAIN
  • another process of the same user can have a different limit
  • such a process is governed by its own limit when it calls fork

4

each resource limit has two levels:

  • soft limit: value the kernel enforces
  • hard limit: ceiling for changes to the soft limit

ordinary process:

  • can lower or raise its soft limit up to its hard limit
  • can lower its hard limit, but cannot raise it again without privilege

privileged process: can raise hard limits within system constraints

5

setrlimit(resource, &limit): set a resource's soft and hard limits

struct rlimit:

  • rlim_cur: current / soft limit
  • rlim_max: maximum / hard limit
  • RLIM_INFINITY: no limit for that value
  • use the symbolic constant; its representation depends on the implementation

6

resource selects the limit to change:

  • RLIMIT_AS: virtual address-space size in bytes
  • RLIMIT_CORE: maximum core-dump size in bytes; 0 disables core dumps core dump records process memory/state for examining a crash in a debugger
  • RLIMIT_CPU: CPU time in seconds soft limit -> SIGXCPU; further CPU use can cause repeated SIGXCPU delivery hard limit -> SIGKILL, which cannot be caught or ignored
  • RLIMIT_FSIZE: maximum file size in bytes at the setrlimit interface exceeding it -> SIGXFSZ; if execution continues, write can fail with EFBIG do not confuse this with block units used by some shell ulimit displays
  • RLIMIT_NOFILE: upper bound on descriptor numbers, not just current open count a newly obtained descriptor must have a number below the limit applies even when many lower-numbered descriptors are unused
  • RLIMIT_NPROC: process-count limit checked against processes of the real user checked using the limit of the process attempting fork
  • RLIMIT_STACK: maximum stack address-space size
  • other limits are described by the system's setrlimit documentation

7

getrlimit(resource, &limit): read the current soft and hard limits

  • fills the same struct rlimit used by setrlimit

8

disk quotas are a separate mechanism

  • limit disk space for users and/or groups on individual filesystems
  • Linux and FreeBSD expose quota operations through quotactl
Section test (1 file) - 5.3.12: Resource Limits
Section test12 (05-03)In catalog
limit.cC / 33 lines
#include <stdio.h>
#include <sys/resource.h>

static void print_entry(const char *name, int resource)
{
    struct rlimit rlim;
    getrlimit(resource, &rlim);
    printf("%s: soft %ld, hard %ld\n",
           name, rlim.rlim_cur, rlim.rlim_max);
}

int main()
{
    struct rlimit rlim;

    print_entry("virtual memory", RLIMIT_AS);
    print_entry("core file size", RLIMIT_CORE);
    print_entry("cpu time", RLIMIT_CPU);
    print_entry("file size", RLIMIT_FSIZE);
    print_entry("open files", RLIMIT_NOFILE);
    print_entry("max user processes", RLIMIT_NPROC);
    print_entry("stack size", RLIMIT_STACK);

    rlim.rlim_cur = 1;
    rlim.rlim_max = 10;
    setrlimit(RLIMIT_CPU, &rlim);
    print_entry("cpu time", RLIMIT_CPU);

    while (1)
        {}

    return 0;
}

Interprocess Communication Overview

Processes can communicate indirectly through ordinary files or shared mmap mappings, but Unix also provides specialized mechanisms.

Mechanism Use
Signals Small asynchronous notifications
Pipes and FIFOs One-way byte streams
Shared memory Common memory visible to multiple processes
Virtual terminals Terminal-like interaction implemented by processes
ptrace Debugger-style control of another process
Sockets Local or network communication
System V IPC Older shared memory, semaphore, and message-queue APIs

The right mechanism depends on whether data must be transferred, whether the processes are related, whether communication crosses machines, and whether synchronization is needed.

Detailed notes - 5.3.13: Overview of Interprocess Communication

1

processes can affect one another through shared objects

  • one process can modify a file that another reads
  • mmap can map a memory region accessible to several processes
  • shared memory: one process's changes can be observed by others
  • communication does not always require a separate, specialized IPC operation

2

signals are a simple specialized communication mechanism

  • in the book's classical-signal model, the signal number identifies the event
  • no general data stream is carried by such a signal

3

pipes provide one-way data transfer

  • named pipes: FIFO
  • unnamed pipes: pipe
  • one end is used for writing, the other for reading
  • data written by one process can be read by another

4

tracing lets one process control and inspect another's execution

  • typical controller: debugger
  • controlled process: program being debugged

5

a pseudo-terminal lets a user process emulate a terminal device

  • examples: xterm and remote-login servers such as sshd
  • emulator communicates with programs attached to the emulated terminal
  • those programs can use it as their controlling terminal

6

System V IPC includes:

  • shared memory
  • semaphore sets
  • message queues
  • author strongly discourages these interfaces; this is the book's assessment

7

sockets provide a common interface for communication protocols

  • support communication between processes on different computers
  • not limited to TCP/IP or any one network standard
  • adding a protocol need not require an entirely new system-call interface
  • Unix-domain sockets also support communication within one system
  • local sockets do not require an external network connection

Signals

A signal is an asynchronous notification delivered to a process. Classic Unix signals carry only a signal number.

Common signals:

Signal Default role
SIGTERM Request termination; can be caught or ignored
SIGKILL Force termination; cannot be caught or ignored
SIGINT Terminal interrupt, usually from Ctrl-C
SIGQUIT Terminal quit, usually from Ctrl-\
SIGSEGV Invalid memory access
SIGFPE Arithmetic exception, such as division by zero
SIGILL Illegal instruction
SIGBUS Bus or address-alignment error
SIGSTOP Stop process; cannot be caught or ignored
SIGCONT Continue a stopped process
SIGCHLD Child changed state or terminated
SIGALRM Timer from alarm expired
SIGUSR1, SIGUSR2 Application-defined signals
SIGPIPE Write to a pipe with no readers

Send a signal:

int kill(int target, int signal_number);

Target rules:

target Meaning
positive pid Send to that process
0 Send to processes in the caller's process group
-1 Send broadly, subject to permission rules
less than -1 Send to process group -target

A process can set a signal disposition to default action, ignore, or handler with signal.

For portable serious programs, sigaction is preferable to signal, but its interface is more detailed.

Signal handlers run at unexpected points. Keep them small:

Timer signal:

unsigned int alarm(unsigned int seconds);

Only one SIGALRM timer is active per process. A new alarm replaces the old one; alarm(0) cancels it.

Waiting for signals has race hazards. A loop like while (!flag) pause(); can miss the exact moment between checking flag and entering pause. The robust pattern blocks the signal with sigprocmask and waits with sigsuspend, which temporarily installs a mask for the duration of the wait.

Etude 5.22 prints + once a second; Ctrl-C switches it to -, Ctrl-\ back to +, and a second Ctrl-C within one second ends the program. The SIGINT handler restores the default action, and only the next SIGALRM installs the handler again:

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>

volatile static char to_print[] = "+";

static void handler_sigint(int s)
{
    int save_errno = errno;
    signal(SIGINT, SIG_DFL);
    to_print[0] = '-';
    write(1, (char *) to_print, 1);
    errno = save_errno;
}

static void handler_sigquit(int s)
{
    int save_errno = errno;
    signal(SIGQUIT, handler_sigquit);
    to_print[0] = '+';
    write(1, (char *) to_print, 1);
    errno = save_errno;
}

static void handler_sigalrm(int s)
{
    int save_errno = errno;
    signal(SIGALRM, handler_sigalrm);
    signal(SIGINT, handler_sigint);
    write(1, (char *) to_print, 1);
    errno = save_errno;
}

int main()
{
    signal(SIGINT, handler_sigint);
    signal(SIGQUIT, handler_sigquit);
    signal(SIGALRM, handler_sigalrm);

    while (1) {
        alarm(1);
        pause();
    }

    return 0;
}
$ ./plusminus
+^C--^\++^C-^C
$ echo $?
130
Detailed notes - 5.3.14: Signals

1

this subsection covers ordinary signals

  • real-time signals can carry additional information and be queued
  • the author's advice against using them is a design preference

2

signal: a notification chosen from a predefined set

  • originally used to terminate processes
  • later acquired other uses

3

termination signals:

  • SIGTERM: request termination; can be caught or ignored
  • SIGKILL: force termination; cannot be caught or ignored
  • commonly SIGTERM = 15 and SIGKILL = 9; use symbolic names in programs

4

graceful termination followed by forced termination:

  • send SIGTERM first -> allow cleanup
  • send SIGKILL after a timeout if the process remains alive
  • e.g. an editor may save recovery information before shutting down

5

fault signals:

  • SIGILL: illegal instruction
  • SIGSEGV: invalid memory access / protection violation
  • SIGFPE: arithmetic exception, e.g. integer division by zero
  • SIGBUS: certain invalid memory accesses, including alignment errors

default action: terminate and, when enabled, produce a core dump

  • catching a fault does not repair the damaged program state
  • trying to save corrupted data can cause another fault

6

SIGSTOP: suspend execution; cannot be caught or ignored SIGCONT: resume execution

  • can have a handler, but still resumes a stopped process

7

terminal keyboard signals go to its foreground process group:

  • Ctrl-C -> SIGINT
  • Ctrl-\ -> SIGQUIT
  • default: terminate; SIGQUIT also requests a core dump

8

SIGCHLD: notify a parent about a child's termination

  • default disposition does not terminate the parent

9

SIGALRM: timer notification requested by alarm

  • useful for timeouts
  • default action is termination -> install the intended disposition first

10

SIGUSR1 and SIGUSR2: application-defined notifications

  • default action is termination

11

signal names are integer macro constants in system headers

  • e.g. SIGKILL denotes a signal number
  • include the headers; do not define these constants yourself

12

senders: another process or the kernel; recipient: a process

kill(target_pid, sig_no) sends a signal:

  • target_pid > 0: that process
  • target_pid = 0: the caller's process group
  • target_pid < -1: process group -target_pid
  • target_pid = -1: eligible processes, with system-specific exclusions
  • group signalling can include the caller itself

permissions restrict which processes can be signalled

  • normally processes of the same user; privileged processes have broader access
  • return: 0 on success, -1 on error

13

signal disposition: what to do when a signal arrives

  • default action
  • ignore it
  • call a handler

SIGKILL and SIGSTOP cannot have their dispositions changed

14

simple handler signature: void handler(int s)

  • receives the signal number
  • returns no value

15

signal installs a disposition:

  • typedef void (*sighandler_t)(int);
  • sighandler_t signal(int signo, sighandler_t hdl);
  • hdl: handler address, SIG_IGN, or SIG_DFL
  • return: previous disposition, or SIG_ERR on failure

16

installing a handler does not call it

  • it changes the response to a future signal
  • if no such signal arrives, the handler is never called

17

handlers run asynchronously relative to the main program

  • execution can be interrupted at an unexpected point
  • one handler can serve several signals by inspecting its argument

18

historical signal semantics differed between systems

System V behaviour:

  • reset disposition to default before entering the handler
  • handler must reinstall itself to catch another occurrence
  • another signal can arrive before reinstallation and take the default action
    • -> a second SIGUSR1 can terminate the process

19

early implementations made this race difficult to observe in practice

  • relying on their scheduling details does not provide a portable guarantee
  • interface users should not need undocumented timing assumptions

20

kernel implementation of signal delivery is discussed later

21

another System V problem: the same signal can interrupt its own handler

  • occurs after the handler has reinstalled itself
  • nested calls can interfere through shared global state

22

traditional names for the two behaviours:

  • System V semantics
  • BSD semantics

these names refer to differences between historical Unix families

23

BSD signal handling:

  • disposition remains installed until explicitly changed
  • the signal being handled is blocked during its handler
    • -> no re-entry caused by that same signal
  • same signal interface name, but different behaviour from System V

24

Linux historically exposed a System V-style signal syscall

  • C libraries commonly implement signal through sigaction with BSD behaviour
  • library function behaviour need not match a same-named kernel syscall

25

prefer sigaction when explicit, predictable handling semantics matter

  • availability of a raw signal syscall depends on the architecture
  • the library can still provide signal using another kernel interface

26

sigaction gives finer control over handling and signal masks

  • queued signals and attached data use additional interfaces such as sigqueue
  • detailed configuration is outside this subsection

27

for the book's signal-based examples:

  • reinstall at the start of the handler for historical System V compatibility
  • explicitly select SIG_DFL if only one occurrence should be caught
  • sigaction avoids depending on these historical signal differences

28

a handler is entered through signal delivery, not an ordinary main-program call

  • main cannot pass arbitrary arguments or collect a return value
  • examples communicate through carefully chosen global variables

29

most library functions cannot safely run in a signal handler

  • a signal may interrupt an update to the library's internal state
  • calling into that state again can observe an incomplete update
  • use only operations guaranteed to be async-signal-safe

30

malloc and free are unsuitable in handlers

  • the interrupted program may already be modifying heap metadata
  • re-entry can corrupt the heap or cause other failures
  • timing-dependent failures are particularly hard to reproduce

31

buffered standard I/O is also unsuitable in handlers

  • printf and related functions maintain mutable stream buffers and state

32

low-level I/O such as write can be used, but preserve errno

  • a handler's syscall may overwrite an error belonging to interrupted code
  • save errno on entry and restore it before returning

33

ordinary global variables can also be unsafe

  • an access wider than a machine operation may be interrupted halfway
  • example: a 64-bit value accessed in two halves on a 32-bit processor
  • -> main can combine half of the old value with half of the new value

34

volatile tells the compiler that a value can change unexpectedly

  • prevents reuse of a cached value where a fresh access is required
  • does not itself make compound operations atomic

35

volatile sig_atomic_t is the portable type for a simple handler flag

  • its individual reads and writes are indivisible relative to signal delivery
  • this does not make all arithmetic or read-modify-write operations atomic
  • it is not a general synchronization mechanism for threads or shared memory

36

native-width accesses often use one instruction on the processors discussed

  • this explains why small integer flags are convenient
  • instruction-level observations are not a substitute for C's guarantees

37

the book uses volatile int, reflecting its target implementations

  • sig_atomic_t is often an alias for int
  • retaining sig_atomic_t expresses the required portable guarantee

38

a caught signal can interrupt a blocking operation

  • many affected calls return -1 with errno = EINTR
  • EINTR indicates interruption, not necessarily an underlying I/O failure

39

handlers execute in user space

  • a process blocked in the kernel must be allowed to run its handler
  • after handling, the interrupted operation may finish, restart, or report EINTR

40

waiting indefinitely in the kernel must not prevent signal handling

  • a short operation can finish before the handler runs
  • an unfinished blocking operation can report EINTR
  • caller may need to retry or reconsider whether to keep waiting

41

SA_RESTART, configured through sigaction, restarts certain interrupted calls

  • eligibility depends on the call and circumstances
  • some read, write, and wait operations can restart
  • nanosleep does not restart automatically this way

42

some signal library implementations enable SA_RESTART implicitly

  • -> signal alone can conceal the restart policy

43

for each blocking call in a program with handlers:

  • handle EINTR appropriately
  • do not assume a signal will necessarily make that call return
  • use sigaction to control the policy explicitly

44

example task: print a message on Ctrl-C and finish after 25 notifications

naive implementation:

  • global counter n
  • handler increments n and calls printf
  • main installs SIGINT handler and spins while n < 25

45

improvements to that example:

  • use a volatile signal-safe counter / flag
  • account for the historical disposition-reset behaviour
  • use a fixed message and write instead of printf
  • save and restore errno in the handler
  • replace the empty busy loop with a blocking wait
  • the book first uses sleep(1)

46

increasing the sleep interval avoids more periodic wakeups

  • a handled signal interrupts sleep
  • main can then check the loop condition immediately

47

pause waits for a signal whose handler is executed

  • no parameters
  • after the handler returns: -1, errno = EINTR
  • avoids periodic wakeups caused by sleep

48

replacing sleep with pause still leaves a race

  • checking the counter and beginning to wait are separate operations

49

ordinary signals with the same number can merge while pending

  • several sends need not produce the same number of handler calls
  • do not use their occurrence count as a reliable message count

50

alarm(seconds) requests one SIGALRM after the specified interval

  • timer is removed when it expires
  • return: remaining seconds from a previous timer, or 0 if none existed

51

only one alarm timer is active for a process

  • another alarm replaces the previous request
  • alarm(0) cancels it without starting another

52

install the desired SIGALRM disposition before starting the timer

  • otherwise its default action terminates the process

53

sleep has historically been allowed to use alarm and SIGALRM internally

  • mixing these mechanisms can therefore be implementation-dependent
  • implementations can instead use nanosleep or another waiting mechanism

54

interrupted sleep calls have different return conventions

  • sleep returns the number of seconds still to sleep
  • usleep and nanosleep can return -1 with errno = EINTR
  • nanosleep does not use a SIGALRM timer for its operation

55

the author prefers the more explicit sleep interfaces

  • nanosleep is useful when precise interruption handling is needed

56

signal-heavy designs are difficult to make correct

  • races between main code and handlers
  • coalescing of ordinary signals
  • effects on every relevant blocking call

57

example: parent must wait until a new child has finished initialization

  • child sends SIGUSR1 when ready
  • parent may handle other signals too
  • -> returning from pause alone does not prove the child is ready

58

first attempt:

  • set child_ready = 0 and install SIGUSR1 handler
  • handler sets child_ready = 1
  • fork; child initializes, then kill(getppid(), SIGUSR1)
  • parent repeats pause while child_ready is zero

59

lost-wakeup race in that attempt:

  • parent checks child_ready and sees zero
  • child sends SIGUSR1 before parent enters pause
  • handler sets child_ready to one
  • parent enters pause anyway and may wait indefinitely for another signal

60

solution: combine sigprocmask and sigsuspend

  • block SIGUSR1 before the critical check
  • sigsuspend atomically enables it while beginning to wait
  • an early signal remains pending until that wait

61

the author recommends keeping signal use simple

  • termination and fault handling
  • occasional requests to a long-running process, e.g. reload configuration
  • use a more suitable IPC mechanism for reliable exchanges of data

62

the remaining discussion explains waiting with sigsuspend

63

blocking a signal defers its delivery

  • pending signal can be delivered after it is unblocked
  • blocking is different from ignoring
  • SIGKILL and SIGSTOP cannot be blocked

64

sigprocmask(how, set, oldset) changes the blocked-signal set

  • sets have type sigset_t
  • SIG_BLOCK: add signals from set
  • SIG_UNBLOCK: remove signals from set
  • SIG_SETMASK: replace the entire blocked set
  • non-NULL oldset receives the previous mask

65

query the current mask without changing it:

  • pass NULL as set and an address as oldset
  • how is ignored

66

functions operating on sigset_t:

  • sigemptyset: remove all members
  • sigfillset: include all signals
  • sigaddset: add one signal
  • sigdelset: remove one signal
  • sigismember: 1 if present, 0 if absent, -1 on error
  • modifying functions return 0 on success, -1 on error
  • an invalid signal number can produce EINVAL

67

sigsuspend(const sigset_t *mask): temporarily replace the signal mask and wait

  • mask specifies signals blocked during the wait
  • old mask is restored before sigsuspend returns

68

sigsuspend waits for an unblocked signal with an effective action

  • ignored signals do not end the wait
  • a terminating signal ends the process
  • a caught signal runs its handler, then sigsuspend returns -1 / EINTR
  • this return convention is the expected successful wait outcome

69

a signal mask lists blocked signals, which can make this interface confusing

  • the important operation here is permitting the awaited signal to arrive

70

usual waiting pattern:

  • block the relevant signal outside the wait
  • temporarily unblock it inside sigsuspend
  • restore blocking when the handler and wait finish

71

correct child-readiness example:

  • construct mask_usr1 containing SIGUSR1 and mask_empty containing none
  • initialize child_ready, block SIGUSR1, install the handler, then fork
  • child initializes and sends SIGUSR1 to the parent
  • parent: while(!child_ready) sigsuspend(&mask_empty);
  • early notification stays pending until sigsuspend unblocks it
  • later notifications remain pending for a later wait
  • in a larger program, preserve unrelated entries in the original mask

72

the same reasoning explains the remaining bugs in the 25-message example

73

25th-signal race:

  • main checks n < 25
  • handler increments n to 25 before main calls pause
  • main still enters pause and needs an extra signal to wake it

74

signal-flood experiment: int_grill runs pressagain as a child

  • fork / exec the target, wait briefly, then repeatedly send SIGINT
  • use waitpid with WNOHANG to check whether it has finished
  • ./int_grill ./pressagain | wc -l can count far more than 25 messages
  • output through a pipe removes much of the terminal's display delay

75

why the count can become so large:

  • another SIGINT is often already pending when the handler returns
  • return passes through signal-restoration code using sigreturn
  • restoring the mask enables the pending signal
  • its handler can run immediately, before main rechecks the counter
  • -> main can be starved by consecutive handler invocations

76

the example eventually gets a gap between incoming signals

  • main finally checks the counter and exits
  • this does not make the earlier excess output correct

77

make the check-and-wait sequence correct:

  • block SIGINT before installing its handler
  • use sigsuspend to enable it only during each wait
  • on return the mask blocks SIGINT while main checks the counter

78

some programmers avoid pause entirely in favour of atomic wait interfaces

  • sigsuspend and pselect can combine mask changes with waiting
  • the author considers the appropriate choice dependent on the task

79

the author contrasts deliberate signal flooding with ordinary keyboard input

  • human typing and terminal processing are much slower
  • this makes the demonstrated failure hard to provoke interactively
  • low probability does not remove the underlying check-and-wait race

80

choose complexity with the real task in mind

  • understand the guarantees and limitations of the selected mechanism
Blocking a signal preserves an early notification until sigsuspend temporarily unblocks it.
Check and wait must be one atomic handoff. Open full size - Editable SVG
Examples & tests (5 files) - 5.3.14: Signals
Book exampleBook example: pressagain.cIn catalog
pressagain.cC / 23 lines
#include <signal.h>
#include <unistd.h>
#include <errno.h>

volatile static int n = 0;
const char message[] = "Press it again, I like it\n";

void handler(int s)
{
    int save_errno = errno;
    signal(SIGINT, handler);
    n++;
    write(1, message, sizeof(message)-1);
    errno = save_errno;
}

int main()
{
    signal(SIGINT, handler);
    while(n < 25)
        sleep(1);
    return 0;
}
Section test14 (05-03)In catalog
signal-00.cC / 23 lines
#include <signal.h>
#include <unistd.h>
#include <errno.h>

volatile static int n = 0;
const char message[] = "Press it again, I like it\n";

static void handler(int s)
{
    int save_errno = errno;
    signal(SIGINT, handler);
    n++;
    write(1, message, sizeof(message)-1);
    errno = save_errno;
}

int main()
{
    signal(SIGINT, handler);
    while (n < 25)
        sleep(1);
    return 0;
}
signal-01.cC / 41 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

volatile int child_ready;

void usr1hdl(int n)
{
    child_ready = 1;
}

int main()
{
    int pid;
    sigset_t mask_usr1, mask_empty;
    sigemptyset(&mask_usr1);
    sigaddset(&mask_usr1, SIGUSR1);
    sigemptyset(&mask_empty);

    printf("Prepare parent\n");

    child_ready = 0;
    sigprocmask(SIG_SETMASK, &mask_usr1, NULL);
    signal(SIGUSR1, usr1hdl);

    pid = fork();
    if (pid == 0) {
        printf("Prepare child\n");
        kill(getppid(), SIGUSR1);
        printf("Child is ready\n");
        exit(0);
    }

    while (!child_ready)
        sigsuspend(&mask_empty);

    printf("Now parent can work with child\n");

    return 0;
}
signal-02.cC / 77 lines
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

enum exit_codes {
    exit_arguments = 1,
    exit_process
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

int launch_process(char *const a[])
{
    int pid;

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        execvp(a[0], a);
        terminate_exec("execvp", exit_process);
    }

    return pid;
}

void iterate_process(int pid)
{
    int status, exit_status, sr, wr;
    struct timespec duration, rem;

    duration.tv_sec = 0;
    duration.tv_nsec = 1e8;

    sr = nanosleep(&duration, &rem);
    if (sr == -1)
        terminate("nanosleep", exit_process);

    do {
        kill(pid, SIGINT);
        wr = waitpid(-1, &status, WNOHANG);
    } while (wr == 0);

    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    }
}

int main(int argc, char **argv)
{
    int pid;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <command with parameters ...>\n", argv[0]);
        exit(1);
    }

    pid = launch_process(&argv[1]);
    iterate_process(pid);

    return 0;
}
signal-03.cC / 32 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

volatile static int n = 0;
const char message[] = "Press it again, I like it\n";

static void handler(int s)
{
    int save_errno = errno;
    signal(SIGINT, handler);
    n++;
    write(1, message, sizeof(message)-1);
    errno = save_errno;
}

int main()
{
    sigset_t mask_int, mask_empty;
    sigemptyset(&mask_int);
    sigaddset(&mask_int, SIGINT);
    sigemptyset(&mask_empty);

    sigprocmask(SIG_SETMASK, &mask_int, NULL);
    signal(SIGINT, handler);

    while (n < 25)
        sigsuspend(&mask_empty);
    return 0;
}

Pipes and FIFOs

A pipe is a kernel object for one-way byte transfer. It has a read end and a write end.

Unnamed pipe:

int pipe(int fd[2]);   /* fd[0] reads, fd[1] writes */

Because an unnamed pipe has no filesystem name, unrelated processes cannot attach to it later. The usual pattern is:

  1. parent creates the pipe
  2. parent forks children
  3. each child closes the pipe ends it does not need
  4. parent closes both pipe ends

Pipe behavior:

Situation Result
Read from empty pipe with writers open Reader blocks
Write to full pipe with readers open Writer blocks
All write descriptors closed Reader drains buffer, then read returns 0
All read descriptors closed Writer receives SIGPIPE; write fails if signal is ignored/caught

A two-process pipeline such as:

ls -lR | grep '^d'

is built by connecting one child's standard output to the pipe write end and the other child's standard input to the pipe read end:

int fd[2];

pipe(fd);

if (fork() == 0) {
    close(fd[0]);
    dup2(fd[1], 1);
    close(fd[1]);
    execlp("ls", "ls", "-lR", NULL);
    perror("ls");
    _exit(1);
}

if (fork() == 0) {
    close(fd[1]);
    dup2(fd[0], 0);
    close(fd[0]);
    execlp("grep", "grep", "^d", NULL);
    perror("grep");
    _exit(1);
}

close(fd[0]);
close(fd[1]);
wait(NULL);
wait(NULL);

A named pipe, or FIFO, is represented by a filesystem object and can be opened by unrelated processes:

int mkfifo(const char *name, int mode);

Opening a FIFO for reading or writing normally blocks until the opposite end is opened. O_NONBLOCK changes this behavior. The FIFO file remains after all descriptors are closed; the kernel pipe object is recreated when the FIFO is opened again.

A shell written as an etude connects the commands of a pipeline this way. In the child for command i, pipe i receives its output and pipe i-1 supplies its input; every unused end is closed:

static void process_pipes(pipe_t p, int i, int first, int last)
{
    if (i < last) {
        close(p[i].fd[0]);
        dup2(p[i].fd[1], 1);
        close(p[i].fd[1]);
    }
    if (i > first) {
        close(p[i-1].fd[1]);
        dup2(p[i-1].fd[0], 0);
        close(p[i-1].fd[0]);
    }
}
Detailed notes - 5.3.15: Pipes and FIFOs

1

pipe: kernel object for one-way data transfer

  • write end receives bytes
  • read end supplies those bytes
  • descriptors in different processes can refer to the same ends

2

two kinds of pipe:

  • named pipe / FIFO: filesystem name can be opened by processes
  • unnamed pipe: created with both ends already open, without a pathname
  • ordinary open cannot connect to an unnamed pipe by name

3

pipe(fd) creates an unnamed pipe

  • int fd[2];
  • fd[0]: read end; fd[1]: write end
  • return: 0 on success, -1 on error, e.g. descriptor/resource exhaustion
  • the book shares descriptors by creating the pipe before fork
    • -> children inherit references to the same pipe

4

connect two children through one pipe:

  • parent creates pipe, then forks both children
  • first child closes fd[0] and writes through fd[1]
  • second child closes fd[1] and reads through fd[0]
  • parent closes both of its descriptors
  • -> only the writer and reader keep the ends they actually use

5

reading while both ends still have open descriptors:

  • empty pipe -> read blocks until data arrives or all writers close
  • available bytes -> read returns data without waiting to fill the request
  • returned byte count may be smaller than the requested count

6

a pipe contains a finite kernel buffer

  • writes can initially succeed even if a reader is not actively reading
  • once space runs out, a blocking write waits for a reader to free space
  • capacity depends on implementation and configuration

7

when the last write descriptor closes:

  • reads can consume bytes already buffered
  • after the buffer empties, read returns 0: EOF
  • an unnamed pipe has no pathname through which to reopen that end

8

when the last read descriptor closes:

  • writing generates SIGPIPE
  • default action: terminate the writer
  • if SIGPIPE is caught or ignored, write can report -1 / EPIPE

9

pipelines connect concurrently running programs

  • first program's stdout -> second program's stdin
  • second program's stdout -> third program's stdin, and so on

10

an N-stage pipeline normally needs N - 1 pipes

  • connect descriptors 0 and 1 to the appropriate ends
  • close every unused pipe descriptor in every process
  • an accidental extra write descriptor prevents the reader from seeing EOF

11

an accidental extra read descriptor also matters

  • intended consumer exits, but the pipe still appears to have a reader
  • producer can fill the buffer and block instead of receiving SIGPIPE
  • tasks waiting for the producer can then remain blocked too

12

example: ls -lR | grep '^d'

  • create one pipe
  • first child:
    • close read end
    • dup2(fd[1], 1), then close the original fd[1]
    • execlp("ls", "ls", "-lR", NULL)
  • second child:
    • close write end
    • dup2(fd[0], 0), then close the original fd[0]
    • execlp("grep", "grep", "^d", NULL)
  • children report an exec failure and terminate
  • parent closes both pipe descriptors and waits for both children

13

FIFO: first in, first out

  • a named pipe lets unrelated processes find the same channel by pathname
  • bytes are read in the order in which they entered the stream
  • the unnamed-pipe examples rely on inherited descriptors

14

FIFO is a special filesystem object

  • processes can independently open it
  • closing every descriptor for one end does not remove its pathname
  • a process can later open that end again

15

mkfifo(name, permissions) creates the FIFO filesystem object

  • permissions are filtered by umask
  • return: 0 on success, -1 on error

16

opening a FIFO connects to the kernel channel

  • O_RDONLY: read end
  • O_WRONLY: write end
  • O_RDWR behaviour is not portable; Linux permits it
  • creating the pathname does not itself open a channel descriptor

17

kernel pipe state and filesystem FIFO have different lifetimes

  • last descriptor closes -> kernel channel state is released
  • FIFO pathname remains until explicitly removed
  • a later open can establish a new channel through the same name

18

ordinary FIFO open waits for the other end to be opened

O_NONBLOCK changes this:

  • read-only open succeeds even without a writer
  • write-only open with no reader fails: -1, errno = ENXIO

19

FIFO end closure follows pipe rules:

  • no writers and no buffered data -> read returns 0
  • no readers -> write generates SIGPIPE

but new descriptors can later appear through the pathname

  • a new writer can make data available after a reader has observed EOF
  • without a writer, reads continue returning 0
  • a later reader can make writing possible again if the writer survived SIGPIPE
A reader first drains buffered bytes; it sees EOF only after the last write end closes.
Pipe EOF depends on every writer reference. Open full size - Editable SVG
Tests & experiments (8 files) - 5.3.15: Pipes and FIFOs
Section test15 (05-03)In catalog
fifo_r.cC / 39 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

enum { buf_size = 4096 };

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main()
{
    int fd, rc, r;
    char buf[buf_size];

    r = mkfifo("fifo.t", 0666);
    if (r == -1)
        terminate("mkfifo", exit_failure);

    fd = open("fifo.t", O_RDONLY);
    if (fd == -1)
        terminate("fifo.t", exit_file);
    while ((rc = read(fd, buf, buf_size)) != 0)
        write(1, buf, rc);
    return 0;
}
fifo_w.cC / 33 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main()
{
    int fd;

    fd = open("fifo.t", O_WRONLY);
    if (fd == -1)
        terminate("fifo.t", exit_file);

    write(fd, "one", 3);

    return 0;
}
pipe-00.cC / 58 lines
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
    int p1[2], p2[2];

    pipe(p1); // yes -> cat
    pipe(p2); // cat -> head

    if (fork() == 0) {
        // yes
        dup2(p1[1], 1);

        close(p1[0]);
        close(p1[1]);

        // BUG: this child still has p2[0] open
        // BUG: also p2[1] open
        execlp("yes", "yes", NULL);
        exit(1);
    }

    if (fork() == 0) {
        // cat
        dup2(p1[0], 0);
        dup2(p2[1], 1);

        close(p1[0]);
        close(p1[1]);
        close(p2[0]);
        close(p2[1]);

        execlp("cat", "cat", NULL);
        exit(1);
    }

    if (fork() == 0) {
        // head -n 1
        dup2(p2[0], 0);

        close(p1[0]);
        close(p1[1]);
        close(p2[0]);
        close(p2[1]);

        execlp("head", "head", "-n", "10", NULL);
        exit(1);
    }

    // parent closes everything correctly
    close(p1[0]);
    close(p1[1]);
    close(p2[0]);
    close(p2[1]);

    pause();
}
pipe-01.cC / 52 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

enum { buf_size = 4096 };

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

static const char msg[] = "Hello there\n";

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main()
{
    int fd[2];
    int p1, p2, rc;
    char buf[buf_size];

    pipe(fd);

    p1 = fork();
    if (p1 == -1)
        terminate("fork", exit_process);
    if (p1 == 0) {
        close(fd[0]);
        write(fd[1], msg, sizeof(msg)-1);
        exit(0);
    }

    p2 = fork();
    if (p2 == -1)
        terminate("fork", exit_process);
    if (p2 == 0) {
        close(fd[1]);
        rc = read(fd[0], buf, buf_size);
        exit(0);
    }
    close(fd[0]);
    close(fd[1]);
    return 0;
}
pipe-02.cC / 77 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

static void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void wait_process()
{
    int wr, status, exit_status;

    wr = wait(&status);
    if (wr == -1)
        terminate("wait", 1);
    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    } else
        printf("killed with signal: %d\n", WTERMSIG(status));
}

int main()
{
    int fd[2], pid;

    pipe(fd);

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd[0]);
        dup2(fd[1], 1);
        close(fd[1]);
        execlp("ls", "ls", "-lR", NULL);
        terminate_exec("ls", exit_process);
    }

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd[1]);
        dup2(fd[0], 0);
        close(fd[0]);
        execlp("grep", "grep", "^d", NULL);
        terminate_exec("grep", exit_process);
    }

    close(fd[0]);
    close(fd[1]);
    wait_process();
    wait_process();

    return 0;
}
pipe-03.cC / 105 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

static void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void wait_process()
{
    int wr, status, exit_status;

    wr = wait(&status);
    if (wr == -1)
        terminate("wait", 1);
    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    } else
        printf("killed with signal: %d\n", WTERMSIG(status));
}

int main()
{
    int fd1[2], fd2[2], pid;

    pipe(fd1);
    pipe(fd2);

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd1[0]);
        dup2(fd1[1], 1);
        close(fd1[1]);

        close(fd2[0]);
        close(fd2[1]);

        execlp("ls", "ls", "-lR", NULL);
        terminate_exec("ls", exit_process);
    }

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd1[1]);
        dup2(fd1[0], 0);
        close(fd1[0]);

        close(fd2[0]);
        dup2(fd2[1], 1);
        close(fd2[1]);

        execlp("grep", "grep", "^d", NULL);
        terminate_exec("grep", exit_process);
    }

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd1[0]);
        close(fd1[1]);

        close(fd2[1]);
        dup2(fd2[0], 0);
        close(fd2[0]);

        execlp("wc", "wc", "-l", NULL);
        terminate_exec("grep", exit_process);
    }

    close(fd1[0]);
    close(fd1[1]);
    close(fd2[0]);
    close(fd2[1]);
    wait_process();
    wait_process();
    wait_process();

    return 0;
}
pipe-04.cC / 125 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

typedef int (*fds_t)[2];

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

static void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void wait_process()
{
    int wr, status, exit_status;

    wr = wait(&status);
    if (wr == -1)
        terminate("wait", 1);
    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    } else
        printf("killed with signal: %d\n", WTERMSIG(status));
}

int main()
{
    int fd1[2], fd2[2], fd3[2], pid;

    pipe(fd1);

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd1[0]);
        dup2(fd1[1], 1);
        close(fd1[1]);

        execlp("ls", "ls", "-lR", NULL);
        terminate_exec("ls", exit_process);
    }

    pipe(fd2);

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd1[1]);
        dup2(fd1[0], 0);
        close(fd1[0]);

        close(fd2[0]);
        dup2(fd2[1], 1);
        close(fd2[1]);

        execlp("grep", "grep", "^d", NULL);
        terminate_exec("grep", exit_process);
    }

    pipe(fd3);
    close(fd1[0]);
    close(fd1[1]);

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        close(fd2[1]);
        dup2(fd2[0], 0);
        close(fd2[0]);

        close(fd3[0]);
        dup2(fd3[1], 1);
        close(fd3[1]);

        execlp("cat", "cat", NULL);
        terminate_exec("cat", exit_process);
    }

    close(fd2[0]);
    close(fd2[1]);

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {

        close(fd3[1]);
        dup2(fd3[0], 0);
        close(fd3[0]);

        execlp("wc", "wc", "-l", NULL);
        terminate_exec("grep", exit_process);
    }

    close(fd3[0]);
    close(fd3[1]);
    wait_process();
    wait_process();
    wait_process();
    wait_process();

    return 0;
}
pipe-05.cC / 108 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

enum { processes_limit = 64, cmds_limit = 64 };

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

typedef int (*fds_t)[2];

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

static void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void wait_process()
{
    int wr, status, exit_status;

    wr = wait(&status);
    if (wr == -1)
        terminate("wait", 1);
    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    } else
        printf("killed with signal: %d\n", WTERMSIG(status));
}

void close_in_out(fds_t fds, int i)
{
    close(fds[i][0]);
    close(fds[i][1]);
}

void launch_process_pipe(char *const cmd[], fds_t fds, int i, int n)
{
    int pid;

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {

        if (i > 0) {
            close(fds[i-1][1]);
            dup2(fds[i-1][0], 0);
            close(fds[i-1][0]);
        }

        if (i < n - 1) {
            close(fds[i][0]);
            dup2(fds[i][1], 1);
            close(fds[i][1]);
        }

        execvp(cmd[0], cmd);
        terminate_exec(cmd[0], exit_process);
    }
}

int main()
{
    int i, n, fds[processes_limit][2];
    char *cmds[cmds_limit];

    n = 4;

    pipe(fds[0]);
    cmds[0] = "ls"; cmds[1] = "-lR"; cmds[2] = NULL;
    launch_process_pipe(cmds, fds, 0, n);

    pipe(fds[1]);
    cmds[0] = "grep"; cmds[1] = "^d"; cmds[2] = NULL;
    launch_process_pipe(cmds, fds, 1, n);
    close_in_out(fds, 0);

    pipe(fds[2]);
    cmds[0] = "cat"; cmds[1] = NULL;
    launch_process_pipe(cmds, fds, 2, n);
    close_in_out(fds, 1);

    cmds[0] = "wc"; cmds[1] = "-l"; cmds[2] = NULL;
    launch_process_pipe(cmds, fds, 3, n);
    close_in_out(fds, 2);

    for (i = 0; i < n; i++)
        wait_process();

    return 0;
}

Tracing

Tracing lets one process, usually a debugger, control another process. The tracer can stop the target, inspect or modify memory and registers, single-step, continue, or stop at system calls.

Unix exposes this through ptrace:

int ptrace(int request, int pid, void *addr, void *data);

Two common modes:

Mode Idea
PTRACE_TRACEME Child asks to be traced, then usually calls exec
PTRACE_ATTACH Tracer attaches to an already running process

ptrace matters for security reasoning. A process that can trace another process with the same credentials can usually control it, even if filesystem access was restricted by mechanisms such as chroot.

PTRACE_ATTACH makes a running process a tracee. The tracer lets it continue, stops it again with SIGSTOP, and detaches:

void attach_process(int pid)
{
    int ret, status;

    ret = ptrace(PTRACE_ATTACH, pid, 0, 0);
    if (ret == -1)
        terminate("PTRACE_ATTACH", exit_process);

    ret = waitpid(pid, &status, 0);
    if (ret == -1)
        terminate("waitpid", exit_process);

    if (!WIFSTOPPED(status)) {
        fprintf(stderr, "process did not stop\n");
        exit(exit_process);
    }

    printf("attached to %d\n", pid);
}
Show the complete program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <signal.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void attach_process(int pid)
{
    int ret, status;

    ret = ptrace(PTRACE_ATTACH, pid, 0, 0);
    if (ret == -1)
        terminate("PTRACE_ATTACH", exit_process);

    ret = waitpid(pid, &status, 0);
    if (ret == -1)
        terminate("waitpid", exit_process);

    if (!WIFSTOPPED(status)) {
        fprintf(stderr, "process did not stop\n");
        exit(exit_process);
    }

    printf("attached to %d\n", pid);
}

void debug(int pid)
{
    int ret, status;

    ret = ptrace(PTRACE_CONT, pid, 0, 0);
    if (ret == -1)
        terminate("PTRACE_CONT", exit_process);

    sleep(3);

    ret = kill(pid, SIGSTOP);
    if (ret == -1)
        terminate("kill SIGSTOP", exit_process);

    ret = waitpid(pid, &status, 0);
    if (ret == -1)
        terminate("waitpid", exit_process);

    if (WIFSTOPPED(status))
        printf("stopped again\n");
}

void detach_process(int pid)
{
    int ret;

    ret = ptrace(PTRACE_DETACH, pid, 0, 0);
    if (ret == -1)
        terminate("PTRACE_DETACH", exit_process);

    printf("detached\n");
}

int main(int argc, char **argv)
{
    int pid;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <pid>\n", argv[0]);
        return exit_arguments;
    }

    pid = atoi(argv[1]);

    attach_process(pid);
    debug(pid);
    detach_process(pid);

    return exit_success;
}
$ sleep 60 &
[1] 4711
$ ./attach 4711
attached to 4711
stopped again
detached
Detailed notes - 5.3.16: Tracing

1

tracing allows one process, usually a debugger, to control another

  • stop or resume it
  • inspect / modify memory
  • execute individual instructions
  • use breakpoints or stop at system calls

2

ptrace provides tracing operations

  • arguments identify the request, target process, address, and data
  • interpretation of address and data depends on the request
  • exact declaration and available requests are system-specific

3

trace a newly started program:

  • debugger forks
  • child requests PTRACE_TRACEME, then execs the target program
  • tracing stop after exec notifies the debugger with SIGCHLD
  • debugger uses wait-family calls to observe the stop
  • PTRACE_SINGLESTEP: execute one instruction
  • PTRACE_CONT: continue execution
  • PTRACE_GETREGS: obtain register contents on supporting systems

4

attach to an existing process with PTRACE_ATTACH

  • debugger assumes tracing-related responsibilities of a parent
  • receives tracing notifications and observes stops through wait
  • target's getppid still identifies its actual parent

5

tracing is a powerful security capability

  • where permitted, it allows inspection and alteration of another process
  • same-user identity alone does not bypass every system's ptrace restrictions
  • chroot changes filesystem lookup; it does not by itself isolate processes
  • tracing a process outside a chroot can defeat the intended confinement
  • actual access depends on credentials, capabilities, and system policy
Tests & experiments (4 files) - 5.3.16: Tracing
Section test16 (05-03)In catalog
trace-00.cC / 141 lines
#include <stdio.h>
#include <stdlib.h>
#include <sys/user.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ptrace.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void wait_process(pipe_t p, int n)
{
    int i, wr, status, exit_status;

    do {
        wr = wait(&status);
        if (wr == -1)
            fprintf(stderr, "Error: child process failed\n");
    } while ();

    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    } else
        printf("killed with signal: %d\n", WTERMSIG(status));

    set_sigactions(SIGCHLD, handler_sigchld);
}

void wait_process(int pid)
{
    int wr, status;

    do {
        wr = wait(&status);
        if (wr == -1)
            terminate("wait", 1);
    } while (wr != pid);

    if (WIFEXITED(status))
        printf("exited with code: %d\n", WEXITSTATUS(status));
    else
        printf("stopped with signal: %d\n", WSTOPSIG(status));
}

int launch_process(char *const cmds[])
{
    int pid;

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_failure);
    if (pid == 0) {
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        execvp(cmds[0], cmds);
        terminate_exec("execvp", exit_process);
    }

    return pid;
}

int wait_process(int pid)
{
    int wr, status;

    r = waitpid(pid, &status, 0);
    if (r == -1)
        terminate("waitpid", 1);

    if (WIFEXITED(status) || !WIFSTOPPED(status))
        return 1;

    return 0;
}

void debug(int pid)
{
    unsigned long i_addr;
    long word;
    int i_value;

    int r, to_break;
    while (1) {
        r = ptrace(PTRACE_SINGLESTEP, pid, NULL, NULL);
        if (r == -1)
            terminate("ptrace singlestep", 1);

        to_break = wait_process(pid);
        if (to_break)
            break;

        r = ptrace(PTRACE_GETREGS, pid, NULL, &regs);
        if (r == -1)
            terminate("ptrace getregs", 1);

        i_addr = regs.rbp - 4;
        word = ptrace(PTRACE_PEEKDATA, pid, (void *)i_addr, NULL);
        i_value = *(int *)&word;

        printf("RIP=0x%llx i=%d\n", (unsigned long long)regs.rip, i_value);
    }
}

int main(int argc, char **argv)
{
    int pid, status;
    struct user_regs_struct regs;

    if (argc < 2) {
        fprintf(stderr,
                "Usage: %s <commands with parameters ...> \n", argv[0]);
        exit(exit_arguments);
    }

    pid = launch_process(argv+1);
    waitpid(pid, &status, 0);
    debug(pid);

    return 0;
}
trace-01.cC / 96 lines
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/ptrace.h>

#define I_FROM 0x401135
#define I_TO   0x401160

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

int launch_process(char *const cmds[])
{
    int pid;

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        execvp(cmds[0], cmds);
        terminate_exec("execvp", exit_process);
    }

    return pid;
}

void print_i(int pid)
{
    struct user_regs_struct r;
    long word;
    int res;

    res = ptrace(PTRACE_GETREGS, pid, 0, &r);
    if (res == -1)
        terminate("GETREGS", exit_process);

    if (r.rip < I_FROM || r.rip > I_TO)
        return;

    errno = 0;
    word = ptrace(PTRACE_PEEKDATA, pid, (void *)(r.rbp - 4), 0);
    if (word == -1)
        terminate("PEEKDATA", exit_process);

    printf("rip=%llx i=%d\n", r.rip, (int)word);
}

int main(int argc, char **argv)
{
    int pid, st;

    if (argc < 2) {
        fprintf(stderr, "usage: %s program [args]\n", argv[0]);
        return 1;
    }

    pid = launch_process(argv+1);
    waitpid(pid, &st, 0);

    while (1) {
        if (ptrace(PTRACE_SINGLESTEP, pid, 0, 0) == -1)
            terminate("SINGLESTEP", exit_process);

        waitpid(pid, &st, 0);

        if (WIFEXITED(st))
            break;

        print_i(pid);
    }

    return 0;
}
trace-02.cC / 87 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/syscall.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

int launch_process(char *const cmds[])
{
    int pid;

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_process);
    if (pid == 0) {
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        execvp(cmds[0], cmds);
        terminate_exec("execvp", exit_process);
    }

    return pid;
}

void debug(int pid)
{
    int entering, res, status;
    struct user_regs_struct r;

    entering = 1;
    while (1) {
        res = ptrace(PTRACE_SINGLESTEP, pid, 0, 0);
        if (res == -1)
            terminate("PTRACE_SINGLESTEP", exit_process);

        waitpid(pid, &status, 0);

        if (WIFEXITED(status))
            break;

        res = ptrace(PTRACE_GETREGS, pid, 0, &r);
        if (res == -1)
            terminate("PTRACE_GETREGS", exit_process);

        if (entering && r.orig_rax == SYS_write)
            printf("write(fd=%lld, buf=0x%llx, count=%lld)\n", r.rdi, r.rsi, r.rdx);
        entering = !entering;
    }
}

int main(int argc, char **argv)
{
    int status, pid;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s program <args...>\n", argv[0]);
        return 1;
    }

    pid = launch_process(argv+1);
    waitpid(pid, &status, 0);
    debug(pid);

    return 0;
}
trace-03.cC / 92 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <signal.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void attach_process(int pid)
{
    int ret, status;

    ret = ptrace(PTRACE_ATTACH, pid, 0, 0);
    if (ret == -1)
        terminate("PTRACE_ATTACH", exit_process);

    ret = waitpid(pid, &status, 0);
    if (ret == -1)
        terminate("waitpid", exit_process);

    if (!WIFSTOPPED(status)) {
        fprintf(stderr, "process did not stop\n");
        exit(exit_process);
    }

    printf("attached to %d\n", pid);
}

void debug(int pid)
{
    int ret, status;

    ret = ptrace(PTRACE_CONT, pid, 0, 0);
    if (ret == -1)
        terminate("PTRACE_CONT", exit_process);

    sleep(3);

    ret = kill(pid, SIGSTOP);
    if (ret == -1)
        terminate("kill SIGSTOP", exit_process);

    ret = waitpid(pid, &status, 0);
    if (ret == -1)
        terminate("waitpid", exit_process);

    if (WIFSTOPPED(status))
        printf("stopped again\n");
}

void detach_process(int pid)
{
    int ret;

    ret = ptrace(PTRACE_DETACH, pid, 0, 0);
    if (ret == -1)
        terminate("PTRACE_DETACH", exit_process);

    printf("detached\n");
}

int main(int argc, char **argv)
{
    int pid;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <pid>\n", argv[0]);
        return exit_arguments;
    }

    pid = atoi(argv[1]);

    attach_process(pid);
    debug(pid);
    detach_process(pid);

    return exit_success;
}

Terminals and Sessions

A Unix terminal is not just a screen and keyboard. For user programs it is a kernel-managed communication endpoint with special rules for interactive use: line editing, echoing typed characters, converting control keys into signals, and tracking which process group is currently allowed to read from it.

Programs often behave differently when their input or output is a terminal. For example, ls may use columns and color when writing to a terminal, but produce plain one-name-per-line output when redirected to a pipe or file.

Check whether a descriptor is attached to a terminal:

int isatty(int fd);

isatty returns 1 for a terminal descriptor and 0 otherwise.

Section test (1 file) - 5.4: Terminals and sessions
Section test04 (05)In catalog
dev.cC / 55 lines
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

enum { buf_size = 4096 };

static void die(const char *msg, int num)
{
    perror(msg);
    exit(num);
}

int main(int argc, char **argv)
{
    int fd, code, count;
    const char *dev, *msg;
    char buf[buf_size];
    char read_write;

    if (argc != 4) {
        fprintf(stderr, "Usage: %s </dev/pts/x> <r/w> <message>\n", argv[0]);
        return 2;
    }
    dev = argv[1];
    read_write = argv[2][0];
    msg = argv[3];

    switch (read_write) {
        case 'r': fd = open(dev, O_RDONLY); break;
        case 'w': fd = open(dev, O_WRONLY, 0666); break;
    }
    if (fd == -1)
        die("open", 1);

    switch (read_write) {
        case 'r':
            count = read(fd, buf, buf_size);
            write(1, buf, count);
            break;
        case 'w':
            code = write(fd, msg, strlen(msg));
            if (code == -1)
                die("write", 2);
            break;
    }

    code = close(fd);
    if (code)
        die("open", 3);

    return 0;
}

Terminal Driver and Line Discipline

Between a terminal-like device and user processes sits the terminal driver. Its line discipline interprets selected input bytes before a program sees them.

Examples:

Input Usual terminal effect
Ctrl-C Send SIGINT to the foreground process group
Ctrl-\ Send SIGQUIT to the foreground process group
Ctrl-Z Send SIGTSTP to stop the foreground process group
Ctrl-D Make the next read report end-of-file when appropriate
Backspace Delete the previous input character in canonical mode
Ctrl-U Clear the current input line in canonical mode
Ctrl-W Delete the previous word when extended line editing is enabled
Ctrl-S/Ctrl-Q Stop and resume terminal output when software flow control is enabled

The terminal device itself does not understand Unix signals. For instance, Ctrl-C normally produces byte value 3; the line discipline receives that byte and decides to send SIGINT instead of passing the byte to the active program.

Common terminal forms:

Form What provides the terminal behavior
Hardware terminal Separate physical terminal connected by a serial line
Virtual console Kernel console emulator using local keyboard and display hardware
Terminal emulator User program such as xterm, backed by a pseudoterminal
Remote login Server program such as sshd or telnetd, backed by a pseudoterminal

isatty reports whether a descriptor refers to a terminal:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    int fd;
    fd = open(argv[1], O_RDONLY);
    printf("%d %d %d\n", isatty(0), isatty(1), isatty(fd));
    return 0;
}
$ ./isatty /dev/tty
1 1 1
$ ./isatty /dev/tty | cat
1 0 1
$ ./isatty ten.txt < /dev/null
0 1 0

It works by asking the terminal driver for its settings; only a terminal can answer TCGETS:

#include <sys/ioctl.h>
#include <termios.h>

int is_terminal(int fd)
{
    struct termios t;

    if (ioctl(fd, TCGETS, &t) == 0)
        return 1;

    return 0;
}
Detailed notes - 5.4.1: Terminal driver and line discipline

1

terminal originally combined keyboard, screen, and a communication

line:

  • keyboard input was sent along the line
  • received text was displayed on the screen
  • one computer could serve many terminals and users
  • -> terminal remains central to Unix process management

2

terminal streams usually imply a human user:

  • C library buffering differs for terminals and other streams
  • ls may use columns and colors on a terminal
  • redirected output normally lists one name per line
  • ls | cat demonstrates this: ls writes to a pipe, even though cat eventually displays that text on the terminal

3

isatty(fd):

  • returns 1 if fd refers to a terminal, otherwise 0
  • library function implemented through a terminal-specific ioctl
  • tests the kind of stream, not its descriptor number

4

terminal behavior can be emulated in software:

  • hardware terminal and physical line are no longer necessary
  • Linux / FreeBSD virtual consoles use the local keyboard and display
  • switch consoles with Alt-F1, Alt-F2, ... in the setup described
  • servers can be administered remotely and use consoles for local work

5

graphical terminal emulators: xterm, rxvt, konsole, ...

  • ordinary user processes implement terminal behavior
  • kernel implements virtual consoles instead
  • virtual consoles still exist while X Window runs
  • console-switching keys depend on the system's configuration

6

physical serial consoles are useful on machines without a local

display:

  • server provides an RS-232 / COM console port
  • laptop plus terminal program can act as the terminal
  • USB-to-serial adapter replaces a missing built-in COM port
  • minicom and similar programs communicate over this connection
  • often used for initial setup before network access is available

7

serial communication:

  • minimal connection: transmit, receive, common ground
  • bits are sent sequentially, grouped with start / stop bits
  • optional parity helps detect transmission errors
  • modems convert digital data for transmission over telephone lines
  • dial-up was widespread before faster access became affordable

8

terminal traffic needs much less bandwidth than images or video:

  • traditional COM-port speeds are sufficient for typed commands
  • output includes generated text and escape sequences
  • even relatively slow serial connections can support text interaction

9

remote-access services such as sshd also provide a terminal interface

  • a pseudoterminal connects remote input/output to local processes

10

line discipline sits between terminal input/output and user programs

  • terminal transmits characters; it does not know Unix signals
  • Ctrl-A -> code 1, Ctrl-B -> 2, Ctrl-C -> 3, ... Ctrl-Z -> 26
  • Ctrl-[ -> 27, Ctrl-\ -> 28, Ctrl-] -> 29
  • driver recognizes configured control characters
  • -> code 3 normally generates SIGINT instead of reaching the program

11

terminal-generated signals target the foreground process group

  • this belongs to the session associated with the terminal

12

canonical line editing is also handled by the line discipline:

  • Backspace: erase the previous character
  • Ctrl-W: erase the previous word
  • Ctrl-R: redisplay the current input line
  • Ctrl-U: erase the entire current line
  • active application does not have to implement these operations

13

programs can change or disable special-character handling:

  • Ctrl-C can become ordinary input instead of generating SIGINT
  • applications can implement their own editing
  • bash / gdb provide history, arrow keys, and completion
  • GNU Readline supplies these features beyond basic line discipline

14

xterm receives keyboard events from X Window:

  • pressing Ctrl-C in its window does not signal xterm itself
  • xterm sends byte 3 to the pseudoterminal
  • kernel line discipline generates SIGINT for the foreground job

15

Ctrl-D does not close the terminal connection:

  • xterm sends byte 4
  • canonical input uses it to deliver pending input without a newline
  • on an empty line, read returns 0 -> application sees EOF
  • cat can finish while the shell and terminal session remain usable
Tests & experiments (2 files) - 5.4.1: Terminal driver and line discipline
Section test01 (05-04)In catalog
terminal-00.cC / 11 lines
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char **argv)
{
    int fd;
    fd = open(argv[1], O_RDONLY);
    printf("%d %d %d\n", isatty(0), isatty(1), isatty(fd));
    return 0;
}
terminal-01.cC / 24 lines
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <termios.h>

int is_terminal(int fd)
{
    struct termios t;

    if (ioctl(fd, TCGETS, &t) == 0)
        return 1;

    return 0;
}


int main(int argc, char **argv)
{
    int fd;
    fd = open(argv[1], O_RDONLY);
    printf("%d %d %d\n", is_terminal(0), is_terminal(1), is_terminal(fd));
    return 0;
}

Sessions, Process Groups, and Job Control

A session is a set of processes with the same session id, sid. A session may have one controlling terminal, and a terminal may control at most one session.

Inside a session, processes are divided into process groups with process group ids, pgid. Shells use this for job control: each command or pipeline is normally placed in its own process group.

Object Identifier Main purpose
Session sid Collect processes belonging to one login or terminal window
Process group pgid Collect processes that form one job
Foreground group pgid The group currently allowed to read from the terminal
Background group pgid A group in the same session that is not foreground

Terminal-generated signals go to the foreground process group, not to every process in the session. This is why Ctrl-C interrupts the command currently running in the shell but does not normally kill background jobs.

Important job-control behavior:

Event Result
Foreground group reads from terminal Read proceeds normally
Background group tries to read from terminal Kernel sends SIGTTIN to that group
Background output with TOSTOP enabled Kernel sends SIGTTOU to that group
Terminal session disappears Foreground group receives SIGHUP; shells may relay it
Stopped job is continued SIGCONT resumes the stopped processes

Inspect session and group ids:

int getsid(int pid);
int getpgid(int pid);

pid == 0 means the calling process.

Create a new session:

int setsid(void);

setsid creates both a new session and a new process group. The caller becomes the leader of both, and the new sid and pgid are equal to the caller's pid. The call fails if the process is already a process-group leader, so code that must create a session often forks first and lets the parent exit:

int pid;

pid = fork();
if (pid > 0) {
    exit(0);
}

if (setsid() == -1) {
    perror("setsid");
    exit(1);
}

Change a process group:

int setpgid(int pid, int pgid);

A process may move itself or a direct child that has not yet called exec. A new group is created by using pgid == pid.

Set the foreground process group of a controlling terminal:

int tcsetpgrp(int fd, int pgrp);

The descriptor must refer to the controlling terminal. When standard input, output, and error may be redirected, open /dev/tty: it names the controlling terminal of the calling process, if there is one.

int ttyfd;

ttyfd = open("/dev/tty", O_RDWR);
if (ttyfd == -1) {
    /* no controlling terminal */
}

When a session leader opens a terminal that is not already a controlling terminal for another session, it may accidentally acquire it as its own controlling terminal. Use O_NOCTTY when opening terminal device files if that must not happen.

Detailed notes - 5.4.2: Sessions and process groups

1

session = set of processes sharing one sid (session identifier)

  • normally associated with work through one terminal
  • session has at most one controlling terminal, possibly none
  • terminal controls at most one session
  • login and starting a terminal emulator usually create new sessions

2

a session contains one or more process groups:

  • a group cannot span different sessions
  • terminal records one foreground group; others are background groups
  • switching the foreground group makes the previous one background
  • without a controlling terminal, foreground has no practical meaning

3

process group collects processes working on one job:

  • interactive shell normally creates a group for each command
  • all stages of a pipeline belong to the same group
  • pgid = process group identifier

4

fork preserves sid and pgid

process can:

  • create a new session and its initial group
    • becomes leader of both, with sid = pgid = pid
  • create a group within its session
  • join another group within the same session

5

leadership restricts creating sessions and groups:

  • setsid fails for a process group leader
  • a session leader is also leader of its initial group
  • a new group/session would need the caller's pid as its identifier
  • fork gives a child a fresh pid so it can create a session

6

groups determine which processes terminal actions affect:

  • Ctrl-C -> SIGINT to foreground group
  • background read -> SIGTTIN, normally stopping that group
  • background output can optionally be restricted too
  • terminal disconnection can cause SIGHUP
  • shell may propagate the hangup to its jobs
  • exact behavior on ordinary shell exit depends on shell settings

7

getsid(pid) and getpgid(pid) return session / group identifiers

  • pid = 0 queries the calling process
  • leader's pid provides the identifier of the session / group

8

setsid() creates a session

  • fails if caller is already a process group leader
  • usual preparation: fork, let parent exit, call setsid in child
  • fork failure must be handled before continuing

9

a successful setsid creates both a new session and its initial group

  • caller is initially the only member of both
  • sid and pgid both equal caller's pid

10

setsid detaches the process from its controlling terminal

  • existing terminal descriptors can remain open
  • a session leader may acquire a free terminal by opening it
  • O_NOCTTY prevents open from acquiring a controlling terminal
  • useful when a session leader opens arbitrary files

11

setpgid(pid, pgid) changes group membership:

  • caller can move itself or an immediate child that has not executed exec
  • destination group must be in the same session
  • pgid = pid creates a group led by that process

12

tcsetpgrp(fd, pgrp) assigns a terminal's foreground group

  • fd must refer to the controlling terminal
  • implemented through ioctl on that terminal
  • terminal driver needs the group to direct signals and control access

13

standard descriptors are not reliable handles for the controlling

terminal:

  • any of 0, 1, 2 may have been redirected
  • isatty proves only that a descriptor is a terminal
  • it does not prove that this is the caller's controlling terminal

14

/dev/tty refers to the caller's controlling terminal

  • open it to obtain a suitable descriptor for tcsetpgrp
  • opening fails if the process has no controlling terminal

15

background caller of tcsetpgrp may trigger SIGTTOU for its group

  • caller can block or ignore SIGTTOU while changing foreground groups
  • only the calling process needs to do this
A session contains groups; a foreground pipeline is one job even when it has several processes.
A terminal targets its foreground process group. Open full size - Editable SVG
Tests & experiments (7 files) - 5.4.2: Sessions and process groups
Section test02 (05-04)In catalog
terminal-00.cC / 16 lines
#include <stdio.h>
#include <unistd.h>

int main()
{
    int pid, sid, pgid;

    pid = getpid();
    sid = getsid(pid);
    pgid = getpgid(pid);
    printf("Process id: %d\n", pid);
    printf("Session id: %d\n", sid);
    printf("Process group id: %d\n", pgid);

    return 0;
}
terminal-01.cC / 29 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int pid, sid, pgid;

    pid = getpid();
    sid = getsid(pid);
    pgid = getpgid(pid);
    printf("Process id: %d\n", pid);
    printf("Session id: %d\n", sid);
    printf("Process group id: %d\n", pgid);

    pid = fork();
    if (pid > 0)
        exit(0);
    setsid();

    pid = getpid();
    sid = getsid(pid);
    pgid = getpgid(pid);
    printf("Process id: %d\n", pid);
    printf("Session id: %d\n", sid);
    printf("Process group id: %d\n", pgid);

    return 0;
}
terminal-02.cC / 30 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int pid, sid, pgid;

    pid = getpid();
    sid = getsid(pid);
    pgid = getpgid(pid);
    printf("Process id: %d\n", pid);
    printf("Session id: %d\n", sid);
    printf("Process group id: %d\n", pgid);

    pid = fork();
    if (pid == 0) {
        pid = getpid();
        sid = getsid(pid);
        pgid = getpgid(pid);
        printf("Process id: %d\n", pid);
        printf("Session id: %d\n", sid);
        printf("Process group id: %d\n", pgid);
        exit(0);
    }
    setpgid(pid, pid);

    return 0;
}

terminal-03.cC / 31 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int pid, sid, pgid;

    pid = getpid();
    sid = getsid(pid);
    pgid = getpgid(pid);
    printf("Process id: %d\n", pid);
    printf("Session id: %d\n", sid);
    printf("Process group id: %d\n", pgid);

    pid = fork();
    if (pid == 0) {
        pid = getpid();
        setpgid(pid, pid);
        sid = getsid(pid);
        pgid = getpgid(pid);
        printf("Process id: %d\n", pid);
        printf("Session id: %d\n", sid);
        printf("Process group id: %d\n", pgid);
        exit(0);
    }

    return 0;
}


terminal-04.cC / 8 lines
#include <unistd.h>

int main()
{
    while (1)
        sleep(1);
    return 0;
}
terminal-05.cC / 21 lines
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(void) {
    int fd, pgid, r;

    fd = STDIN_FILENO;
    pgid = getpgrp();

    r = tcsetpgrp(fd, pgid);
    if (r == -1) {
        fprintf(stderr, "tcsetpgrp failed: %s\n", strerror(errno));
        return 1;
    }

    printf("fd is %d\n", fd);
    printf("foreground process group is now %d\n", pgid);
    return 0;
}
terminal-06.cC / 22 lines
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(void) {
    int fd, r;

    fd = open("/dev/tty", O_RDWR);
    if (fd != 0) {

        r = tcsetpgrp(fd, getpgrp());
        if (r == -1) {
            fprintf(stderr, "tcsetpgrp failed: %s\n", strerror(errno));
            return 1;
        }
    }

    printf("foreground process group is now %d\n", getpgrp());
    return 0;
}

Terminal Modes with termios

The termios interface controls terminal line discipline. It is layered over terminal ioctl operations but is easier to use directly.

int tcgetattr(int fd, struct termios *tp);
int tcsetattr(int fd, int options, const struct termios *tp);

tcgetattr reads the current settings. tcsetattr installs new settings:

Option When settings take effect
TCSANOW Immediately
TCSADRAIN After pending output has been transmitted
TCSAFLUSH After pending output has been transmitted; unread input is discarded

Main fields of struct termios:

Field Meaning
c_iflag Input processing flags
c_oflag Output processing flags
c_cflag Serial-line control flags
c_lflag Local terminal behavior: canonical mode, signals, echo, jobs
c_cc Control-character table and noncanonical read parameters

The most important local flags:

Flag Meaning
ICANON Canonical mode: input is line-oriented and edited by the driver
IEXTEN Extra line-editing keys such as word erase and reprint
ISIG Interpret interrupt, quit, and suspend characters as signals
ECHO Echo typed characters back to the terminal
TOSTOP Stop background groups that try to write to the terminal

Canonical mode gives the program a complete line only after the user presses Enter. Noncanonical mode lets the program receive bytes sooner; full-screen programs and editors commonly use it, usually through libraries such as ncurses.

Temporarily turning off echo is enough for simple password-style input:

struct termios old, now;
char buf[128];

if (!isatty(0)) {
    fprintf(stderr, "standard input is not a terminal\n");
    exit(1);
}

tcgetattr(0, &old);
now = old;
now.c_lflag &= ~ECHO;
tcsetattr(0, TCSANOW, &now);

printf("Password: ");
fflush(stdout);
fgets(buf, sizeof(buf), stdin);
putchar('\n');

tcsetattr(0, TCSANOW, &old);

Always restore terminal settings after changing them. Production code should also restore them on error paths and on relevant signals.

The c_cc array assigns meanings to control characters:

Entry Usual meaning
VEOF End-of-file character, usually Ctrl-D
VINTR Interrupt character, usually Ctrl-C
VQUIT Quit character, usually Ctrl-\
VSUSP Suspend character, usually Ctrl-Z
VSTOP Stop output, usually Ctrl-S
VSTART Resume output, usually Ctrl-Q
VERASE Erase previous character, usually Backspace
VKILL Kill current line, usually Ctrl-U
VWERASE Erase previous word, usually Ctrl-W
VREPRINT Reprint current line, usually Ctrl-R
VMIN Minimum bytes needed for noncanonical read
VTIME Timeout for noncanonical read, in tenths of a second

Setting a control-character slot to _POSIX_VDISABLE disables that special character on systems that support the value.

Detailed notes - 5.4.3: Controlling the terminal driver

1

usual terminal behavior:

  • input is delivered after a complete line is entered
  • typed characters are echoed
  • certain control characters trigger special actions

2

crt and ncurses change terminal-driver settings for full-screen programs

  • the same settings can be controlled directly

3

termios provides C library functions for terminal control

  • underlying device operations use ioctl
  • includes tcsetpgrp and functions for line settings
  • serial-line settings reflect its origins with physical RS-232 terminals
  • these options still matter when communicating with serial devices

4

direct terminal control is useful for small tasks:

  • example: read a password without echo
  • a full-screen library is unnecessary for changing one setting

5

canonical vs noncanonical input:

  • canonical: line discipline collects and edits complete lines
  • noncanonical: read behavior is controlled by byte counts and timers
  • echo and signal handling are separate options
  • special characters can be reassigned

6

struct termios stores terminal settings:

  • tcgetattr(fd, &settings) reads them
  • tcsetattr(fd, options, &settings) installs them
  • fd must refer to the terminal to configure
  • check isatty before assuming standard input is a terminal

7

tcsetattr timing options:

  • TCSANOW: apply immediately
  • TCSADRAIN: wait for queued output to be transmitted
  • TCSAFLUSH: drain output and discard unread input before applying

8

main struct termios fields:

  • c_iflag: input processing flags
  • c_oflag: output processing flags
  • c_cflag: communication / hardware control flags
  • c_lflag: local line-discipline flags
  • c_cc[NCCS]: control-character settings
  • use declared types tcflag_t and cc_t, not assumed int / char types

9

IXON in c_iflag enables software flow control:

  • Ctrl-S normally suspends terminal output
  • Ctrl-Q resumes it
  • useful when output scrolls faster than the user can read

10

other input-processing examples:

  • IGNCR discards incoming carriage returns (CR, code 13)
  • ISTRIP removes the high bit of incoming bytes
  • such transformations can corrupt multibyte or eight-bit text
  • many input flags relate to physical serial-line behavior

11

c_oflag controls outgoing character processing

  • flags can affect newline / carriage-return handling
  • OLCUC, where supported, maps lowercase Latin letters to uppercase

12

c_cflag mostly concerns the physical communication channel

  • baud rate, character format, and modem-related behavior
  • these are less relevant to an entirely virtual terminal connection

13

c_lflag includes the main line-discipline controls:

  • ICANON enables complete-line input and line editing
  • basic editing includes erase-character and erase-line
  • IEXTEN enables additional processing such as word erase and redisplay

14

ISIG enables terminal-generated signals:

  • Ctrl-C -> SIGINT
  • Ctrl-\ -> SIGQUIT
  • Ctrl-Z -> SIGTSTP

15

TOSTOP controls output from background process groups:

  • clear: background output is normally allowed
  • set: background output can generate SIGTTOU and stop the group
  • background reads are already restricted by SIGTTIN
  • SIGCONT resumes stopped processes

16

ECHO controls whether typed characters appear on the screen

password-input example:

  • verify that input is a terminal
  • get settings and save an unchanged copy
  • clear ECHO, then apply the changed settings
  • read the secret without displaying it
  • restore saved settings on completion and on error paths

17

usual terminal-setting pattern: read -> modify a copy -> apply -> restore

  • constructing all termios fields from scratch is error-prone
  • set flags with bitwise OR: ts.c_lflag |= ICANON | IEXTEN | ISIG | ECHO;

18

clear selected flags with an inverted mask:

  • ts.c_lflag &= ~(ICANON | IEXTEN | ISIG | ECHO);
  • selected bits become zero; other bits retain their values

19

editing the struct changes only the process's copy

  • call tcsetattr to change the actual terminal settings

20

c_cc stores special-character codes at named indices

  • c_cc[VEOF] normally contains 4 -> Ctrl-D
  • assigning another code changes the EOF control character
  • VEOF processing belongs to canonical mode

21

other c_cc indices and usual bindings:

  • VINTR: 3 / Ctrl-C -> SIGINT
  • VQUIT: 28 / Ctrl-\ -> SIGQUIT
  • VSUSP: 26 / Ctrl-Z -> SIGTSTP
    • these require ISIG
  • VSTOP / VSTART: 19 / Ctrl-S and 17 / Ctrl-Q
    • flow control requires IXON
  • VERASE: 127 / Backspace; VKILL: 21 / Ctrl-U
  • VWERASE: 23 / Ctrl-W; VREPRINT: 18 / Ctrl-R
    • word erase and redisplay use extended canonical processing

22

newline itself is always code 10

  • VEOL and VEOL2 can add alternative line-ending characters

23

disable an individual control character using the platform's disable value

  • _POSIX_VDISABLE is used for this purpose
  • disabling VINTR removes the keyboard binding that generates SIGINT

24

noncanonical reads use VMIN and VTIME:

  • VMIN: minimum byte count
  • VTIME: timer measured in tenths of a second
  • VMIN = 1, VTIME = 0 waits for at least one byte
  • disabling ICANON does not itself clear the separate ISIG flag

25

VMIN = 0, VTIME = 0:

  • read returns immediately with available bytes
  • no data -> read returns 0
  • unlike EOF, this can just mean that nothing is ready yet
  • O_NONBLOCK commonly reports unavailable input with -1 / EAGAIN

26

with a nonzero VTIME:

  • VMIN = 0: timer starts when read begins
  • VMIN > 0: timer starts after the first byte and restarts for each byte
  • return when the required data arrives or the applicable timer expires
  • useful for serial devices as well as interactive terminals

27

further reading from the book:

  • The TTY demystified
  • man 3 termios
Examples & tests (7 files) - 5.4.3: Controlling the terminal driver
Book exampleBook example: blindpsw.cIn catalog
blindpsw.cC / 28 lines
#include <stdio.h>
#include <termios.h>
#include <unistd.h>  /* for isatty */
#include <string.h>  /* for memcpy */

int main()
{
    struct termios ts1, ts2;
    char buf[128];
    char *r;
    if(!isatty(0)) {
        fprintf(stderr, "We cat only work with a terminal, sorry\n");
        return 1;
    }
    tcgetattr(0, &ts1);
    memcpy(&ts2, &ts1, sizeof(ts1));
    ts1.c_lflag &= ~ECHO;
    tcsetattr(0, TCSANOW, &ts1);
    printf("Please blind-type the code: ");
    r = fgets(buf, sizeof(buf), stdin);
    if(!r) {
        fprintf(stderr, "Unexpected end of file\n");
        return 1;
    }
    printf("\nThe code you entered is [%s]\n", buf);
    tcsetattr(0, TCSANOW, &ts2);
    return 0;
}
Section test03 (05-04)In catalog
passwd.cC / 32 lines
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>

enum { bufsize = 128 };

int main()
{
    struct termios ts1, ts2;
    char buf[bufsize];
    char *r;

    if (!isatty(0)) {
        fprintf(stderr, "Not a terminal, sorry\n");
        return 1;
    }

    tcgetattr(0, &ts1);
    memcpy(&ts2, &ts1, sizeof(ts1));
    ts1.c_lflag &= ~ECHO;
    tcsetattr(0, TCSANOW, &ts1);
    printf("Please bind-type the code: ");
    r = fgets(buf, sizeof(buf), stdin);
    if (!r) {
        fprintf(stderr, "Unexpected end of file\n");
        return 1;
    }
    printf("\nThe code you entered is [%s]\n", buf);
    tcsetattr(0, TCSANOW, &ts2);
    return 0;
}
terminal-00.cC / 26 lines
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>

int main()
{
    struct termios ts1, ts2;

    if (!isatty(0)) {
        fprintf(stderr, "Not a terminal, sorry\n");
        return 1;
    }

    tcgetattr(0, &ts1);
    memcpy(&ts2, &ts1, sizeof(ts1));

    ts1.c_cc[VINTR] = 0;
    tcsetattr(0, TCSANOW, &ts1);

    while (1)
        sleep(1);

    tcsetattr(0, TCSANOW, &ts2);
    return 0;
}
terminal-01.cC / 35 lines
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <string.h>

enum { buf_size = 4096 };

int main()
{
    struct termios ts1, ts2;
    char buf[buf_size];
    int rc;

    if (!isatty(0)) {
        fprintf(stderr, "Not a terminal, sorry\n");
        return 1;
    }

    tcgetattr(0, &ts1);
    memcpy(&ts2, &ts1, sizeof(ts1));

    ts1.c_lflag &= ~(ICANON | IEXTEN | ISIG | ECHO);
    ts1.c_cc[VMIN] = 5;
    ts1.c_cc[VTIME] = 10;
    tcsetattr(0, TCSANOW, &ts1);

    while (1) {
        rc = read(0, buf, buf_size);
        write(1, "hello", 6);
        write(1, buf, rc);
    }

    tcsetattr(0, TCSANOW, &ts2);
    return 0;
}
terminal-02.cC / 55 lines
#define _XOPEN_SOURCE 600

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main(void) {
    int master_fd = posix_openpt(O_RDWR | O_NOCTTY);
    if (master_fd == -1) {
        perror("posix_openpt");
        return 1;
    }

    if (grantpt(master_fd) == -1) {
        perror("grantpt");
        close(master_fd);
        return 1;
    }

    if (unlockpt(master_fd) == -1) {
        perror("unlockpt");
        close(master_fd);
        return 1;
    }

    char *slave_name = ptsname(master_fd);
    if (slave_name == NULL) {
        perror("ptsname");
        close(master_fd);
        return 1;
    }

    printf("slave device: %s\n", slave_name);

    int slave_fd = open(slave_name, O_RDWR | O_NOCTTY);
    if (slave_fd == -1) {
        perror("open slave");
        close(master_fd);
        return 1;
    }

    /*
       master_fd and slave_fd are now connected.

       Data written to master_fd can be read from slave_fd.
       Data written to slave_fd can be read from master_fd.
    */

    close(slave_fd);
    close(master_fd);
    return 0;
}
terminal-03.cC / 95 lines
#define _XOPEN_SOURCE 600

#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <termios.h>

int main(void) {
    int master_fd = posix_openpt(O_RDWR | O_NOCTTY);
    if (master_fd == -1) {
        perror("posix_openpt");
        return 1;
    }

    if (grantpt(master_fd) == -1) {
        perror("grantpt");
        return 1;
    }

    if (unlockpt(master_fd) == -1) {
        perror("unlockpt");
        return 1;
    }

    char *slave_name = ptsname(master_fd);
    if (slave_name == NULL) {
        perror("ptsname");
        return 1;
    }

    pid_t pid = fork();

    if (pid == -1) {
        perror("fork");
        return 1;
    }

    if (pid == 0) {
        /*
           Child: create a new session.
           After this, the child has no controlling terminal.
        */
        if (setsid() == -1) {
            perror("setsid");
            _exit(1);
        }

        /*
           Open slave side. Do NOT use O_NOCTTY here if you want
           this PTY to become the child's controlling terminal.
        */
        int slave_fd = open(slave_name, O_RDWR);
        if (slave_fd == -1) {
            perror("open slave");
            _exit(1);
        }

        /*
           Connect terminal to stdin/stdout/stderr.
        */
        dup2(slave_fd, STDIN_FILENO);
        dup2(slave_fd, STDOUT_FILENO);
        dup2(slave_fd, STDERR_FILENO);

        if (slave_fd > STDERR_FILENO) {
            close(slave_fd);
        }

        close(master_fd);

        execlp("bash", "bash", NULL);
        perror("execlp");
        _exit(1);
    }

    /*
       Parent: terminal-emulator side.
       It talks to the child through master_fd.
    */

    printf("child is using slave PTY: %s\n", slave_name);

    /*
       Here you would normally:
       - read from keyboard/stdin and write to master_fd
       - read from master_fd and write to screen/stdout
    */

    waitpid(pid, NULL, 0);
    close(master_fd);

    return 0;
}
terminal-04.cC / 79 lines
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <signal.h>

typedef void (*signalhandler_t)(int);

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void set_sigactions(int signum, signalhandler_t handler)
{
    int r;

    struct sigaction act = { 0 };
    act.sa_handler = handler;
    r = sigaction(signum, &act, NULL);
    if (r == -1)
        terminate("sigaction", 1);
}

static void print_ids()
{
    int pid, sid, pgid;

    pid = getpid();
    sid = getsid(pid);
    pgid = getpgid(pid);
    printf("pid: %d, sid: %d, pgid: %d\n", pid, sid, pgid);
}

int main()
{
    int pid, ret, fd;
    const char *file_name;

    print_ids();

    pid = fork();
    if (pid > 0) {
/*
        ret = setpgid(pid, pid);
        if (ret == -1)
            terminate("setpgid", 1);
*/

        while (1)
            sleep(1);
    }
    print_ids();

/*
    file_name = "/dev/pts/3";
    fd = open(file_name, O_RDWR);
    if (fd == -1)
        terminate(file_name, 1);
*/

    ret = setsid();
    if (ret == -1)
        terminate("setsid", 1);


    set_sigactions(SIGCHLD, SIG_IGN);
    file_name = "/dev/tty";
    fd = open(file_name, O_RDWR|O_NOCTTY);
    if (fd == -1)
        terminate(file_name, 1);
    tcsetpgrp(fd, getpgid(0));

    print_ids();

    return 0;
}

Pseudoterminals

A pseudoterminal is a kernel object that lets a program emulate a terminal. It has two sides:

Side Used by
Master Terminal emulator or remote-login server
Slave Shell and programs running as if attached to a real terminal

Bytes written on one side are read from the other. The line discipline sits on the slave side, so a terminal emulator such as xterm does not need to send SIGINT itself. It writes the Ctrl-C byte to the master side; the terminal driver interprets it and signals the foreground process group.

Portable creation flow:

int master;
char *slave_name;

master = posix_openpt(O_RDWR | O_NOCTTY);
grantpt(master);
unlockpt(master);
slave_name = ptsname(master);

posix_openpt opens /dev/ptmx and creates a master/slave pair. grantpt sets ownership and permissions for the slave device. unlockpt allows the slave side to be opened. ptsname returns the slave device path.

Some systems also provide openpty, which creates and opens both sides in one call:

int openpty(int *master, int *slave, char *name,
            const struct termios *termp,
            const struct winsize *winp);

It is convenient but less portable.

Detailed notes - 5.4.4: The other side of a pseudoterminal

1

terminal emulation has two main forms:

  • virtual consoles implemented by the kernel
  • ordinary user programs such as xterm
  • pseudoterminal = kernel object providing the latter's virtual link

2

pseudoterminal has two bidirectional endpoints:

  • master: used by the terminal emulator
  • slave: used by programs running under the terminal

3

create a pseudoterminal master:

  • getpt() is a glibc-specific interface
  • portable interface: posix_openpt(O_RDWR | O_NOCTTY)
  • Linux implements this through /dev/ptmx
  • returns the master descriptor and creates an associated slave device
  • slave's device file lets the session's programs connect to the pair

4

prepare the slave before opening it:

  • grantpt(master_fd) establishes suitable ownership / access
  • unlockpt(master_fd) allows the slave to be opened
  • ownership setup must correspond to the user receiving the session
  • remote-login services also establish the authenticated user's credentials

5

unlockpt completes the preparation:

  • ptsname(master_fd) supplies the slave device's pathname
  • child can create a session with setsid
  • open the slave and connect it to descriptors 0, 1, and 2
  • exec starts the shell or other session program
  • master remains with the program implementing terminal behavior

6

openpty can create and open both endpoints together:

  • returns master and slave descriptors through pointer arguments
  • optional name buffer receives the slave pathname
  • optional termios and winsize arguments initialize terminal behavior
  • optional arguments may be NULL

7

openpty originated in BSD

  • available on several systems, but not the POSIX portable interface
Tests & experiments (4 files) - 5.4.4: The other side of a pseudoterminal
Section test04 (05-04)In catalog
terminal-00.cC / 80 lines
#define _XOPEN_SOURCE 600

#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

static int child_process(int fd_master, const char *name_slave)
{
    int pid, ret, fd_slave;

    pid = fork();
    if (pid == -1)
        terminate("fork", 1);

    if (pid == 0) {
        ret = setsid();
        if (ret == -1)
            terminate("setsid", 1);

        fd_slave = open(name_slave, O_RDWR);
        if (fd_slave == -1)
            terminate("open", 1);

        dup2(fd_slave, 0);
        dup2(fd_slave, 1);
        dup2(fd_slave, 2);
        close(fd_master);
        close(fd_slave);
        execlp("bash", "bash", NULL);
        terminate_exec("bash", 1);
    }

    return pid;
}

int main()
{
    int fd_master, ret, pid;
    char *name_slave;

    fd_master = posix_openpt(O_RDWR | O_NOCTTY);
    if (fd_master == -1)
        terminate("posix_openpt", 1);

    ret = grantpt(fd_master);
    if (ret == -1)
        terminate("grantpt", 1);

    ret = unlockpt(fd_master);
    if (ret == -1)
        terminate("unlockpt", 1);

    name_slave = ptsname(fd_master);
    if (name_slave == NULL)
        terminate("ptsname", 1);

    pid = child_process(fd_master, name_slave);

    printf("child is using slave PTY: %s\n", name_slave);

    waitpid(pid, NULL, 0);
    close(fd_master);

    return 0;
}
terminal-01.cC / 96 lines
#define _XOPEN_SOURCE 600

#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void write_fd(int fd, const char *str)
{
    write(fd, str, strlen(str));
}

static int child_process(int fd_master, const char *name_slave)
{
    int pid, ret, fd_slave;

    pid = fork();
    if (pid == -1)
        terminate("fork", 1);

    if (pid == 0) {
        ret = setsid();
        if (ret == -1)
            terminate("setsid", 1);

        fd_slave = open(name_slave, O_RDWR);
        if (fd_slave == -1)
            terminate("open", 1);

        dup2(fd_slave, 0);
        dup2(fd_slave, 1);
        dup2(fd_slave, 2);
        close(fd_master);
        close(fd_slave);
        execlp("bash", "bash", NULL);
        terminate_exec("bash", 1);
    }

    return pid;
}

int main()
{
    int fd_master, ret, pid;
    char *name_slave;

    fd_master = posix_openpt(O_RDWR | O_NOCTTY);
    if (fd_master == -1)
        terminate("posix_openpt", 1);

    ret = grantpt(fd_master);
    if (ret == -1)
        terminate("grantpt", 1);

    ret = unlockpt(fd_master);
    if (ret == -1)
        terminate("unlockpt", 1);

    name_slave = ptsname(fd_master);
    if (name_slave == NULL)
        terminate("ptsname", 1);

    pid = child_process(fd_master, name_slave);

    sleep(10);

    printf("child is using slave PTY: %s\n", name_slave);

    write_fd(fd_master, "ls\necho hello\nexit\n");

    char buf[1024];
    int n;

    while ((n = read(fd_master, buf, sizeof(buf))) > 0)
        write(1, buf, n);

    waitpid(pid, NULL, 0);
    close(fd_master);

    return 0;
}
terminal-02.cC / 96 lines
#define _XOPEN_SOURCE 600

#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void write_fd(int fd, const char *str)
{
    write(fd, str, strlen(str));
}

static int child_process(int fd_master, const char *name_slave)
{
    int pid, ret, fd_slave;

    pid = fork();
    if (pid == -1)
        terminate("fork", 1);

    if (pid == 0) {
        ret = setsid();
        if (ret == -1)
            terminate("setsid", 1);

        fd_slave = open(name_slave, O_RDWR);
        if (fd_slave == -1)
            terminate("open", 1);

        dup2(fd_slave, 0);
        dup2(fd_slave, 1);
        dup2(fd_slave, 2);
        close(fd_master);
        close(fd_slave);
        execlp("bash", "bash", NULL);
        terminate_exec("bash", 1);
    }

    return pid;
}

int main()
{
    int fd_master, ret, pid;
    char *name_slave;

    fd_master = posix_openpt(O_RDWR | O_NOCTTY);
    if (fd_master == -1)
        terminate("posix_openpt", 1);

    ret = grantpt(fd_master);
    if (ret == -1)
        terminate("grantpt", 1);

    ret = unlockpt(fd_master);
    if (ret == -1)
        terminate("unlockpt", 1);

    name_slave = ptsname(fd_master);
    if (name_slave == NULL)
        terminate("ptsname", 1);

    pid = child_process(fd_master, name_slave);

    sleep(2);

    printf("child is using slave PTY: %s\n", name_slave);

    write_fd(fd_master, "\x04");

    char buf[1024];
    int n;

    while ((n = read(fd_master, buf, sizeof(buf))) > 0)
        write(1, buf, n);

    waitpid(pid, NULL, 0);
    close(fd_master);

    return 0;
}
terminal-03.cC / 24 lines
#include <stdio.h>
#include <pwd.h>

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s <user name>\n", argv[0]);
        return 1;
    }

    struct passwd *pw = getpwnam(argv[1]);

    if (pw != NULL) {
        printf("Name: %s\n", pw->pw_name);
        printf("Password: %s\n", pw->pw_passwd);
        printf("UID: %d\n", pw->pw_uid);
        printf("GID: %d\n", pw->pw_gid);
        printf("Home: %s\n", pw->pw_dir);
        printf("Shell: %s\n", pw->pw_shell);
    } else {
        printf("User not found\n");
    }

    return 0;
}

Daemons

A daemon is a long-running background process not meant to interact directly with a terminal. Web servers, mail servers, print services, scheduled job runners, and system logging services are typical examples.

Daemon startup usually does three things:

Step Reason
Detach from terminal/session Terminal hangups should not control the daemon
Change directory, often / Avoid pinning removable or administratively managed mounts
Redirect descriptors 0..2 Prevent accidental reads/writes through standard descriptors

Typical daemonization outline:

int pid;

close(0);
close(1);
close(2);
open("/dev/null", O_RDONLY);
open("/dev/null", O_WRONLY);
open("/dev/null", O_WRONLY);

chdir("/");

pid = fork();
if (pid > 0) {
    exit(0);
}

setsid();

pid = fork();
if (pid > 0) {
    exit(0);
}

The first fork ensures that setsid can succeed. The second fork makes the daemon stop being a session leader, reducing the chance that it accidentally acquires a controlling terminal later.

Since daemons do not have an interactive terminal, they normally report diagnostics through the system log:

void openlog(const char *ident, int options, int facility);
void syslog(int priority, const char *format, ...);
void closelog(void);

Common priorities include LOG_ERR, LOG_WARNING, and LOG_INFO. Programs without a more specific facility usually use LOG_USER. Many daemons also use SIGHUP as a request to reload configuration.

Detailed notes - 5.4.5: Daemons

1

daemon = process intended to work without direct terminal interaction

  • examples: web / mail servers, cron, print service
  • often runs for a long time
  • commonly changes current directory to / so it does not keep another filesystem busy or prevent its unmounting

2

keep standard descriptors open even if unused:

  • otherwise a later open may reuse 0, 1, or 2 for an unrelated file
  • accidental standard-output writes could then corrupt that file
  • traditional daemons redirect all three to /dev/null

3

traditional daemonization separates the process from the terminal:

  • redirect standard streams to /dev/null
  • chdir("/")
  • fork and let the original parent exit
  • setsid creates a separate session
  • fork again and let the session leader exit

4

the two forks have different purposes:

  • first ensures child is not a group leader, allowing setsid
  • second makes surviving daemon a non-leader
  • -> it cannot accidentally acquire a controlling terminal

5

without terminal output, diagnostics go to system logging:

  • openlog establishes logging settings
  • syslog sends a formatted message
  • closelog releases logging resources
  • implementation may send messages to a logging daemon through a socket

6

openlog(ident, options, facility):

  • ident names the program in log messages
  • options controls logging details; 0 is often enough
  • facility classifies the service
  • LOG_USER is suitable when no special facility applies

7

syslog(priority, format, ...) resembles printf:

  • LOG_ERR: error
  • LOG_WARNING: warning
  • LOG_INFO: informational message
  • administrator can filter messages by severity
  • example: syslog(LOG_INFO, "Daemon started, pid == %d", getpid());

8

closelog ends the program's connection to system logging

  • releases any associated open resources

9

signals can serve as daemon-control requests:

  • SIGHUP commonly requests a configuration reload
  • more elaborate services may use other control interfaces
Section test (1 file) - 5.4.5: Daemons
Section test05 (05-04)In catalog
terminal.cC / 64 lines
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <pty.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

static int child_process(int fd_master, int fd_slave, const char *name_slave)
{
    int pid, ret;

    pid = fork();
    if (pid == -1)
        terminate("fork", 1);

    if (pid == 0) {
        ret = setsid();
        if (ret == -1)
            terminate("setsid", 1);

        dup2(fd_slave, 0);
        dup2(fd_slave, 1);
        dup2(fd_slave, 2);
        close(fd_master);
        close(fd_slave);
        execlp("bash", "bash", NULL);
        terminate_exec("bash", 1);
    }

    return pid;
}

int main()
{
    int fd_master, fd_slave, ret, pid;
    char *name_slave;

    ret = openpty(&fd_master, &fd_slave, name_slave, NULL, NULL);
    if (ret == -1)
        terminate("openpty", 1);

    pid = child_process(fd_master, fd_slave, name_slave);

    printf("child is using slave PTY: %s\n", name_slave);

    waitpid(pid, NULL, 0);
    close(fd_master);
    close(fd_slave);

    return 0;
}

Previous: C Programming Reading map Next: Networks and Protocols

Comments

Leave a comment Sign in All comments