System Programming Fundamentals
Open in the Padhaiko app1.1 Overview of system programming and its role in networking
System programming is the discipline of writing low-level software that interacts directly with the operating system kernel, hardware abstractions, and core system resources—such as processes, memory, file descriptors, timers, and network interfaces—rather than relying solely on high-level application frameworks.
System Programming vs. Application Programming
- Application Programming builds end-user software (such as web apps, spreadsheets, or mobile UIs) on top of high-level abstractions, managed runtimes, and third-party libraries.
- System Programming builds the foundational infrastructure—operating system utilities, compilers, daemons, database engines, container runtimes, and high-performance network servers—using direct Operating System APIs (POSIX/Linux system calls) with deterministic control over memory layout, concurrency, and I/O latency.
Why System Programming Is Essential in Networking
Modern networked systems (web servers, load balancers, routers, proxies, DNS resolvers, and distributed databases) must handle thousands or millions of simultaneous connections with microsecond-level responsiveness. System programming provides the exact tools required:
- Direct Socket and Protocol Control: Applications need explicit access to TCP/UDP sockets, raw IP packets, socket options (
SO_REUSEADDR,TCP_NODELAY), and kernel buffers to implement custom protocols or tune throughput. - Low-Overhead I/O Multiplexing: High-concurrency servers rely on kernel event notification primitives (
select,poll,epoll) and non-blocking file descriptors to monitor thousands of sockets inside a single thread. - Zero-Copy and Buffer Management: System calls like
sendfile()andmmap()minimize expensive memory copies between kernel buffers and user-space memory when serving large static files or streaming media. - Process and Thread Orchestration: Network daemons must fork worker processes, manage thread pools, synchronize shared caches using mutexes or semaphores, and handle asynchronous OS signals (
SIGTERM,SIGCHLD,SIGPIPE) cleanly without dropping active clients.
1.2 User space versus kernel space
Modern CPUs enforce hardware-level privilege separation using protection rings (on x86-64, Ring 0 for the OS kernel and Ring 3 for user applications; on ARM64, EL1 vs. EL0). The operating system divides virtual memory and CPU execution into two strictly isolated domains: Kernel Space and User Space.
Kernel Space and User Space
- Kernel Space (Supervisor / Privileged Mode): The protected region of virtual memory and CPU privilege level reserved for the OS kernel, device drivers, protocol stacks (TCP/IP), and the Virtual File System (VFS). Code executing in kernel space has unrestricted access to physical RAM, CPU control registers, hardware interrupts, and I/O controllers.
- User Space (Unprivileged Mode): The isolated execution environment where normal user applications (browsers, compilers, C programs, network servers) run. Each user process sees its own private virtual address space and cannot directly touch kernel memory, hardware ports, or another process's memory.
| Aspect | User Space | Kernel Space |
|---|---|---|
| CPU Privilege Level | Unprivileged mode (e.g., Ring 3 on x86-64) | Privileged / Supervisor mode (e.g., Ring 0 on x86-64) |
| Memory Isolation | Private virtual address space per process; isolated by MMU | Shared kernel virtual address space mapped across all processes |
| Hardware Access | Prohibited; must request services via system calls | Full direct access to CPU, MMU, NIC, and disk controllers |
| Fault Impact | Crash (e.g., segmentation fault) terminates only that process | Unhandled bug causes a kernel panic, crashing the entire OS |
| Typical Components | Shells, web servers (nginx), libc, Python/C user programs | Process scheduler, VFS, TCP/IP stack, memory manager, drivers |
Mode Switching (Context Transition)
Because user programs cannot read a disk sector or transmit a network frame directly, they must cross the boundary into kernel space using a software interrupt or trap instruction (such as syscall on x86-64 or svc on ARM64):
- The user process places the system call number and arguments into designated CPU registers.
- The CPU executes the
syscallinstruction, which switches the hardware privilege level from User Mode to Kernel Mode and jumps to a trusted kernel entry point. - The kernel validates every user-supplied pointer and permission check, performs the requested hardware/resource operation, and places the return value in a register.
- The kernel executes
sysret(oreret), dropping privilege back to User Mode and resuming the user program.
1.3 System calls and standard libraries
A system call (syscall) is the programmatic interface through which a user-space process requests a privileged service from the operating system kernel. In practice, C programs rarely invoke raw CPU syscall trap instructions directly; instead, they call wrapper functions provided by the C Standard Library (libc, such as glibc or musl on Linux).
System Calls vs. Library Functions
- System Call: A direct entry point into the OS kernel (e.g.,
read(),write(),open(),fork(),socket()). Every invocation crosses the user-kernel boundary and executes inside kernel space. - Standard Library Function: A reusable user-space routine packaged in
libc(e.g.,strlen(),malloc(),printf(),fopen()). A library function may execute entirely in user space (such asstrlen()), buffer data in user space before occasionally calling a syscall (such asprintf()orfread()), or act as a thin wrapper around a single syscall (such aswrite()).
| Aspect | System Calls | Standard Library Functions |
|---|---|---|
| Execution Domain | Crosses into Kernel Space on every call | Runs primarily in User Space; calls syscalls only when needed |
| Buffering | Unbuffered at user level (kernel may still cache pages) | User-space buffered (stdio buffer, typically 4 KB–8 KB) |
| Error Reporting | Returns -1 and sets thread-local errno | Varies (NULL, EOF, or negative value; errno set if syscall failed) |
| Portability | OS-specific / POSIX-specific | Portable across all platforms implementing ISO C (stdio.h, stdlib.h) |
| Overhead per Call | Higher (requires user-kernel mode switch) | Very low for small operations absorbed by user-space buffers |
Error Handling with errno and perror()
When a POSIX system call succeeds, it returns 0 or a non-negative integer (such as a file descriptor or byte count). When it fails, it returns -1 and stores a positive integer error code in the global (thread-local) variable errno (defined in <errno.h>).
| Constant | Typical Meaning | Common Cause |
|---|---|---|
EACCES | Permission denied | Opening a protected file or binding a privileged port (< 1024) without root |
ENOENT | No such file or directory | Target path passed to open() or execve() does not exist |
EINTR | Interrupted system call | A blocking syscall (like read() or accept()) was interrupted by a signal |
EAGAIN / EWOULDBLOCK | Resource temporarily unavailable | Non-blocking socket/fd has no data ready to read right now |
EBADF | Bad file descriptor | Using a closed, negative, or uninitialized file descriptor |
ECONNREFUSED | Connection refused | Client connect() reached a host where no server is listening on that port |
1.4 File descriptors and low-level I/O
In Unix and Linux, "everything is a file" (or behaves like a file interface): regular disk files, terminal consoles, pipes, character devices, and network sockets are all accessed through small non-negative integers called file descriptors (fds).
File Descriptor
A file descriptor (fd) is a per-process, non-negative integer (0, 1, 2, ...) that acts as an index into the process's File Descriptor Table inside the kernel. Each entry points to an Open File Table entry (storing the file offset, access mode, and status flags), which in turn points to the kernel's v-node / i-node (or socket structure) representing the underlying resource.
Standard File Descriptors
By POSIX convention, every newly launched process inherits three pre-opened file descriptors from its parent shell:
| FD Number | POSIX Symbolic Constant (<unistd.h>) | stdio Stream | Default Target |
|---|---|---|---|
0 | STDIN_FILENO | stdin | Keyboard / terminal input |
1 | STDOUT_FILENO | stdout | Terminal screen output |
2 | STDERR_FILENO | stderr | Terminal error output (unbuffered) |
Kernel Three-Table File Representation
Understanding the separation of three kernel data structures explains how fork(), dup(), and dup2() work:
Process FD Table (Per-Process) Open File Table (Kernel-Wide) Inode / Socket Table
+----+-------+---------------+ +---------------------------+ +---------------------+
| fd | flags | file ptr | ----> | mode: O_RDWR | -----> | File metadata/data |
+----+-------+---------------+ | offset: 1024 | | (inode #4821, size) |
| 0 | ... | -> tty_in | | refcount: 1 | +---------------------+
| 1 | ... | -> tty_out | +---------------------------+
| 2 | ... | -> tty_err |
| 3 | ... | --------------+----^
+----+-------+---------------+- Lowest-Available FD Rule: Whenever a process opens a new file or socket (
open(),socket(),accept(),pipe()), POSIX guarantees the kernel assigns the lowest unused non-negative integer in that process's FD table (for instance,3if0, 1, 2are already open).
Core Low-Level POSIX I/O System Calls
Low-level unbuffered I/O uses five fundamental calls declared in <fcntl.h> and <unistd.h>:
| System Call | Signature Summary | Purpose & Return Value |
|---|---|---|
open() | int open(const char *path, int oflag, ... /* mode_t mode */); | Opens or creates a file; returns lowest free fd (>= 0) or -1 on error. Flags include O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_TRUNC, O_APPEND, O_NONBLOCK. |
read() | ssize_t read(int fd, void *buf, size_t count); | Reads up to count bytes from fd into buf; returns bytes read (0 at EOF, -1 on error). Note: may return fewer bytes than requested (short read). |
write() | ssize_t write(int fd, const void *buf, size_t count); | Writes up to count bytes from buf to fd; returns bytes written or -1 on error. Always loop on sockets/pipes to handle partial writes. |
lseek() | off_t lseek(int fd, off_t offset, int whence); | Repositions the open file offset (SEEK_SET, SEEK_CUR, SEEK_END); fails with ESPIPE on pipes and sockets. |
close() | int close(int fd); | Releases fd back to the process FD table and decrements the open file entry's reference count; returns 0 or -1. |
dup() / dup2() | int dup(int oldfd); / int dup2(int oldfd, int newfd); | Duplicates an fd so both integers share the same Open File Table entry (and file offset). dup2() atomically closes newfd (if open) and duplicates oldfd onto newfd (used for shell I/O redirection). |
1.5 Linux/Unix system architecture overview
A Linux/Unix operating system is organized into cleanly decoupled layers so that user programs remain portable across diverse storage, CPU, and networking hardware.
+-----------------------------------------------------------------------+
| USER SPACE |
| [ Shells, Daemons, Network Servers ] [ C Standard Library (libc) ] |
+-----------------------------------------------------------------------+
| System Call Interface (SCI: syscall / libc) |
+-----------------------------------------------------------------------+
| KERNEL SPACE |
| +-----------------+ +--------------------+ +--------------------+ |
| | Process & | | Virtual File | | Network Stack | |
| | Thread Scheduler| | System (VFS) | | (Sockets, TCP/UDP, | |
| | (fork, exec) | | (ext4, procfs) | | IP, Netfilter) | |
| +-----------------+ +--------------------+ +--------------------+ |
| +-----------------+ +--------------------+ +--------------------+ |
| | Memory Manager | | IPC Subsystem | | Device Drivers | |
| | (VM, mmap, swap)| | (pipes, shm, msg) | | (NIC, NVMe, tty) | |
| +-----------------+ +--------------------+ +--------------------+ |
+-----------------------------------------------------------------------+
| HARDWARE: CPU & MMU | Physical RAM | NIC (Ethernet/WiFi) | Disk |
+-----------------------------------------------------------------------+Key Kernel Subsystems Relevant to Network & Systems Programming
- System Call Interface (SCI): Validates arguments, checks permissions, and dispatches traps (
read,socket,fork,epoll_wait) to the proper kernel subsystem. - Process & Scheduler Subsystem: Manages
task_structdescriptors, process creation (fork/clone), virtual-CPU time-slicing, states (RUNNING,INTERRUPTIBLE,ZOMBIE), and signal delivery. - Memory Management Subsystem: Implements virtual memory paging, copy-on-write (
fork()), page cache (buffering file I/O in RAM), and memory-mapped files (mmap()). - Virtual File System (VFS): Provides a uniform
open/read/write/closeabstraction over concrete file systems (ext4,xfs), pseudo-filesystems (/proc,/sys), pipes, and sockets. - Networking Subsystem: Implements the BSD Socket layer, transport protocols (TCP, UDP), network layer (IPv4/IPv6, routing tables), and link-layer queueing disciplines before handing frames to the NIC device driver.
- Device Drivers: Hardware-specific kernel modules that program device registers, service interrupts, and run DMA transfers between peripheral hardware (disks, network cards) and kernel memory.
Worked Examples
Tracing File Descriptor Allocation and Redirection with dup2()
A newly started Linux process has standard file descriptors 0 (stdin), 1 (stdout), and 2 (stderr) open. It executes the following sequence of system calls (assume every call succeeds):
fd1 = open("input.txt", O_RDONLY);fd2 = open("output.log", O_WRONLY | O_CREAT | O_TRUNC, 0644);close(fd1);fd3 = open("err.log", O_WRONLY | O_CREAT | O_APPEND, 0644);dup2(fd2, STDOUT_FILENO);close(fd2);
Trace the integer values assigned to fd1, fd2, and fd3, and determine which file printf("OK\n") writes to afterward.
Initial State: At process startup, descriptors 0, 1, and 2 are already occupied by stdin, stdout, and stderr.
Applying the Lowest-Available FD Rule:
fd1 = open("input.txt", ...)receives the lowest free integer:fd1 = 3. Open set:{0, 1, 2, 3}.fd2 = open("output.log", ...)receives the next lowest free integer:fd2 = 4. Open set:{0, 1, 2, 3, 4}.close(fd1)frees descriptor3. Open set:{0, 1, 2, 4}.fd3 = open("err.log", ...)reuses the newly freed lowest slot:fd3 = 3. Open set:{0, 1, 2, 3, 4}.
Redirecting Standard Output with dup2():
After close(fd2), fd 4 is closed (reference count drops to 1), while fd 1 remains connected to output.log.
Tracing printf("OK\n"): Because printf() writes to stdout (STDOUT_FILENO = 1), and fd 1 now points to output.log, "OK\n" is written into output.log. (Also note fd1 + fd2 + fd3 summed across assignments equals 3 + 4 + 3 = 10, while final open non-standard fd is fd3 = 3, and fd1=3, fd2=4, STDOUT=1 -> 3 + 4 + 1 = 8.)
fd1 = 3,fd2 = 4, andfd3 = 3(reusing freed slot 3).- After
dup2(fd2, 1)andclose(fd2), open descriptors are0(stdin),1(output.log),2(stderr), and3(err.log). printf("OK\n")writes tooutput.log.
Low-Level POSIX File Copy Program in C
Write a clean, well-structured C program using only POSIX low-level I/O system calls (open, read, write, close) that copies a source file to a destination file using a 4096-byte buffer, handles partial writes safely, and reports errors via perror().
Open Source and Destination Files with Proper Flags and Permissions:
- Open the source file with
O_RDONLY. - Open the destination file with
O_WRONLY,O_CREAT, andO_TRUNC(bitwise OR) and permission mode0644(rw-r--r--).
Loop with read() and Handle Partial write() Calls:
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUF_SIZE 4096
int write_all(int fd, const char *buf, ssize_t len) {
ssize_t total = 0;
while (total < len) {
ssize_t n = write(fd, buf + total, (size_t)(len - total));
if (n < 0) {
if (errno == EINTR) continue; /* retry if interrupted by signal */
return -1;
}
total += n;
}
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 3) {
fprintf(stderr, "Usage: %s <src> <dst>\n", argv[0]);
return EXIT_FAILURE;
}
int src_fd = open(argv[1], O_RDONLY);
if (src_fd < 0) {
perror("open source");
return EXIT_FAILURE;
}
int dst_fd = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (dst_fd < 0) {
perror("open destination");
close(src_fd);
return EXIT_FAILURE;
}
char buf[BUF_SIZE];
ssize_t nread;
while ((nread = read(src_fd, buf, sizeof(buf))) != 0) {
if (nread < 0) {
if (errno == EINTR) continue;
perror("read");
close(src_fd);
close(dst_fd);
return EXIT_FAILURE;
}
if (write_all(dst_fd, buf, nread) < 0) {
perror("write");
close(src_fd);
close(dst_fd);
return EXIT_FAILURE;
}
}
close(src_fd);
close(dst_fd);
return EXIT_SUCCESS;
}The program opens both files via open(), streams 4096-byte chunks with read(), guarantees complete transmission of each chunk using write_all() (retrying on EINTR and advancing the pointer on partial writes), checks errors with perror(), and releases both file descriptors with close().
Quantifying System Call Overhead: Unbuffered vs. Buffered I/O
A C program copies a 1 MiB (1,048,576 bytes) file using read() and write(). Suppose each system call (round-trip user-to-kernel-to-user mode switch) takes 0.4 microseconds. Ignore actual disk/cache copy time and compute the pure syscall transition overhead when using:
- A 1-byte buffer (
BUF_SIZE = 1). - A 4096-byte buffer (
BUF_SIZE = 4096).
Case 1 — 1-Byte Buffer: Reading and writing 1,048,576 bytes 1 byte at a time requires:
1,048,576read()syscalls (ignoring the single finalread()returning0at EOF, or1,048,576data syscalls) +1,048,576write()syscalls =2,097,152data-transfer syscalls.- Total mode-switch overhead =
2,097,152 * 0.4 us = 838,860.8 us(~838.86 msor0.839 s) spent purely crossing the user-kernel boundary.
Case 2 — 4096-Byte (4 KiB) Buffer:
- Number of chunks =
1,048,576 / 4096 = 256chunks. - Total data-transfer syscalls =
256read()+256write()=512syscalls. - Total mode-switch overhead =
512 * 0.4 us = 204.8 us(~0.205 ms).
Speedup Ratio: 838,860.8 us / 204.8 us = 4096 times lower syscall transition overhead.
- 1-byte buffer:
2,097,152data syscalls -> 838,860.8 microseconds (~838.9 ms) of syscall overhead. - 4096-byte buffer:
512data syscalls -> 204.8 microseconds (~0.205 ms) of syscall overhead (a 4096x reduction).
Exercises
Practice Exercises — System Programming Fundamentals
Define system programming and explain four specific reasons why system-level programming (rather than high-level application frameworks alone) is critical for building scalable networked applications.
Definition: System programming is the development of low-level software (utilities, daemons, servers, drivers) that directly invokes operating system interfaces (system calls) to manage processes, threads, memory, file descriptors, and network hardware.
Four Roles in Networking:
- Direct Socket Control: Exposes TCP/UDP sockets, raw sockets, and kernel tuning options (
SO_REUSEADDR,TCP_NODELAY, buffer sizes). - I/O Multiplexing: Enables a single server process to monitor thousands of concurrent connections via
select(),poll(), orepoll(). - Zero-Copy Transfers: Uses
sendfile()andmmap()to avoid redundant user-kernel memory copies when serving high-volume network traffic. - Deterministic Concurrency and Signal Handling: Provides fine-grained control over
fork(), POSIX threads, mutexes, and asynchronous OS signals (SIGCHLD,SIGTERM) without garbage-collection pauses.
System programming builds infrastructure directly atop OS system calls. In networking, it is critical for (1) direct socket/protocol control, (2) high-concurrency I/O multiplexing (epoll), (3) zero-copy data movement (sendfile/mmap), and (4) deterministic process, thread, and signal management.
Differentiate between user space and kernel space. Trace the exact hardware and kernel sequence that occurs when a C program calls read(fd, buf, 100).
User Space vs. Kernel Space:
- User Space executes at unprivileged CPU level (e.g., Ring 3 on x86-64) inside an isolated per-process virtual address space; it cannot access hardware or kernel memory directly, and a crash terminates only that process.
- Kernel Space executes at privileged/supervisor level (Ring 0) with unrestricted access to RAM, MMU, NICs, and disks; an unhandled fault triggers a kernel panic.
Execution Sequence for read(fd, buf, 100):
- The C program calls the
libcread()wrapper, which places theSYS_readsyscall number and arguments (fd,buf,100) in CPU registers and executes a trap instruction (syscall). - Hardware elevates CPU privilege from User Mode to Kernel Mode and jumps to the kernel syscall dispatcher.
- The kernel validates that
fdis valid and readable, and checks thatbufpoints to writable user-space memory belonging to the calling process. - The VFS subsystem invokes the underlying file/socket driver; if data is unavailable on a blocking fd, the process sleeps until an interrupt delivers data.
- The kernel copies up to
100bytes intobuf, puts the byte count in the return register, and executessysretto drop back to User Mode.
User space is unprivileged and process-isolated (Ring 3), whereas kernel space has unrestricted hardware access (Ring 0). Calling read() triggers a syscall trap into Ring 0, where the kernel validates fd and buf, retrieves data via VFS/drivers, copies bytes to user memory, and returns via sysret to User Mode.
A network logging daemon writes 512 KiB (524,288 bytes) of log records. Suppose one mode switch (write() syscall) costs 0.5 microseconds, and the stdio library uses an 8 KiB (8,192-byte) user-space buffer. Compare:
- Calling unbuffered
write(fd, &ch, 1)for every byte. - Calling
fwrite(&ch, 1, 1, fp)wherestdioflushes automatically every 8 KiB.
Compute the number of write() syscalls and total syscall transition time in both cases.
Case 1 — Unbuffered write() per byte: Each 1-byte write() crosses into kernel space (2 mode switches per syscall: user-to-kernel entry + kernel-to-user return = 2 * 0.5 us = 1.0 us per syscall):
- Number of
write()syscalls =524,288. - Total syscall transition time =
524,288 * 2 * 0.5 us = 524,288.0 us(524.288 ms).
Case 2 — stdio Buffered fwrite() (8 KiB user buffer): fwrite() copies each byte into libc's 8,192-byte user-space buffer without calling the kernel. It invokes write() only when the buffer fills:
- Number of
write()syscalls =524,288 / 8,192 = 64syscalls. - Total syscall transition time (at
2 * 0.5 us = 1.0 usper syscall) =64 * 2 * 0.5 us = 64.0 us(0.064 ms).
- Unbuffered
write()per byte:524,288syscalls -> 524,288 us (524.288 ms) of transition overhead. - Buffered
fwrite()(8 KiB buffer):64syscalls -> 64.0 us (0.064 ms) of transition overhead (an 8,192x reduction).
A process starts with standard fds 0, 1, and 2 open. It runs:
a = open("f1.txt", O_RDONLY);
b = open("f2.txt", O_WRONLY | O_CREAT, 0644);
close(0);
c = dup(b);
d = open("f3.txt", O_RDONLY);Determine the exact integer values returned for a, b, c, and d, and explain how c and b interact when write(c, "Hi", 2) is followed by write(b, "!", 1).
Tracing Lowest-Available FD Assignments:
- Initial open fds:
{0, 1, 2}. a = open("f1.txt", ...): lowest free fd isa = 3. Open set:{0, 1, 2, 3}.b = open("f2.txt", ...): lowest free fd isb = 4. Open set:{0, 1, 2, 3, 4}.close(0): closes stdin, freeing slot0. Open set:{1, 2, 3, 4}.c = dup(b): duplicatesbonto the lowest free fd, which isc = 0. Open set:{0, 1, 2, 3, 4}.d = open("f3.txt", ...): lowest free fd isd = 5. Open set:{0, 1, 2, 3, 4, 5}.
Interaction Between b and c: Because c was created via dup(b), entries 0 and 4 in the process FD table point to the same Open File Table entry (sharing the same file offset).
write(c, "Hi", 2)writes"Hi"at offset0and advances the shared offset to2.write(b, "!", 1)writes"!"at the shared offset2(instead of overwriting"Hi"), resulting in"Hi!"inf2.txtwith offset3.
a = 3, b = 4, c = 0, and d = 5 (sum a + b + c + d = 12). Because dup(b) makes c share b's Open File Table entry and file offset, write(c, "Hi", 2) followed by write(b, "!", 1) sequentially writes "Hi!" into f2.txt.
Sketch the Linux/Unix layered system architecture and trace how a network application's send() call on a TCP socket flows down through user space, kernel subsystems, and hardware.
Architectural Layers (Top to Bottom):
- User Space: Applications/daemons +
libcstandard library wrappers. - System Call Interface (SCI): Validates fd and user buffer pointers, transitions CPU to Kernel Mode.
- Kernel Subsystems: Virtual File System (VFS) / BSD Socket layer, Network Protocol Stack (TCP/UDP, IP, Netfilter), Memory Manager (kernel socket buffers
sk_buff), Process Scheduler, and IPC. - Device Drivers: NIC driver managing transmit ring descriptors and DMA.
- Physical Hardware: CPU, RAM, and Network Interface Card (NIC).
Downward Path of send(sockfd, data, len, 0):
- Application calls
libcsend(), trapping viasyscallinto the SCI. - SCI verifies
sockfdmaps to a socket in the process's FD table. - The BSD Socket layer copies
datafrom user space into kernelsk_buffstructures inside the socket send buffer. - The TCP layer segments the payload, attaches sequence/ack numbers and checksum, and passes segments to the IP layer for routing and IP header attachment.
- The NIC device driver places packet descriptors onto the hardware TX ring; the NIC fetches the frames via DMA and transmits electrical/optical signals onto the network medium.
Linux/Unix separates User Space (libc and apps), the System Call Interface, Kernel Subsystems (Scheduler, Memory Manager, VFS, Network Stack, IPC, Device Drivers), and Hardware. A send() call traps across SCI into the BSD socket layer, moves data into kernel sk_buffs, traverses TCP -> IP -> NIC driver, and is transmitted by the NIC over DMA.