Skip to content
System Programming
Basic IO

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
    • syscall interface vs. library wrappers (glibc)
  • Error Handling

    • Return values (-1 convention)
    • errno global variable
    • Using perror() and strerror()
  • 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 umask effect
    • Differences between system calls and stdio (fopen, fread, etc.)

Practice / Lab

  • Syscall Tracing

    • Use strace ls to observe syscalls in action
    • Identify open, read, write, close in the trace
  • Error Handling

    • Write a C program to open a non-existent file, print error with perror
  • 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

Homework


References & Resources

Required

Optional

Tools

  • strace, errno, perror, man

Quiz (Self-check)

  1. What distinguishes a system call from a regular library function?
  2. Which system calls are involved when reading a file from disk?
  3. What values are reserved for stdin, stdout, and stderr file descriptors?
  4. How does errno get set, and how should you properly print its meaning?
  5. What is the difference between open and creat?