System Calls & POSIX
System calls are the gateway between your program and the operating system kernel. Let’s understand how they work.User Space vs Kernel Space
The Transition Steps
- User Mode (Ring 3): Your program runs with limited privileges. It cannot access hardware directly.
- Library Call: You call
printf(). The C library (libc) formats the string and callswrite(). - System Call: The
write()wrapper puts arguments in CPU registers (e.g.,rax=1 for write) and executes a special instruction (syscallon x86-64). - Mode Switch: The CPU switches to Kernel Mode (Ring 0) and jumps to a predefined kernel entry point.
- Kernel Execution: The kernel validates arguments, checks permissions, and performs the operation (e.g., writing to the terminal buffer).
- Return: The kernel executes
sysret, switching the CPU back to User Mode and returning the result (number of bytes written or error).
Making System Calls
Via libc Wrappers
Direct System Calls
Error Handling
File Descriptors
Process Information
Environment Variables
Time and Date
Resource Limits
POSIX Portability
Common System Call Reference
| Category | System Calls |
|---|---|
| File I/O | open, close, read, write, lseek, pread, pwrite |
| File Info | stat, fstat, lstat, access, chmod, chown |
| Directories | mkdir, rmdir, chdir, getcwd, opendir, readdir |
| Processes | fork, exec*, wait, waitpid, exit, _exit |
| Signals | kill, sigaction, sigprocmask, pause, sigsuspend |
| Memory | mmap, munmap, mprotect, brk, sbrk |
| IPC | pipe, socketpair, shmget, semget, msgget |
| Network | socket, bind, listen, accept, connect, send, recv |
| Time | time, gettimeofday, clock_gettime, nanosleep |
| Misc | ioctl, fcntl, dup, dup2, select, poll, epoll |
Exercises
1
System Info Tool
Build a tool that prints comprehensive system information (CPU, memory, disk, network).
2
Safe Wrapper Library
Create a library of safe wrappers for common system calls with proper error handling and EINTR retry.
3
Syscall Tracer
Use
ptrace to build a simple strace-like tool.4
Resource Monitor
Build a tool that monitors a process’s resource usage over time.
Next Up
Concurrency
Process and thread programming