System Calls and Basic File I/O
Overview
This week marks the beginning of direct interaction with the kernel.
Students will learn what a system call (syscall) is, how it bridges user space and kernel space, and how errors are communicated via errno.
We then explore file descriptors, the foundation of Linux’s “everything is a file” philosophy, and practice with fundamental file-related system calls: creat, open, read, write, and close.
Key Concepts
-
System Calls
- Role of syscalls in OS design
- User mode vs. kernel mode
- Interrupts, traps, and context switching
syscallinterface vs. library wrappers (glibc)
-
Error Handling
- Return values (
-1convention) errnoglobal variable- Using
perror()andstrerror()
- Return values (
-
File Descriptors
- Concept of file descriptors (integers representing open files)
- Standard descriptors: stdin (0), stdout (1), stderr (2)
- “Everything is a file” in Unix: devices, pipes, sockets
-
Essential File System Calls
creat(),open(),read(),write(),close()- Flags:
O_RDONLY,O_WRONLY,O_RDWR,O_CREAT,O_APPEND, etc. - Permissions and the
umaskeffect - Differences between system calls and stdio (
fopen,fread, etc.)
Practice / Lab
-
Syscall Tracing
- Use
strace lsto observe syscalls in action - Identify
open,read,write,closein the trace
- Use
-
Error Handling
- Write a C program to open a non-existent file, print error with
perror
- Write a C program to open a non-existent file, print error with
-
File I/O Basics
- Write a program that:
- Creates a file with
creat() - Writes a string to it with
write() - Reads it back with
read()and prints to stdout - Closes the file descriptor
- Creates a file with
- Write a program that:
Homework
References & Resources
Required
- The Linux Programming Interface – Kerrisk, Ch. 4–5: System Calls & File I/O
- File Descriptor (Wiki)
- Handling a File by its Descriptor in C
- OS5 - File Descriptors, File Descriptor Table
Optional
- Beej’s Guide to Unix IPC (intro chapters)
- Linux Syscalls Table
- Linux manual page - open(2)
- Linux manual page - creat(3p)
- Linux manual page - read(2)
- Linux manual page - write(2)
- Linux manual page - close(2)
- Linux manual page - fcntl(2)
- Linux manual page - errno(3)
- errno – C library
- Reading and Writing Files in C, two ways (fopen vs. open)
Tools
strace,errno,perror,man
Quiz (Self-check)
- What distinguishes a system call from a regular library function?
- Which system calls are involved when reading a file from disk?
- What values are reserved for stdin, stdout, and stderr file descriptors?
- How does
errnoget set, and how should you properly print its meaning? - What is the difference between
openandcreat?