Linux System Calls Reference

Reference for Linux system calls. Essential for systems programming, covering file I/O, process management, memory operations, networking, and signal handling.

0xHabib
Updated 5 days ago
systems
advanced
systems
linux
system-calls
c
systems-programming
kernel
unix
File Operations
Essential

open

Required Headers:
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>
int open(const char *pathname, int flags, mode_t mode);

Open a file and return a file descriptor. Flags determine access mode and behavior.

Data Structures:
Common flags:
O_RDONLY    - Read only
O_WRONLY    - Write only  
O_RDWR      - Read/write
O_CREAT     - Create if doesn't exist
O_EXCL      - Fail if exists (with O_CREAT)
O_TRUNC     - Truncate to 0 bytes
O_APPEND    - Append mode
O_NONBLOCK  - Non-blocking I/O
Returns: File descriptor on success, -1 on error
Example:
#include <fcntl.h>
#include <sys/stat.h>

// Open file for reading
int fd = open("/etc/passwd", O_RDONLY);

// Create new file with permissions
int fd = open("newfile.txt", O_CREAT | O_WRONLY, 0644);
Common Errors:
ENOENT
EACCES
EMFILE

read

Required Headers:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

Read data from a file descriptor into a buffer.

Returns: Number of bytes read, 0 on EOF, -1 on error
Example:
#include <unistd.h>

char buffer[1024];
ssize_t bytes = read(fd, buffer, sizeof(buffer));
if (bytes > 0) {
    // Process the data
    buffer[bytes] = '';  // Null-terminate if text
}
Common Errors:
EBADF
EFAULT
EINTR

write

Required Headers:
#include <unistd.h>#include <string.h>
ssize_t write(int fd, const void *buf, size_t count);

Write data from a buffer to a file descriptor.

Returns: Number of bytes written, -1 on error
Example:
#include <unistd.h>
#include <string.h>

const char *msg = "Hello, World!
";
ssize_t bytes = write(STDOUT_FILENO, msg, strlen(msg));
Common Errors:
EBADF
EFAULT
ENOSPC

close

Required Headers:
#include <unistd.h>
int close(int fd);

Close a file descriptor, freeing it for reuse.

Returns: 0 on success, -1 on error
Example:
#include <unistd.h>
#include <stdio.h>

if (close(fd) == -1) {
    perror("close failed");
}
Common Errors:
EBADF
EINTR
EIO