Reformat code

This commit is contained in:
Fabio Scotto di Santolo
2025-07-04 10:39:07 +02:00
parent 2bea38d7fc
commit dd53e83af6
28 changed files with 632 additions and 524 deletions

16
.clang-format Normal file
View File

@@ -0,0 +1,16 @@
BasedOnStyle: LLVM
IndentWidth: 8
TabWidth: 8
UseTab: Always
BreakBeforeBraces: Linux
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortFunctionsOnASingleLine: InlineOnly
ColumnLimit: 80
AlignConsecutiveDeclarations: false
AlignConsecutiveAssignments: false
AlignEscapedNewlines: Left
AlignOperands: false
IndentCaseLabels: false
SpaceBeforeParens: ControlStatements

View File

@@ -9,6 +9,7 @@ Welcome! This is a collection of chapter summaries from the book **Linux System
- [Chapter 3 Buffered I/O](chp3/README.md)
- [Chapter 4 Advanced File I/O](chp4/README.md)
- [Chapter 5 - Process Management](chp5/README.md)
- [Chapter 6 - Advanced Process Management](chp6/README.md)
- [Exercises](exercises/README.md)
> Each file contains an English summary of the chapter's key concepts.

View File

@@ -2,7 +2,8 @@
#include <stdlib.h>
#include <unistd.h>
int main(void) {
int main(void)
{
int fd = open("test.txt", O_CREAT | O_RDWR);
// close(fd);
return EXIT_SUCCESS;

View File

@@ -1,7 +1,7 @@
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{

View File

@@ -1,12 +1,13 @@
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int fd;
fd = open("test.txt", O_CREAT | O_EXCL, S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
fd = open("test.txt", O_CREAT | O_EXCL,
S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);
if (fd == -1)
perror("open");
close(fd);

View File

@@ -6,7 +6,8 @@
#define _XOPEN_SOURCE 500
#include <unistd.h>
int main(void) {
int main(void)
{
printf("Try to open file read.txt\n");
int fd = open("read.txt", O_RDONLY);
if (fd == -1) {
@@ -22,7 +23,8 @@ int main(void) {
return -1;
}
// cannot rewind cursor at the start file because pread use "bytes_read_total" for position
// cannot rewind cursor at the start file because pread use
// "bytes_read_total" for position
printf("File size of %d bytes\n", len);
@@ -32,9 +34,12 @@ int main(void) {
size_t bytes_read_total = 0;
ssize_t ret;
while (bytes_read_total < len && (ret = pread(fd, buf, len - bytes_read_total, bytes_read_total)) != -1) {
while (bytes_read_total < len &&
(ret = pread(fd, buf, len - bytes_read_total,
bytes_read_total)) != -1) {
if (ret == -1) {
if (errno == EINTR) continue;
if (errno == EINTR)
continue;
perror("Failed to read read.txt");
break;
}

View File

@@ -5,7 +5,8 @@
#include <string.h>
#include <unistd.h>
int main(void) {
int main(void)
{
printf("Try to open file read.txt\n");
int fd = open("read.txt", O_RDONLY);
if (fd == -1) {
@@ -31,9 +32,12 @@ int main(void) {
size_t bytes_read_total = 0;
ssize_t ret;
while (bytes_read_total < len && (ret = read(fd, buf + bytes_read_total, len - bytes_read_total)) != 0) {
while (bytes_read_total < len &&
(ret = read(fd, buf + bytes_read_total,
len - bytes_read_total)) != 0) {
if (ret == -1) {
if (errno == EINTR) continue;
if (errno == EINTR)
continue;
perror("Failed to read read.txt");
break;
}

View File

@@ -1,7 +1,8 @@
#include <unistd.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
int main(void)
{
int ret;
ret = truncate("./pirate.txt", 45);

View File

@@ -1,10 +1,11 @@
#include <poll.h>
#include <stdio.h>
#include <unistd.h>
#include <poll.h>
#define TIMEOUT 5 /* poll timeout, in seconds */
int main(void) {
int main(void)
{
struct pollfd fds[2];
int ret;

View File

@@ -6,7 +6,8 @@
#define TIMEOUT 5
#define BUF_LEN 1024
int main(void) {
int main(void)
{
struct timeval tv;
fd_set readfds;
int ret;
@@ -20,13 +21,7 @@ int main(void) {
tv.tv_usec = 0;
/* All right, now block! */
ret = select(
STDIN_FILENO + 1,
&readfds,
NULL,
NULL,
&tv
);
ret = select(STDIN_FILENO + 1, &readfds, NULL, NULL, &tv);
if (ret == -1) {
perror("select");
return 1;

View File

@@ -1,11 +1,11 @@
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#define FILE_NUMBER 3
#define FILENAME_MAX_LEN 10
@@ -15,7 +15,8 @@
int create_tmp_file(char *filename);
void cleanup(char *filenames[]);
int main(void) {
int main(void)
{
int exit_code = 0;
char *filename_template = "test%d.txt";
char *filenames[FILE_NUMBER] = {NULL};
@@ -23,7 +24,8 @@ int main(void) {
// Create a bunch of number ephemeral files
for (int i = 0; i < FILE_NUMBER; i++) {
char *filename = (char *)malloc(FILENAME_MAX_LEN*sizeof(char));
char *filename =
(char *)malloc(FILENAME_MAX_LEN * sizeof(char));
if (!filename) {
perror("malloc failed");
exit_code = -1;
@@ -34,11 +36,13 @@ int main(void) {
printf("Opening file %s...\n", filename);
fds[i] = create_tmp_file(filename);
if (fds[i] == -1) {
fprintf(stderr, "Error to open file %s: %s\n", filename, strerror(errno));
fprintf(stderr, "Error to open file %s: %s\n", filename,
strerror(errno));
exit_code = -1;
goto exit;
}
printf("Open file %s with file descriptor %d\n", filename, fds[i]);
printf("Open file %s with file descriptor %d\n", filename,
fds[i]);
// write something in the files
dprintf(fds[i], "Hello I am %s\n", filename);
@@ -50,21 +54,17 @@ int main(void) {
FD_SET(fds[i], &readfds);
}
struct timeval *timeout = (struct timeval *)malloc(sizeof(struct timeval));
struct timeval *timeout =
(struct timeval *)malloc(sizeof(struct timeval));
timeout->tv_sec = TIMEOUT;
timeout->tv_usec = 0;
/* This function do not work with regular files because for the operating system,
* a regular file is ready always.
* This example is wrong the best way to use select() is with socket, pipe or other channel types.
/* This function do not work with regular files because for the
* operating system, a regular file is ready always. This example is
* wrong the best way to use select() is with socket, pipe or other
* channel types.
*/
int ret = select(
FILE_NUMBER + 1,
&readfds,
NULL,
NULL,
timeout
);
int ret = select(FILE_NUMBER + 1, &readfds, NULL, NULL, timeout);
if (ret == -1) {
fprintf(stderr, "Error to select: %s\n", strerror(errno));
@@ -82,7 +82,8 @@ int main(void) {
char buf[BUF_LEN + 1];
int len = read(fd, buf, BUF_LEN);
if (len == -1) {
fprintf(stderr, "Error reading file %s: %s\n", filenames[i], strerror(errno));
fprintf(stderr, "Error reading file %s: %s\n",
filenames[i], strerror(errno));
exit_code = 1;
goto exit;
}
@@ -99,7 +100,8 @@ exit:
int fd = fds[i];
printf("Close file with file descriptor %d\n", fd);
if (close(fd) == -1) {
fprintf(stderr, "Error to close file %d: %s\n", fd, strerror(errno));
fprintf(stderr, "Error to close file %d: %s\n", fd,
strerror(errno));
}
}
@@ -112,7 +114,8 @@ exit:
return exit_code;
}
int create_tmp_file(char *filename) {
int create_tmp_file(char *filename)
{
int fd = open(filename, O_CREAT | O_EXCL | O_RDWR, 0644);
if (fd == -1) {
return -1;
@@ -120,11 +123,13 @@ int create_tmp_file(char *filename) {
return fd;
}
void cleanup(char *filenames[]) {
void cleanup(char *filenames[])
{
for (int j = 0; j < FILE_NUMBER; j++) {
if (filenames[j] != NULL) {
if (remove(filenames[j]) == -1)
fprintf(stderr, "Failed to remove %s: %s\n", filenames[j], strerror(errno));
fprintf(stderr, "Failed to remove %s: %s\n",
filenames[j], strerror(errno));
free(filenames[j]);
filenames[j] = NULL;
}

View File

@@ -1,6 +1,7 @@
#include <stdio.h>
int main(void) {
int main(void)
{
FILE *in, *out;
struct pirate {
char name[100]; /* real name */
@@ -35,6 +36,7 @@ int main(void) {
perror("fclose");
return 1;
}
printf("name=\"%s\" booty=%lu beard_len=%u\n", p.name, p.booty, p.beard_len);
printf("name=\"%s\" booty=%lu beard_len=%u\n", p.name, p.booty,
p.beard_len);
return 0;
}

View File

@@ -1,7 +1,8 @@
#include<stdio.h>
#include <limits.h>
#include <stdio.h>
int main(void) {
int main(void)
{
printf("Limit buffer size is %u bytes.\n", LINE_MAX);
printf("Buffer size is %u bytes.\n", BUFSIZ);
}

View File

@@ -1,10 +1,10 @@
#include <fcntl.h>
#include <linux/fs.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/fs.h>
#include <sys/stat.h>
#include <sys/types.h>
/* get_block - for the file associated with the given fd, returns
* the physical block mapping to logical_block
@@ -22,7 +22,8 @@ int get_nr_blocks(int fd);
*/
void print_blocks(int fd);
int main(int argc, char *argv[]) {
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "usage: %s <file>\n", argv[0]);
return 1;
@@ -38,7 +39,8 @@ int main(int argc, char *argv[]) {
return 0;
}
int get_block(int fd, int logical_block) {
int get_block(int fd, int logical_block)
{
int ret = ioctl(fd, FIBMAP, &logical_block);
if (ret < 0) {
perror("ioctl");
@@ -47,7 +49,8 @@ int get_block(int fd, int logical_block) {
return logical_block;
}
int get_nr_blocks(int fd) {
int get_nr_blocks(int fd)
{
struct stat buf;
int ret = fstat(fd, &buf);
if (ret < 0) {
@@ -57,7 +60,8 @@ int get_nr_blocks(int fd) {
return buf.st_blocks;
}
void print_blocks(int fd) {
void print_blocks(int fd)
{
int nr_blocks = get_nr_blocks(fd);
if (nr_blocks < 0) {
fprintf(stderr, "get_nr_blocks failed!\n");
@@ -79,7 +83,8 @@ void print_blocks(int fd) {
fprintf(stderr, "get_block failed!\n");
return;
}
if (!phys_block) continue;
if (!phys_block)
continue;
printf("(%u, %u) ", i, phys_block);
}

View File

@@ -1,15 +1,16 @@
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/types.h>
/* get_inode - returns the inode of the file associated
* with the given file descriptor, or -1 on failure.
*/
int get_inode(int fd);
int main(int argc, char *argv[]) {
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "usage: %s <file>\n", argv[0]);
return 1;
@@ -27,7 +28,8 @@ int main(int argc, char *argv[]) {
return 0;
}
int get_inode(int fd) {
int get_inode(int fd)
{
struct stat buf;
int ret = fstat(fd, &buf);

View File

@@ -1,11 +1,12 @@
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "usage: %s <file>\n", argv[0]);

View File

@@ -1,11 +1,12 @@
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
int main(void) {
int main(void)
{
char foo[48], bar[51], baz[49];
int fd = open("buccaneer.txt", O_RDONLY);
if (fd == -1) {

View File

@@ -1,19 +1,18 @@
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
int main(void) {
int main(void)
{
struct iovec iov[3];
char *buf[] = {
"The term buccaneer comes from the word boucan.\n",
char *buf[] = {"The term buccaneer comes from the word boucan.\n",
"A boucan is a wooden frame used for cooking meet.\n",
"Buccaneer is the West Indies name for a pirate.\n"
};
"Buccaneer is the West Indies name for a pirate.\n"};
int fd = open("buccaneer.txt", O_WRONLY | O_CREAT | O_TRUNC);
if (fd == -1) {

View File

@@ -1,12 +1,13 @@
#include <stdio.h>
#include <stdlib.h>
void out(void) {
void out(void)
{
printf("atexit() succeeded!\n");
}
int main(void) {
int main(void)
{
if (atexit(out)) {
fprintf(stderr, "atexit() failed\n");
return 1;

View File

@@ -1,13 +1,14 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define NR_OPEN 1048576
int main(void) {
int main(void)
{
// create new process
pid_t pid = fork();
if (pid == -1) {
@@ -18,10 +19,12 @@ int main(void) {
}
// create a new session and process group
if (setsid() == -1) return -1;
if (setsid() == -1)
return -1;
// set the working directory to the root directory
if (chdir("/") == -1) return -1;
if (chdir("/") == -1)
return -1;
// close all open files--NR_OPEN is overkill, but works
for (int i = 0; i < NR_OPEN; i++) {

View File

@@ -2,7 +2,8 @@
#define _XOPEN_SOURCE 500
#include <unistd.h>
int main(void) {
int main(void)
{
printf("My session id=%d\n", getsid(0));
printf("My process group id=%d\n", getpgid(0));
return 0;

View File

@@ -1,9 +1,9 @@
#include <stdio.h>
#define _XOPEN_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
/* my_system - synchronously spawns and waits for the command
* "/bin/sh -c <cmd>".
@@ -13,7 +13,8 @@
*/
int my_system(const char *);
int main(int argc, char *argv[]) {
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "usage: %s <command>", argv[0]);
return EXIT_FAILURE;
@@ -38,7 +39,8 @@ int main(int argc, char *argv[]) {
return status;
}
int my_system(const char *cmd) {
int my_system(const char *cmd)
{
pid_t pid = fork();
if (pid == -1) {
return -1;

View File

@@ -1,9 +1,10 @@
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
int main(void)
{
if (!fork())
return 1;
@@ -16,10 +17,12 @@ int main(void) {
printf("pid=%d\n", pid);
if (WIFEXITED(status))
printf("Normal termination with exit status=%d\n", WEXITSTATUS(status));
printf("Normal termination with exit status=%d\n",
WEXITSTATUS(status));
if (WIFSIGNALED(status))
printf("Killed by signal=%d%s\n", WTERMSIG(status), WCOREDUMP(status) ? " (dumped core)" : "");
printf("Killed by signal=%d%s\n", WTERMSIG(status),
WCOREDUMP(status) ? " (dumped core)" : "");
if (WIFSTOPPED(status))
printf("Stopped by signal=%d\n", WSTOPSIG(status));

52
chp6/README.md Normal file
View File

@@ -0,0 +1,52 @@
# 📘 Chapter 6 Advanced Process Management (Summary)
**From _Linux System Programming_ by Robert Love, 2nd Ed.**
---
## 🔄 Process Scheduling
- The kernel scheduler selects **runnable processes** (those not blocked on I/O, etc.).
- Goals: **maximize CPU utilization**, minimize wait time, and ensure fairness :contentReference[oaicite:1]{index=1}.
- Covers **preemptive scheduling**, **timeslices**, and the Linux **Completely Fair Scheduler (CFS)**.
- Explains **processor affinity** and CPU sets: binding processes to specific CPUs for cache performance :contentReference[oaicite:2]{index=2}.
## 🧭 Yielding the Processor
- `sched_yield()` lets a running process give up the CPU voluntarily.
- Useful in busy-wait loops or when expecting immediate CPU from others :contentReference[oaicite:3]{index=3}.
## 🎚️ Priorities & Nice Values
- Processes can adjust their priority using **`nice()`**, where lower nice = higher priority.
- Real-time scheduling policies (`SCHED_FIFO`, `SCHED_RR`) grant stronger priority guarantees for time-sensitive tasks :contentReference[oaicite:4]{index=4}.
## 🧠 Processor Affinity
- **Get/set CPU affinity** with `sched_getaffinity()` and `sched_setaffinity()`.
- Ensures cache affinity, reducing context-switch overhead :contentReference[oaicite:5]{index=5}.
## ⏱️ Real-Time Scheduling
- Differences between **hard** and **soft real-time** systems.
- Configurable policies: `SCHED_FIFO`, `SCHED_RR`, with real-time priority range 099 :contentReference[oaicite:6]{index=6}.
- Care needed: real-time tasks can lead to starvation of normal tasks.
## 🔒 Resource Limits
- Kernel enforces per-process limits via `setrlimit()`/`getrlimit()`:
- CPU usage (`RLIMIT_CPU`)
- File sizes (`RLIMIT_FSIZE`)
- Number of open files, memory, etc. :contentReference[oaicite:7]{index=7}.
- Helps contain rogue or misbehaving processes, essential for robustness.
---
## ✅ Why It Matters
Advanced control over process scheduling, priorities, affinity, and resource limits is critical for writing:
- Real-time or latency-sensitive applications
- High-performance servers that benefit from core binding
- Robust daemons that avoid resource exhaustion
This chapter equips systems programmers with the tools to finely tune how tasks interact with the kernel scheduler and manage system impact.
---
## 📚 References
- *Linux System Programming*, 2nd Ed. — Robert Love
- `man 2 sched_setscheduler`, `man 2 setrlimit`, `man 2 sched_getaffinity`
- Wikipedia: [Completely Fair Scheduler](https://en.wikipedia.org/wiki/Completely_Fair_Scheduler) :contentReference[oaicite:8]{index=8}

View File

@@ -1,13 +1,13 @@
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#define BUFF_LEN 4096
int main(int argc, char *argv[]) {
int main(int argc, char *argv[])
{
// Check number of arguments
if (argc < 3) {
fprintf(stderr, "Usage: %s SOURCE DEST\n", argv[0]);
@@ -25,7 +25,8 @@ int main(int argc, char *argv[]) {
return EXIT_FAILURE;
}
// Open destination file in write mode, if exists trunc file otherwise create a new file
// Open destination file in write mode, if exists trunc file otherwise
// create a new file
int dstfd = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dstfd == -1) {
perror("Failed open destination file");
@@ -41,7 +42,8 @@ int main(int argc, char *argv[]) {
while ((read_bytes = read(srcfd, buff, BUFF_LEN)) != 0) {
if (read_bytes == -1) {
// There is an error for reading source file
if (errno == EINTR) continue;
if (errno == EINTR)
continue;
perror("Failed to read source file");
exit_code = EXIT_FAILURE;
break;

View File

@@ -1,8 +1,9 @@
#include "tree.h"
#include <stdio.h>
#include <stdlib.h>
#include "tree.h"
int main(int argc, char *argv[]) {
int main(int argc, char *argv[])
{
const char *path = (argc > 1) ? argv[1] : ".";
if (print_tree(path, 0) == -1) {
@@ -12,4 +13,3 @@ int main(int argc, char *argv[]) {
return EXIT_SUCCESS;
}

View File

@@ -1,27 +1,32 @@
#include "tree.h"
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include "tree.h"
int print_tree(const char *path, int depth) {
int print_tree(const char *path, int depth)
{
DIR *dir = opendir(path);
if (!dir) return -1;
if (!dir)
return -1;
struct dirent *entry;
while ((entry = readdir(dir)) != NULL) {
// Skip . and ..
if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0)
if (strcmp(entry->d_name, ".") == 0 ||
strcmp(entry->d_name, "..") == 0)
continue;
for (int i = 0; i < depth; i++) printf(" ");
for (int i = 0; i < depth; i++)
printf(" ");
printf("|-- %s\n", entry->d_name);
// Construct full path
char full_path[4096];
snprintf(full_path, sizeof(full_path), "%s/%s", path, entry->d_name);
snprintf(full_path, sizeof(full_path), "%s/%s", path,
entry->d_name);
struct stat st;
if (stat(full_path, &st) == 0 && S_ISDIR(st.st_mode)) {
@@ -32,4 +37,3 @@ int print_tree(const char *path, int depth) {
closedir(dir);
return 0;
}

View File

@@ -4,4 +4,3 @@
int print_tree(const char *path, int depth);
#endif