CSE Roadmap

Core tier · about 3 hours · 8 parts

Part 4 of 8 · 2 min read

From C

Think of a telephone operator who turns a plain request into the exact buttons that a switchboard needs. The C library does that for system calls. The analogy stops in one place: an operator is a person, and the library is code that runs inside the program's own address space.

In plain words: Programs rarely use raw system calls. They use the C library, which wraps each call in a function. The library also offers many functions that are not system calls, such as printf and malloc. They may or may not call the kernel inside.

An API (application programming interface) is a set of functions a programmer may call. The common API on Unix and Linux is called POSIX. A program written to POSIX can be compiled on many systems. A single API function may use one system call, several, or none.

The key lines.

By convention, a system call wrapper returns -1 on failure. The reason is in a global variable named errno, which holds a small number. The function strerror turns it into text. Check every call, since a failure is common: files vanish, disks fill, and descriptors close.

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

int main(void) {
    int fd = open("/no/such/file.txt", O_RDONLY);
    if (fd == -1) {
        printf("open failed, errno = %d (%s)\n", errno, strerror(errno));
        return 1;
    }
    close(fd);
    return 0;
}

Output:

open failed, errno = 2 (No such file or directory)

A second example writes to a descriptor that is not open. The kernel catches the mistake, and the wrapper reports it:

ssize_t n = write(99, "x", 1);
if (n == -1)
    printf("write failed: errno=%d (%s)\n", errno, strerror(errno));

Output:

write failed: errno=9 (Bad file descriptor)

Two points to remember. First, errno is only meaningful right after a call fails. A later successful call may leave an old value there, so read it at once. Second, a wrapper for some calls returns a count, such as the number of bytes written, and the count may be smaller than requested. Always use the returned value.

Common mistake

Ignoring the return value of read or write. A call can succeed but transfer fewer bytes than asked, or fail with -1. Code that assumes everything worked loses data without any message.

Check yourself: 1. What does a system call wrapper return on failure, and where is the reason? 2. Is printf a system call? 3. Why must errno be read straight after the failing call?