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
mmapfork,
exec, termination, waiting, zombies, time, priority, and
redirectionThe 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.
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.
operating system in the narrow sense:
operating system in the broad sense:
user task:
background needed before studying OS:
CPU execution modes:
return from a user task to privileged mode also transfers control to a
predefined handler owned by the OS:
only kernel code executes in privileged mode
multitasking modes:
full multitasking needs hardware support for:
OS material had appeared earlier because later programming topics could not be explained without it; earlier treatment was necessarily superficial
detailed OS study has 2 aspects:
why the OS is needed:
user program -> system call -> kernel -> hardware or kernel object
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.
device management has 2 parts: coordination and abstraction
abstraction is needed because devices are numerous and different:
OS device abstraction:
physical storage devices differ widely:
OS presents these devices as one disk abstraction:
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.
starting and stopping tasks:
CPU scheduling:
memory management is part of task management:
processes need to communicate
privileges belong to running programs/processes, not directly to human users
multi-user systems need access control:
giving one user unrestricted privileges on a personal machine is
dangerous:
the book notes that Unix systems had avoided actively spreading viruses;
it attributes this mainly to privilege separation and Unix design choices
Unix administrators normally:
Unix interfaces usually expose technical details instead of hiding
them:
Unix design traditionally favors engineering and security over marketing
claims of convenience:
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.
OS responsibilities:
kernel has special costs and risks:
minimal-kernel principle:
OS should not provide user communication:
Android and Mac OS X illustrate the distinction:
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.
Unix names a family of systems built around common principles, not one particular OS; a broader Unix philosophy grew around those principles
main Unix design principle:
example setting:
program w lists active sessions and their users
remove the two header lines with tail -n +3
finish the pipeline:
this is an example of six small programs cooperating in one pipeline to solve a real task
text representation can use more memory and require parsing than binary,
but it is easy for people to:
Unix generally prefers text except for:
many Internet protocols use text streams:
"silence is golden":
Unix user interfaces generally assume that the user knows what they are
doing:
graphical interfaces follow "mechanism, not policy":
"everything is a file":
Unix syscall interfaces also follow the simple-composition philosophy:
"everything is a byte stream" in the syscall interface:
KISS = "Keep it simple, Stupid!"
Unix software is usually distributed as portable source code:
free software is not the same as freeware or merely open source
GNU GPL protects these freedoms with a copyleft condition:
GPL does not require a zero price:
open source and free software are different:
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.
Unix architecture was not changed fundamentally by graphical desktops because graphical shells are outside the kernel
X Window System:
an X GUI application remains an ordinary Unix process:
X server:
X connection may be local or over a network
X uses a stream socket:
X server is also an ordinary process
an X server need not use a physical video card:
to inspect the system directly, start an X server without the usual desktop
wrapper; the classic display mode uses the -retro option
if another X server is already running:
a bare X server shows an empty screen, a large X-shaped cursor, and its default textured background
without clients, the only useful action is moving the cursor
start a client and explicitly select its display:
with only X and xterm running, the xterm window has no border, title, or minimize/maximize/close buttons
window decoration is provided by a separate window manager:
some modern Gnome applications take over work traditionally assigned to the window manager, which makes them awkward under other window managers
start a lightweight window manager such as twm from xterm
when the window manager runs:
an X window manager is just another X client
an X application may run on the same host as the X server or remotely
X-terminal sessions need remote authentication and session setup:
terminology is confusing because several levels are involved:
at the X protocol level, the X-terminal provides the display service and
is therefore the server; applications requesting display are clients
many X terminals plus a few application servers can reduce
administration:
traditional X terminals carried keyboard/mouse events and graphics
#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;
}
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 |
system-call entry is processor-dependent:
C normally uses library wrappers that look like ordinary C functions
C library wrappers smooth kernel differences:
common Unix wrapper error handling:
with threads, errno is usually a macro selecting a per-thread integer:
#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;
}
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.
user task alone:
kernel:
privilege separation is essential:
requests normally allowed to every task include:
many requests depend on user or group identity:
root is the Unix superuser:
quantitative limits can also be enforced:
Unix privilege separation uses numeric identifiers:
"user" in the kernel does not necessarily mean a human:
uid 0 identifies root
users can belong to groups:
groups originally supported cooperation on multi-user systems
/etc/passwd and /etc/group are ordinary readable text files:
fields in /etc/passwd describe:
passwords are no longer stored in /etc/passwd:
/etc/group has four fields:
primary-group membership comes from the fourth /etc/passwd field and need not be repeated in /etc/group
kernel does not read /etc/passwd or /etc/group itself:
Unix input/output is built around a small set of simple ideas:
input/output includes:
programs under multitasking OSs perform I/O through system calls
this chapter fills in file and stream details that were previously left implicit
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 |
file:
filesystem:
filesystem can also mean the on-disk data structures:
"filesystem" therefore has 2 meanings:
early filesystems used short names in one global namespace
use directory or catalogue, not the informal word folder
directory:
each process has a current directory
Unix uses one directory tree instead of device letters such as A: or C:
Unix directory entry stores only:
file structure:
Unix file names may be about 255 characters and may contain almost any character except NUL and slash
hard links:
unlink removes a directory entry, not necessarily the data:
command ln creates a hard link
directory is itself a special kind of file:
directory restrictions:
symbolic link:
create a symbolic link with:
short symbolic-link targets may be stored inside the inode's block-pointer area
other special files may also occupy no blocks outside the inode
/
|-- bin
|-- dev
|-- etc
|-- home
| `-- student
`-- tmp
directory name -> inode number -> inode -> data blocks
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.
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.
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 |
file permissions determine which processes, acting for which users, may perform operations on a file
inode stores:
octal notation matches the three-bit groups:
directory execute permission means access/traversal, not running a
program:
special permission bits:
SetUid is often used on administrator-owned programs
Sticky bit originally kept frequently used executable code in memory
Unix executables can be binary or script files:
SetUid and SetGid are ignored for executable scripts
suid-script threat setup:
starting a script involves a race:
attacker can exploit the two opens:
Sticky bit on a public writable directory:
SetGid on a directory:
SetUid on directories is ignored on most systems, including Linux
some systems interpret SetGid without group execute as mandatory locking
permission and ownership tools:
symlink permissions are normally ignored
rwx r-x r--
owner group others
#!/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())
#!/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])
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:
read may return fewer bytes than requested.read returns 0 at end of file.write may write fewer bytes than requested.open,
read, write, and closeclose after writing, because delayed write errors
can appear thereWhen 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
Unix commonly represents transferred data as byte streams
C wrappers for the basic I/O calls are named open, read, write, lseek, and close
system calls identify streams by file descriptors:
file descriptor and inode are unrelated:
standard descriptors are a convention:
number is only an index into a kernel data structure
open creates a new I/O stream and has two profiles:
open name and mode:
common modifying flags:
O_NONBLOCK makes reads and writes return immediately instead of waiting
perms is used only when O_CREAT may create a new file
umask:
common umask choices:
new ordinary data files usually request perms 0666
open result:
opening must always be checked
read and write profiles:
read behavior:
write may block on streams with limited kernel buffers:
read/write results:
always inspect read's result
write results should normally be checked too
without O_NONBLOCK, write usually waits until all supplied data is accepted
modern write returns zero only when len is zero, which should not be relied on
lseek changes the current position in an open stream:
seeking past the end and writing creates a sparse-file hole
only some streams are seekable
off_t size matters:
lseek64 supplies a 64-bit offset and return value
close releases a descriptor:
check close especially after writing
several descriptor numbers may refer to one kernel stream object
asynchronous output is common:
asynchronous output can lose data on a crash or power failure
fsync waits for one file's pending data and required metadata:
fdatasync is similar to fsync
sync requests system-wide writeback:
fcntl configures descriptor behavior:
open flags have categories:
test a status flag with bitwise and:
F_SETFL changes status flags
fcntl(fd, F_SETFL, O_NONBLOCK) is enough when no other status flags matter
#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;
}
#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;
}
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.
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.
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.
filesystem-object calls cover operations besides reading and writing
link creates a hard link:
unlink removes a directory entry:
unlink deletes file data only after the last link is removed and the file is
closed by the last process using it
rename changes a file name or moves it within one filesystem:
rename can atomically replace an existing non-directory target
mkdir and rmdir create and remove directories:
symlink creates a symbolic link:
unlink applied to a symbolic link removes the link itself
chmod changes permission bits:
chown and lchown change ownership:
stat, lstat, and fstat obtain metadata:
truncate and ftruncate change file length:
#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;
}
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;
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 |
Unix presents many external devices as special files:
device-file examples:
device files use ordinary system calls:
older Linux audio devices could be read and written as files
not every peripheral has a file representation
device files are either:
pseudo character devices:
block devices usually represent disks
device files are special file types alongside directories and symbolic links
FreeBSD moved away from a separate block-device type because of cache control
ioctl handles device-specific operations:
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
directory is a special disk file containing names and inode numbers
kernel alone changes directory contents:
C library directory interface:
readdir returns a pointer to a library-owned struct dirent
when entries are exhausted, readdir returns NULL
struct dirent is system-dependent:
sample directory listing program:
#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;
}
#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;
}
#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;
}
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:
offset must be page-aligned.length is rounded to whole pages by the system.NULL as start unless there is a
specific reason to choose an address.SIGBUSmunmap removes mappingsmsync forces mapped changes toward storagemmap is also used as a general mechanism for allocating
virtual memory. An anonymous private mapping gives a process fresh
memory directly from the OS.
mmap maps file contents into a process's virtual address space
before mmap, open the file and pass its descriptor in fd
mmap page size need not equal the virtual-memory page size
protection flags:
flags select shared or private behavior:
MAP_ANONYMOUS|MAP_SHARED creates shared memory across forked processes
start is an optional preferred address
mmap returns the mapped address
example mapping:
file length need not be page-aligned:
munmap cancels mappings:
munmap removes every page intersecting the requested range
msync can force modified mapped pages to be written to the file
mmap is now also a general virtual-memory allocation interface
PROGRAMS = 05-02-07-mmap-04
CFLAGS = -g -Wall -O0
all: $(PROGRAMS)
$(PROGRAMS): %: %.c
$(CC) $(CFLAGS) $^ -o $@
clean:
rm -f *.o $(PROGRAMS)
#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);
}
#include <stdio.h>
#include <unistd.h>
int main()
{
int size;
size = getpagesize();
printf("Page size: %d\n", size);
return 0;
}
#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;
}
#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;
}
#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;
}
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.
process:
technical terms can become established before anyone defines them precisely
first approximation: a program that has been started
problem with this approximation:
bare-metal firmware is another counterexample:
working approximation: a program executing under OS control
kernel's view of a process:
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.
process identifiers:
permissions belong to the process acting for a user
query identifiers using getpid(), getppid(), getuid(), getgid(), geteuid(), getegid(), and related calls
process memory consists of regions with different properties
main memory regions:
register state is part of process state:
CPU scheduler selects processes to run
book's example scheduler:
static scheduling preference in Unix is usually expressed by nice value
command-line arguments and environment are also process properties
new programs normally inherit the launching program's environment
some implementations allow a third parameter to main for the environment
environment strings live in process memory -> ordinary library functions suffice
Linux /proc/PID/environ and the library's current environment can differ
some programs change their displayed command line to show current activity
current working directory:
root directory:
chroot is not a complete security boundary
change directory with chdir(path)
change process root with chroot(path)
chroot changes pathname resolution for this process and its descendants
file descriptor table is another process property
descriptor table maps numbers to kernel I/O objects
umask is a process property
other process properties:
#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);
}
#include <stdio.h>
extern char **environ;
int main()
{
int i;
for (i = 0; environ[i]; i++)
printf("%s\n", environ[i]);
return 0;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv)
{
char *str = argv[0];
strcpy(str, "hello there");
sleep(10);
return 0;
}
#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;
}
#include <stdio.h>
int main(int argc, char **argv)
{
printf("hello\n");
return 0;
}
#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;
}
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.
executable sections and runtime memory segments were introduced with assembly
virtual addresses are translated to physical addresses by the MMU
memory organization depends on hardware and OS
book's example: a simplified Linux/i386 address space
illustrated executable starts at 0x08048000
code/data regions are mappings in the kernel's memory model
initial mappings:
Linux also provides brk for changing the program break
address-space randomization introduces unpredictable gaps and positions
stack has a configured size limit, often 8 MB in the book's example
heap and mmap areas can grow into the remaining virtual space
illustrated i386 split reserves 0xC0000000-0xFFFFFFFF for kernel addresses
in the illustrated design:
traditional implementation includes protected kernel mappings in each process's
page tables
systems can add special mappings such as Linux vDSO
Typical areas in a process address space:
#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;
}
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:
pidppid is the parent's pidfork appears to return 0 in the childMemory 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.
traditional Unix process creation: duplicate an existing process with fork()
fork results:
child initially resembles parent, with important differences:
not every property is inherited
three successive successful fork calls produce eight processes
parent and child usually need different work
also handle p == -1
parent and child execute concurrently
parent may print first
child may print first
race condition: result depends on the ordering of independent events
ordinary private memory is logically copied by fork
MAP_SHARED mappings are an exception to private-memory copying
both processes then access the same mapped storage through ptr
shared memory needs synchronization
fork copies the descriptor table, not the underlying open-file descriptions
shared open-file descriptions include the current file offset
#include <stdio.h>
#include <unistd.h>
int main()
{
fork();
fork();
fork();
printf("Hello\n");
return 0;
}
#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;
}
#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;
}
#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);
}
#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;
}
execUnix 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.
exec replaces the program inside an existing process
advantage of separating creation and program replacement:
an interface combining creation and execution must receive more settings at once
execve performs program replacement
execve arguments:
exec library functions provide convenient wrappers around execve
execv uses the caller's current environment
execvp(file, argv) has the same argument arrangement as execv
execvp can search PATH
when argument count is known in source code, an argument list is convenient
execl/execlp form argv from their variadic arguments
example: run ls -l -a /var
successful exec never returns to the old program
exit performs library cleanup before terminating
_exit avoids flushing inherited stdio buffers
book's explicit failure sequence:
flush pending parent diagnostics before fork when needed
exit, _exit, and return from main are examined in the next subsection
open descriptors normally survive exec
FD_CLOEXEC is the exception
descriptor flags and stream status flags are different
fcntl descriptor-flag commands:
query using fcntl(fd, F_GETFD)
open(..., O_CLOEXEC, ...) can set close-on-exec at creation
#include <unistd.h>
#include <stdio.h>
int main()
{
execlp("ls", "ls", "-la", "exec01.c", NULL);
perror("execlp");
exit(1);
return 0;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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.
two main termination paths:
ordinary language-level termination eventually requests kernel termination
exit status convention:
exit versus _exit:
example: printf("Hello, world"); followed by _exit(0)
adding a newline changes the example's behavior when stdout is line-buffered
usual terminal output: newline flushes the line -> message appears usual redirected output: fully buffered -> message may remain unflushed
newline flushing depends on buffering mode
second example: print a line, fork, then return from main
second example prints once to the terminal but twice when redirected
explanation of the duplicated redirected output:
_exit, exit, and return from main are voluntary termination
signal termination has a signal number, not a normal exit status
fatal program errors are commonly reported through signals
termination leaves information that the parent may need
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Hello world");
_exit(0);
}
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Hello world\n");
_exit(0);
}
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Hello world\n");
fork();
return 0;
}
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.
parent collects the child's termination information
zombie occupies a process-table entry until it is reaped
wait behavior:
decode wait status with macros:
wait4 offers child selection, options, and resource accounting
wait4 child selector:
process-group selectors:
remaining wait4 arguments:
wait4 results:
related interfaces:
in the cases discussed here:
cannot kill a zombie: it has already finished executing
blocking on one particular child can delay reaping all the others
when waiting for one target among several children:
#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;
}
#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;
}
#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;
}
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.
fork + exec + wait:
creation:
child, pid == 0:
parent, pid > 0:
#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;
}
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.
program execution takes time
time(&t): current time as seconds since the Epoch
book's historical aside: Unix time passed 1,500,000,000 seconds on 14 July 2017
time also stores its result through the supplied time_t pointer
use time_t for a variable whose address is passed to time
convert seconds since the Epoch to calendar fields:
struct tm fields:
convert a date/time into a fixed-format string:
functions ending in _r write into storage supplied by the caller
strftime formats a struct tm using a format string
one-second resolution is too coarse for many communication timeouts gettimeofday(&tv, NULL): obtain time in struct timeval
sleeping process: temporarily asks for no CPU time
sleep is a library function that can be implemented through other system calls
sleep return value:
usleep requests a pause in microseconds
combining sleep and usleep adds overhead and reduces timing precision
usleep returns 0 on completion or -1 on failure/interruption
nanosleep(&requested, &remaining): request a pause using struct timespec
nanosecond units do not guarantee nanosecond timing accuracy
priority affects how a process receives CPU time
nice(increment): add to the current nice value
negative nice increment requests a higher scheduling priority
-1 from nice may mean either failure or a legitimate nice value of -1
nice value survives exec and is inherited through fork
getpriority(which, who) / setpriority(which, who, priority):
getpriority:
setpriority:
getpriority has the same -1 ambiguity as nice
#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;
}
#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;
}
#include <stdio.h>
#include <time.h>
int main()
{
long t;
t = time(NULL);
printf("%ld\n", t);
}
#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);
}
#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);
}
#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;
}
#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;
}
#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;
}
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 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);
file descriptors can refer to files, pipes, sockets, and other kernel objects
standard descriptor numbers are a convention used by programs and
libraries:
redirecting stdout by closing and reopening:
closing stdout before opening its replacement is fragile:
dup(fd): duplicate an existing descriptor using the lowest free number
dup2(fd, new_fd): duplicate fd at a specified descriptor number
temporarily redirect a library that always writes to stdout:
shell redirections (<, >, >>) usually happen when launching a program
example: reproduce ls -l -a -R / > flist
child:
parent:
alternative: open flist in the parent before fork
fcntl(fd, F_DUPFD, minimum): duplicate fd at the first free number >= minimum
#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;
}
#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;
}
#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;
}
#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;
}
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.
process credentials include:
Linux also has:
book's ordinary user-process model starts with PID 1, traditionally /sbin/init
privileged login programs establish the user's session credentials
executing a SetUid / SetGid program can separate real and effective
IDs:
real and saved IDs allow controlled switching of effective credentials
example: Vasya uid 1003 owns SetUid program vasyaprog; Petya uid 1012 runs it
read process IDs:
actual return types are uid_t and gid_t, not necessarily int
getresuid / getresgid retrieve real, effective, and saved IDs together
getgroups(size, array): retrieve supplementary group IDs
seteuid / setegid change only the effective user/group ID
setuid / setgid also primarily affect the effective ID
setgroups(size, list): replace the supplementary group list
other interfaces can change or retrieve several IDs together:
#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;
}
#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;
}
#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;
}
#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 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.
resource limits restrict how much of a permitted resource a process may use
ulimit -a displays the calling shell's current resource limits
limits belong to individual processes
user-process-count limit:
each resource limit has two levels:
ordinary process:
privileged process: can raise hard limits within system constraints
setrlimit(resource, &limit): set a resource's soft and hard limits
struct rlimit:
resource selects the limit to change:
getrlimit(resource, &limit): read the current soft and hard limits
disk quotas are a separate mechanism
#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;
}
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.
processes can affect one another through shared objects
signals are a simple specialized communication mechanism
pipes provide one-way data transfer
tracing lets one process control and inspect another's execution
a pseudo-terminal lets a user process emulate a terminal device
System V IPC includes:
sockets provide a common interface for communication protocols
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:
malloc, free, or stdio
functions from a handlerwrite only when needederrno if the handler uses system
callsvolatile int
flagserrno == EINTRTimer 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
this subsection covers ordinary signals
signal: a notification chosen from a predefined set
termination signals:
graceful termination followed by forced termination:
fault signals:
default action: terminate and, when enabled, produce a core dump
SIGSTOP: suspend execution; cannot be caught or ignored SIGCONT: resume execution
terminal keyboard signals go to its foreground process group:
SIGCHLD: notify a parent about a child's termination
SIGALRM: timer notification requested by alarm
SIGUSR1 and SIGUSR2: application-defined notifications
signal names are integer macro constants in system headers
senders: another process or the kernel; recipient: a process
kill(target_pid, sig_no) sends a signal:
permissions restrict which processes can be signalled
signal disposition: what to do when a signal arrives
SIGKILL and SIGSTOP cannot have their dispositions changed
simple handler signature: void handler(int s)
signal installs a disposition:
installing a handler does not call it
handlers run asynchronously relative to the main program
historical signal semantics differed between systems
System V behaviour:
early implementations made this race difficult to observe in practice
kernel implementation of signal delivery is discussed later
another System V problem: the same signal can interrupt its own handler
traditional names for the two behaviours:
these names refer to differences between historical Unix families
BSD signal handling:
Linux historically exposed a System V-style signal syscall
prefer sigaction when explicit, predictable handling semantics matter
sigaction gives finer control over handling and signal masks
for the book's signal-based examples:
a handler is entered through signal delivery, not an ordinary main-program call
most library functions cannot safely run in a signal handler
malloc and free are unsuitable in handlers
buffered standard I/O is also unsuitable in handlers
low-level I/O such as write can be used, but preserve errno
ordinary global variables can also be unsafe
volatile tells the compiler that a value can change unexpectedly
volatile sig_atomic_t is the portable type for a simple handler flag
native-width accesses often use one instruction on the processors discussed
the book uses volatile int, reflecting its target implementations
a caught signal can interrupt a blocking operation
handlers execute in user space
waiting indefinitely in the kernel must not prevent signal handling
SA_RESTART, configured through sigaction, restarts certain interrupted calls
some signal library implementations enable SA_RESTART implicitly
for each blocking call in a program with handlers:
example task: print a message on Ctrl-C and finish after 25 notifications
naive implementation:
improvements to that example:
increasing the sleep interval avoids more periodic wakeups
pause waits for a signal whose handler is executed
replacing sleep with pause still leaves a race
ordinary signals with the same number can merge while pending
alarm(seconds) requests one SIGALRM after the specified interval
only one alarm timer is active for a process
install the desired SIGALRM disposition before starting the timer
sleep has historically been allowed to use alarm and SIGALRM internally
interrupted sleep calls have different return conventions
the author prefers the more explicit sleep interfaces
signal-heavy designs are difficult to make correct
example: parent must wait until a new child has finished initialization
first attempt:
lost-wakeup race in that attempt:
solution: combine sigprocmask and sigsuspend
the author recommends keeping signal use simple
the remaining discussion explains waiting with sigsuspend
blocking a signal defers its delivery
sigprocmask(how, set, oldset) changes the blocked-signal set
query the current mask without changing it:
functions operating on sigset_t:
sigsuspend(const sigset_t *mask): temporarily replace the signal mask and wait
sigsuspend waits for an unblocked signal with an effective action
a signal mask lists blocked signals, which can make this interface confusing
usual waiting pattern:
correct child-readiness example:
the same reasoning explains the remaining bugs in the 25-message example
25th-signal race:
signal-flood experiment: int_grill runs pressagain as a child
why the count can become so large:
the example eventually gets a gap between incoming signals
make the check-and-wait sequence correct:
some programmers avoid pause entirely in favour of atomic wait interfaces
the author contrasts deliberate signal flooding with ordinary keyboard input
choose complexity with the real task in mind
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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:
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]);
}
}
pipe: kernel object for one-way data transfer
two kinds of pipe:
pipe(fd) creates an unnamed pipe
connect two children through one pipe:
reading while both ends still have open descriptors:
a pipe contains a finite kernel buffer
when the last write descriptor closes:
when the last read descriptor closes:
pipelines connect concurrently running programs
an N-stage pipeline normally needs N - 1 pipes
an accidental extra read descriptor also matters
example: ls -lR | grep '^d'
FIFO: first in, first out
FIFO is a special filesystem object
mkfifo(name, permissions) creates the FIFO filesystem object
opening a FIFO connects to the kernel channel
kernel pipe state and filesystem FIFO have different lifetimes
ordinary FIFO open waits for the other end to be opened
O_NONBLOCK changes this:
FIFO end closure follows pipe rules:
but new descriptors can later appear through the pathname
#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;
}
#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;
}
#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();
}
#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;
}
#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;
}
#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;
}
#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;
}
#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 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);
}
#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
tracing allows one process, usually a debugger, to control another
ptrace provides tracing operations
trace a newly started program:
attach to an existing process with PTRACE_ATTACH
tracing is a powerful security capability
#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, ®s);
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;
}
#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;
}
#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;
}
#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;
}
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.
#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;
}
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;
}
terminal originally combined keyboard, screen, and a communication
line:
terminal streams usually imply a human user:
isatty(fd):
terminal behavior can be emulated in software:
graphical terminal emulators: xterm, rxvt, konsole, ...
physical serial consoles are useful on machines without a local
display:
serial communication:
terminal traffic needs much less bandwidth than images or video:
remote-access services such as sshd also provide a terminal interface
line discipline sits between terminal input/output and user programs
terminal-generated signals target the foreground process group
canonical line editing is also handled by the line discipline:
programs can change or disable special-character handling:
xterm receives keyboard events from X Window:
Ctrl-D does not close the terminal connection:
#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;
}
#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;
}
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.
session = set of processes sharing one sid (session identifier)
a session contains one or more process groups:
process group collects processes working on one job:
fork preserves sid and pgid
process can:
leadership restricts creating sessions and groups:
groups determine which processes terminal actions affect:
getsid(pid) and getpgid(pid) return session / group identifiers
setsid() creates a session
a successful setsid creates both a new session and its initial group
setsid detaches the process from its controlling terminal
setpgid(pid, pgid) changes group membership:
tcsetpgrp(fd, pgrp) assigns a terminal's foreground group
standard descriptors are not reliable handles for the controlling
terminal:
/dev/tty refers to the caller's controlling terminal
background caller of tcsetpgrp may trigger SIGTTOU for its group
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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.
usual terminal behavior:
crt and ncurses change terminal-driver settings for full-screen programs
termios provides C library functions for terminal control
direct terminal control is useful for small tasks:
canonical vs noncanonical input:
struct termios stores terminal settings:
tcsetattr timing options:
main struct termios fields:
IXON in c_iflag enables software flow control:
other input-processing examples:
c_oflag controls outgoing character processing
c_cflag mostly concerns the physical communication channel
c_lflag includes the main line-discipline controls:
ISIG enables terminal-generated signals:
TOSTOP controls output from background process groups:
ECHO controls whether typed characters appear on the screen
password-input example:
usual terminal-setting pattern: read -> modify a copy -> apply -> restore
clear selected flags with an inverted mask:
editing the struct changes only the process's copy
c_cc stores special-character codes at named indices
other c_cc indices and usual bindings:
newline itself is always code 10
disable an individual control character using the platform's disable value
noncanonical reads use VMIN and VTIME:
VMIN = 0, VTIME = 0:
with a nonzero VTIME:
further reading from the book:
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
#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;
}
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.
terminal emulation has two main forms:
pseudoterminal has two bidirectional endpoints:
create a pseudoterminal master:
prepare the slave before opening it:
unlockpt completes the preparation:
openpty can create and open both endpoints together:
openpty originated in BSD
#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;
}
#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;
}
#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;
}
#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;
}
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.
daemon = process intended to work without direct terminal interaction
keep standard descriptors open even if unused:
traditional daemonization separates the process from the terminal:
the two forks have different purposes:
without terminal output, diagnostics go to system logging:
openlog(ident, options, facility):
syslog(priority, format, ...) resembles printf:
closelog ends the program's connection to system logging
signals can serve as daemon-control requests:
#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