Lesson 15 of 15

sys_write

The write() System Call

write(fd, buf, count) is syscall number 1 on Linux x86-64. It writes count bytes from buf to the file descriptor fd. The return value is the number of bytes written, or -1 on error.

ssize_t write(int fd, const void *buf, size_t count);

In the kernel, sys_write dispatches to the file's write method via the VFS layer. For file descriptors 1 (stdout) and 2 (stderr), it ends up in the terminal driver which sends bytes to the screen.

Your Implementation

Write int sys_write(int fd, const char *buf, int len):

  • If fd is 1 (stdout) or 2 (stderr): write all bytes with putchar, return len
  • Otherwise: return -1 (EBADF — bad file descriptor)
int sys_write(int fd, const char *buf, int len) {
    if (fd == 1 || fd == 2) {
        for (int i = 0; i < len; i++) putchar(buf[i]);
        return len;
    }
    return -1;
}

Why Separate fd 1 and 2?

Real write does not treat stdout and stderr differently at the syscall level — both go to their respective file descriptions. We treat them identically because in our simulation both write to the same output stream.

Your Task

Implement sys_write that writes to stdout/stderr (fd 1/2) and returns -1 for all other file descriptors.

TCC compiler loading...
Loading...
Click "Run" to execute your code.