From the free course Systems Programming in C and Unix Environments on Lykke
Exam Preparation and Review
Key concepts: C Memory Model Review · POSIX System Call Synthesis · Signal Disposition · Socket Management Pitfalls
Synthesis of course materials for midterm and final examinations.
Exam Preparation and Review
The transition from high-level application programming to systems programming requires a fundamental shift in how one perceives the computer. In systems programming, the abstractions of the language (C) and the operating system (POSIX) are not merely tools, but the very constraints and materials of the craft. Success in a systems-level examination depends on a dual mastery: the ability to manually trace the state of memory and the ability to predict the side effects of kernel-level operations.
This review synthesizes the core pillars of the curriculum—Memory Models, Process Management, Signal Handling, and Network I/O—into a cohesive framework for exam preparation.
The C Memory Model: Lifetimes and Layout
At the heart of every C program lies the memory model. Unlike managed languages like Java or Python, C requires the programmer to understand exactly where an object resides in the virtual address space and how long it stays there.
The Four Pillars of Object Lifetimes
C distinguishes between objects based on their lifetime (when they are created and destroyed) and their scope (where their names are visible).
| Segment | Lifetime | Management | Characteristics |
|---|---|---|---|
| Static / Data | Program Duration | Compiler/Linker | Stores global variables and static locals. Initialized once at startup. |
| Stack | Function Scope | Automatic (LIFO) | Stores local variables and return addresses. Fast, but limited in size. |
| Heap | Manual | malloc() / free() |
Dynamic allocation. Persistent until explicitly freed. Prone to leaks. |
| Text | Program Duration | Read-Only | Stores the actual machine instructions and string literals. |
The Rule of Three: When analyzing memory problems, always ask: 1) Who allocated it? 2) Who owns it? 3) Who is responsible for freeing it?
Pointer Arithmetic and Type Synthesis
Pointers are not merely integers; they are typed addresses. The expression ptr + 1 increments the address by 1 * sizeof(*ptr) bytes. This is the most common area for "off-by-one" errors in exam questions.
Example: Pointer Offset Calculation
int arr[5] = {10, 20, 30, 40, 50};
int *p = &arr[1]; // p points to 20
printf("%d\n", *(p + 2)); // Result: 40
In the example above, p + 2 moves the pointer forward by two int widths (usually 8 bytes), landing on arr[3].
Common Pitfalls in Memory
- Dangling Pointers: Accessing memory after it has been
free()'d or after a stack frame has been popped. - Memory Leaks: Losing the last pointer to a heap allocation without calling
free(). - Buffer Overflows: Writing past the allocated bounds of an array, often corrupting the stack canary or return address.
- Undefined Behavior (UB): Operations like dereferencing a
NULLpointer or shifting an integer by more than its bit-width. Once UB occurs, the compiler is no longer bound by the rules of the language.
POSIX System Call Synthesis
System calls are the gateway to the kernel. While C provides the logic, POSIX provides the capability. For the exam, you must be able to synthesize multiple system calls to achieve complex behaviors, such as redirection or process synchronization.
The Process Lifecycle: fork, exec, and wait
The fork() system call is unique because it returns twice: once in the parent (returning the child's PID) and once in the child (returning 0).
| Function | Purpose | Effect on Address Space |
|---|---|---|
fork() |
Create a child process | Exact clone (Copy-on-Write) |
execvp() |
Replace process image | Overwrites current memory with new program |
waitpid() |
Synchronize with child | Parent blocks until child changes state |
exit() |
Terminate process | Cleans up resources, returns status to parent |
File Descriptor Inheritance
One of the most critical concepts is how file descriptors (FDs) behave across a fork(). The child inherits a copy of the parent's FD table. Both FDs point to the same Open File Description in the kernel, meaning they share the same file offset.
Example: Redirection Logic
To redirect stdout to a file in a child process:
int fd = open("output.txt", O_WRONLY | O_CREAT, 0644);
if (fork() == 0) {
dup2(fd, STDOUT_FILENO); // Replace stdout with our file
close(fd); // Close original copy
execlp("ls", "ls", NULL);
}
close(fd);
wait(NULL);
Zombie and Orphan Processes
- Zombie: A process that has terminated (
exit) but whose parent has not yet calledwait(). It occupies an entry in the process table. - Orphan: A process whose parent has terminated. It is "adopted" by
init(PID 1), which automatically reaps it.
Signal Disposition and Asynchronous Safety
Signals are software interrupts that break the normal flow of execution. Handling them correctly is one of the most difficult tasks in systems programming due to their asynchronous nature.
Signal Handling Mechanisms
The modern way to handle signals is via sigaction, which provides more control and reliability than the deprecated signal() function.
| Signal | Default Action | Typical Usage |
|---|---|---|
SIGINT |
Terminate | Generated by Ctrl+C |
SIGKILL |
Terminate (Forced) | Cannot be caught or ignored |
SIGSEGV |
Terminate (Core Dump) | Invalid memory access |
SIGCHLD |
Ignore | Sent to parent when child stops/terminates |
SIGALRM |
Terminate | Generated by alarm() timer |
Reentrancy and Async-Signal-Safety
A function is reentrant if it can be interrupted in the middle of its execution and then safely called again (the "re-entry") before its previous invocation has finished.
Exam Tip: Inside a signal handler, you should only call async-signal-safe functions. For example,
printf()is NOT safe because it uses internal locks and buffers;write()IS safe because it is a direct system call.
The sig_atomic_t Type
When sharing a flag between a signal handler and the main program, use volatile sig_atomic_t. This ensures the compiler doesn't optimize the variable into a register and that reads/writes are atomic.
Socket Management Pitfalls
Networking in C involves a specific sequence of system calls. Errors usually arise from a misunderstanding of the state machine or improper buffer handling.
The Socket Lifecycle
- Socket Creation:
socket() - Naming:
bind()(Server only) - Preparation:
listen()(Server only) - Connection:
connect()(Client) oraccept()(Server) - Data Transfer:
read()/write()orsend()/recv() - Teardown:
close()
| Problem | Cause | Solution |
|---|---|---|
EADDRINUSE |
Port is in "TIME_WAIT" state | Use setsockopt with SO_REUSEADDR |
| Partial Reads | Network MTU or congestion | Wrap read() in a while loop |
| Deadlock | Both sides waiting to read | Ensure a clear application-level protocol |
| SIGPIPE | Writing to a closed socket | Handle SIGPIPE or use MSG_NOSIGNAL |
Byte Order (Endianness)
The internet uses Big-Endian (Network Byte Order). Most modern PCs use Little-Endian (Host Byte Order). You must use htons(), htonl(), ntohs(), and ntohl() to convert 16-bit and 32-bit integers when sending them over a socket.
Exam Problem Walkthroughs
Problem 1: The Fork Tree
Question: How many times is "Hello" printed?
fork();
if (fork() == 0) {
fork();
}
printf("Hello\n");
Solution:
- Initial process (P1) forks. Now we have P1 and P2.
- P1 (parent) skips the
ifblock. - P2 (child) enters the
ifblock and forks again. Now we have P2 and P3. - P1, P2, and P3 all reach the
printf. - Total: 4 times. (Wait, let's re-trace).
- Start: 1 process.
- 1st fork: 2 processes.
- 2nd fork: The child of the 1st fork (P2) forks again. The parent (P1) does NOT.
- Result: P1 (original), P2 (child), P3 (grandchild).
- Correct Total: 3 times.
Problem 2: Pointer Arithmetic
Question: What is the output of the following code?
char *str = "Systems";
char **ptr = &str;
ptr++;
// What is *ptr?
Solution:
ptr is a char**. Incrementing it moves it by sizeof(char*) (usually 8 bytes). Since ptr was pointing to the local variable str on the stack, ptr++ now points to some random memory adjacent to str on the stack. Dereferencing it (*ptr) results in Undefined Behavior or a crash. This is a common trick question—incrementing a pointer to a single variable is almost always an error.
Problem 3: Signal Race Conditions
Question: Why is this code dangerous?
int count = 0;
void handler(int sig) { count++; }
int main() {
signal(SIGINT, handler);
while(count < 1) {
// do work
}
}
Solution:
If the compiler optimizes the while loop, it might load count into a register once and never check memory again, causing an infinite loop even if the signal arrives. The variable count must be declared as volatile sig_atomic_t.
Final Review Checklist
- Can you draw the memory layout of a process from memory?
- Do you know the difference between
char arr[] = "hello"andchar *ptr = "hello"? (Stack vs. Text segment). - Can you trace a complex series of
fork()andwait()calls? - Do you understand why
malloc(strlen(str))is a bug? (Forgetting the null terminator\0). - Are you comfortable converting between
struct sockaddr,struct sockaddr_in, andstruct addrinfo? - Can you identify a race condition in a multi-threaded program?
Source Materials
Study Systems Programming in C and Unix Environments on Lykke
This course page is free to open: signed out, you can read its first two sections, and signing in, on any plan, opens the rest. The free Lykke Chrome extension syncs your own Canvas courses, so ChatGPT, Claude and Muse can answer from your classes and deadlines. It only reads Canvas.
Add the free extensionSign in to open every sectionAll sections of Systems Programming in C and Unix Environments · Browse more course pages