-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathos.html
More file actions
2113 lines (1711 loc) · 113 KB
/
os.html
File metadata and controls
2113 lines (1711 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Operating Systems - Better Dev</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group">
<a href="index.html">Home</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> › Operating Systems</div>
<h1>Operating Systems</h1>
<p>How your computer actually works under the hood. Processes, syscalls, memory, concurrency, file systems -- explained so you actually understand what happens when you run a program.</p>
<div class="tip-box" style="margin-top: 1rem;">
<div class="label">Free Textbook</div>
<p>This page is a companion to <a href="https://pages.cs.wisc.edu/~remzi/OSTEP/" class="resource-link" target="_blank">Operating Systems: Three Easy Pieces (OSTEP)</a> -- the best free OS textbook. Read it alongside this page for the full picture.</p>
</div>
</div>
</div>
<div class="page-with-toc">
<aside class="sidebar-toc">
<div class="toc">
<h4>Table of Contents</h4>
<a href="#what-is-os">1. What Is an OS?</a>
<a href="#processes">2. Processes</a>
<a href="#syscalls">3. System Calls</a>
<a href="#process-api">4. Process API (fork, exec, wait)</a>
<a href="#scheduling">5. CPU Scheduling</a>
<a href="#threads">6. Threads & Concurrency</a>
<a href="#locks">7. Locks & Synchronization</a>
<a href="#deadlocks">8. Deadlocks</a>
<a href="#memory">9. Memory & Address Spaces</a>
<a href="#paging">10. Paging & Virtual Memory</a>
<a href="#io">11. I/O & Devices</a>
<a href="#filesystems">12. File Systems</a>
<a href="#security">13. OS Security Basics</a>
<a href="#context-switch">14. Context Switching</a>
<a href="#ipc">15. Inter-Process Communication (IPC)</a>
<a href="#program-execution">16. How Programs Actually Run</a>
<a href="#containers-os">17. Containers & Virtualization</a>
<a href="#linux-commands">18. Essential Linux Commands</a>
<a href="#quiz">19. Practice Quiz</a>
</div>
</aside>
<div class="content">
<!-- Mobile TOC -->
<div class="toc" style="margin-bottom: 2rem;">
<h4>Table of Contents</h4>
<a href="#what-is-os">1. What Is an OS?</a>
<a href="#processes">2. Processes</a>
<a href="#syscalls">3. System Calls</a>
<a href="#process-api">4. Process API (fork, exec, wait)</a>
<a href="#scheduling">5. CPU Scheduling</a>
<a href="#threads">6. Threads & Concurrency</a>
<a href="#locks">7. Locks & Synchronization</a>
<a href="#deadlocks">8. Deadlocks</a>
<a href="#memory">9. Memory & Address Spaces</a>
<a href="#paging">10. Paging & Virtual Memory</a>
<a href="#io">11. I/O & Devices</a>
<a href="#filesystems">12. File Systems</a>
<a href="#security">13. OS Security Basics</a>
<a href="#context-switch">14. Context Switching</a>
<a href="#ipc">15. Inter-Process Communication (IPC)</a>
<a href="#program-execution">16. How Programs Actually Run</a>
<a href="#containers-os">17. Containers & Virtualization</a>
<a href="#linux-commands">18. Essential Linux Commands</a>
<a href="#quiz">19. Practice Quiz</a>
</div>
<!-- ============================================================ -->
<!-- SECTION 1: WHAT IS AN OS? -->
<!-- ============================================================ -->
<section id="what-is-os">
<h2>1. What Is an Operating System?</h2>
<p>An operating system (OS) is a piece of software that sits between your programs and the hardware. When you open a browser, type in a terminal, or save a file, your program doesn't talk to the CPU or disk directly -- it asks the OS to do it.</p>
<p>The OS has three main jobs:</p>
<ul>
<li><strong>Virtualisation</strong> -- make it look like each program has its own CPU and its own memory, even though they're all sharing the same physical hardware.</li>
<li><strong>Concurrency</strong> -- let multiple programs (and multiple threads within a program) run at the same time without stepping on each other.</li>
<li><strong>Persistence</strong> -- store data on disk so it survives after your program exits or the machine reboots.</li>
</ul>
<p>These are the "three easy pieces" from the OSTEP textbook. Every concept in this page falls into one of these three buckets.</p>
<div class="memory-diagram">
┌─────────────────────────────────┐
│ Your Programs │ ← User space (your code runs here)
│ (browser, editor, game, etc.) │
├─────────────────────────────────┤
│ System Call Interface │ ← The boundary (syscalls)
├─────────────────────────────────┤
│ Operating System │ ← Kernel space (privileged code)
│ Process mgmt | Memory | FS │
├─────────────────────────────────┤
│ Hardware │ ← CPU, RAM, Disk, Network
│ (physical resources) │
└─────────────────────────────────┘</div>
<h3>User Mode vs Kernel Mode</h3>
<p>The CPU has (at minimum) two privilege levels:</p>
<ul>
<li><strong>User mode</strong> -- your normal programs run here. They <em>cannot</em> directly access hardware, other processes' memory, or privileged instructions. If they try, the CPU raises a fault.</li>
<li><strong>Kernel mode</strong> -- the OS kernel runs here. It has full access to everything: hardware registers, all memory, I/O ports.</li>
</ul>
<p>The only way for a user-mode program to do something privileged (open a file, allocate memory, send a network packet) is to make a <strong>system call</strong>, which we'll cover in section 3.</p>
<div class="warning-box">
<div class="label">Why This Matters</div>
<p>This separation is what keeps your computer stable. A buggy program can't crash the whole machine because it literally cannot touch hardware or other processes' memory. The OS acts as a gatekeeper.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 2: PROCESSES -->
<!-- ============================================================ -->
<section id="processes">
<h2>2. Processes</h2>
<p>A <strong>process</strong> is a running program. When you double-click an app or type <code>./my_program</code> in a terminal, the OS creates a process for it. Each process gets:</p>
<ul>
<li>Its own <strong>address space</strong> -- its own view of memory (code, stack, heap, data)</li>
<li>One or more <strong>threads</strong> of execution</li>
<li>Open <strong>file descriptors</strong> (files, sockets, pipes it has open)</li>
<li>A <strong>process ID (PID)</strong> -- a unique number identifying it</li>
<li>A <strong>state</strong> -- running, ready, or blocked</li>
</ul>
<h3>Process States</h3>
<p>At any moment, a process is in one of these states:</p>
<div class="memory-diagram">
┌──────────┐
Created ──→ │ Ready │ ←──────────────┐
└────┬─────┘ │
│ (scheduler picks it) │ (I/O completes or
▼ │ event arrives)
┌──────────┐ ┌─────┴──────┐
│ Running │ ──────→ │ Blocked │
└────┬─────┘ (needs └────────────┘
│ I/O or
│ waits)
▼
┌──────────┐
│Terminated│
└──────────┘</div>
<ul>
<li><strong>Ready</strong> -- the process could run, but the CPU is busy with another process. It's waiting in the ready queue.</li>
<li><strong>Running</strong> -- the process is actually executing instructions on the CPU right now.</li>
<li><strong>Blocked</strong> -- the process is waiting for something (disk read, network data, user input). It can't run even if the CPU is free.</li>
</ul>
<h3>What's Inside a Process (the PCB)</h3>
<p>The OS keeps a <strong>Process Control Block (PCB)</strong> for every process. Think of it as a struct:</p>
<pre><code><span class="lang-label">Conceptual</span>
<span class="keyword">struct</span> PCB {
<span class="builtin">int</span> pid; <span class="comment">// process ID</span>
<span class="builtin">int</span> state; <span class="comment">// READY, RUNNING, BLOCKED</span>
<span class="builtin">int</span> priority; <span class="comment">// scheduling priority</span>
regs_t saved_registers; <span class="comment">// CPU registers when not running</span>
<span class="builtin">void</span>* page_table; <span class="comment">// pointer to address space info</span>
<span class="builtin">int</span> open_files[<span class="number">256</span>]; <span class="comment">// file descriptor table</span>
pid_t parent_pid; <span class="comment">// who created this process</span>
};</code></pre>
<p>When the OS switches from process A to process B (<strong>context switch</strong>), it saves A's registers into A's PCB, then loads B's registers from B's PCB. This is how the illusion of "every process has its own CPU" works.</p>
<div class="example-box">
<div class="label">Example: Context Switch</div>
<p>Process A is running. A timer interrupt fires (every ~1-10ms). The OS:</p>
<ol>
<li>Saves A's registers (program counter, stack pointer, etc.) into A's PCB</li>
<li>Changes A's state from RUNNING to READY</li>
<li>Picks process B from the ready queue</li>
<li>Loads B's saved registers from B's PCB</li>
<li>Changes B's state from READY to RUNNING</li>
<li>Jumps to where B left off</li>
</ol>
<p>This happens thousands of times per second. Each switch takes ~1-10 microseconds.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 3: SYSTEM CALLS -->
<!-- ============================================================ -->
<section id="syscalls">
<h2>3. System Calls (Syscalls)</h2>
<p>A <strong>system call</strong> is how your program asks the OS to do something it can't do itself. Your code runs in user mode. It can't touch hardware. So when it needs to open a file, create a process, or send data over the network, it must cross the boundary into kernel mode.</p>
<h3>How a Syscall Works (Step by Step)</h3>
<div class="memory-diagram">
Your program Kernel
───────────── ──────
1. Put syscall number
in a register (e.g. rax)
2. Put arguments in
registers (rdi, rsi, rdx..)
3. Execute special CPU
instruction:
"syscall" (x86-64)
"svc" (ARM)
"int 0x80" (old x86)
│
▼
┌─── CPU switches to ───┐
│ kernel mode │
└────────────────────────┘
4. Kernel looks up syscall
number in syscall table
5. Runs the handler function
(e.g. sys_open, sys_read)
6. Returns result
│
▼
┌─── CPU switches back ─┐
│ to user mode │
└────────────────────────┘
7. Result is in rax register
(or -1 for error + errno)</div>
<p>The key insight: the <code>syscall</code> instruction is a <em>hardware mechanism</em>. The CPU itself switches privilege levels. Your program can't fake being in kernel mode -- the CPU enforces the boundary.</p>
<h3>Major Syscall Categories</h3>
<table>
<tr><th>Category</th><th>Syscalls</th><th>What They Do</th></tr>
<tr><td><strong>Process</strong></td><td><code>fork</code>, <code>exec</code>, <code>wait</code>, <code>exit</code>, <code>kill</code></td><td>Create, replace, wait for, terminate processes</td></tr>
<tr><td><strong>File I/O</strong></td><td><code>open</code>, <code>read</code>, <code>write</code>, <code>close</code>, <code>lseek</code></td><td>Open, read, write, close files</td></tr>
<tr><td><strong>Memory</strong></td><td><code>mmap</code>, <code>munmap</code>, <code>brk</code></td><td>Map memory, grow/shrink heap</td></tr>
<tr><td><strong>Network</strong></td><td><code>socket</code>, <code>bind</code>, <code>listen</code>, <code>accept</code>, <code>connect</code></td><td>Create sockets, accept connections</td></tr>
<tr><td><strong>Info</strong></td><td><code>getpid</code>, <code>getuid</code>, <code>uname</code></td><td>Get process/user/system info</td></tr>
<tr><td><strong>Signals</strong></td><td><code>signal</code>, <code>sigaction</code>, <code>kill</code></td><td>Handle async notifications</td></tr>
<tr><td><strong>Directory</strong></td><td><code>mkdir</code>, <code>rmdir</code>, <code>chdir</code>, <code>getcwd</code></td><td>Manage directories</td></tr>
</table>
<h3>File Descriptors -- the Universal Handle</h3>
<p>When you open a file, the OS doesn't give you a pointer to the file. It gives you a small integer called a <strong>file descriptor (fd)</strong>. This is an index into a per-process table of open files.</p>
<p>Every process starts with three file descriptors already open:</p>
<div class="formula-box">
fd 0 = stdin (standard input -- keyboard by default)
fd 1 = stdout (standard output -- terminal by default)
fd 2 = stderr (standard error -- terminal by default)
</div>
<p>When you call <code>open("myfile.txt", O_RDONLY)</code>, the kernel finds the next available fd (usually 3) and returns it. All future <code>read()</code> and <code>write()</code> calls use this fd number.</p>
<pre><code><span class="lang-label">C</span>
<span class="comment">// Open a file -- returns a file descriptor (small int)</span>
<span class="builtin">int</span> fd = <span class="function">open</span>(<span class="string">"data.txt"</span>, O_RDONLY);
<span class="keyword">if</span> (fd == -<span class="number">1</span>) {
<span class="function">perror</span>(<span class="string">"open failed"</span>); <span class="comment">// prints human-readable error</span>
<span class="keyword">return</span> <span class="number">1</span>;
}
<span class="comment">// Read up to 1024 bytes from the file</span>
<span class="builtin">char</span> buf[<span class="number">1024</span>];
ssize_t bytes_read = <span class="function">read</span>(fd, buf, <span class="keyword">sizeof</span>(buf));
<span class="comment">// Write to stdout (fd 1)</span>
<span class="function">write</span>(<span class="number">1</span>, buf, bytes_read);
<span class="comment">// Always close when done</span>
<span class="function">close</span>(fd);</code></pre>
<div class="tip-box">
<div class="label">Everything is a File</div>
<p>Unix's big insight: files, pipes, sockets, terminals, and even devices all use the same <code>read()</code>/<code>write()</code>/<code>close()</code> interface with file descriptors. That's why the same code can read from a file, a network connection, or a pipe -- the fd abstracts the details away.</p>
</div>
<h3>Syscalls vs Library Functions</h3>
<p>Don't confuse syscalls with C library (libc) functions:</p>
<ul>
<li><code>printf()</code> is a <strong>library function</strong> -- it formats your string in user space, then eventually calls the <code>write()</code> <strong>syscall</strong> to actually output it.</li>
<li><code>malloc()</code> is a <strong>library function</strong> -- it manages a pool of memory in user space, and only calls <code>brk()</code> or <code>mmap()</code> syscalls when it needs more from the OS.</li>
<li><code>fopen()</code> is a library wrapper around the <code>open()</code> syscall that adds buffering.</li>
</ul>
<p>Library functions are faster because they avoid the user-to-kernel mode switch. Syscalls are expensive (hundreds of nanoseconds each), so libc batches operations to minimise them.</p>
<div class="example-box">
<div class="label">Example: Tracing Syscalls</div>
<p>You can see every syscall a program makes using <code>strace</code> on Linux:</p>
<pre><code><span class="lang-label">Shell</span>
<span class="comment"># See all syscalls made by ls</span>
$ strace ls
<span class="comment"># Count syscalls by type</span>
$ strace -c ls
<span class="comment"># Trace only file-related syscalls</span>
$ strace -e trace=file ls
<span class="comment"># Trace a running process by PID</span>
$ strace -p 1234</code></pre>
<p>Try <code>strace -c echo "hello"</code> -- you'll see it makes about 30 syscalls just to print one word. Most are setup (loading libraries, setting up memory).</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 4: PROCESS API -->
<!-- ============================================================ -->
<section id="process-api">
<h2>4. Process API (fork, exec, wait)</h2>
<p>In Unix/Linux, you create processes using three syscalls that work together: <code>fork()</code>, <code>exec()</code>, and <code>wait()</code>. This design seems odd at first, but it's incredibly powerful.</p>
<h3>fork() -- Clone Yourself</h3>
<p><code>fork()</code> creates an <em>exact copy</em> of the current process. The new process (child) gets a copy of the parent's memory, file descriptors, and code. Both processes continue from the same line -- the line after <code>fork()</code>.</p>
<pre><code><span class="lang-label">C</span>
<span class="keyword">#include</span> <span class="string"><stdio.h></span>
<span class="keyword">#include</span> <span class="string"><unistd.h></span>
<span class="builtin">int</span> <span class="function">main</span>() {
<span class="function">printf</span>(<span class="string">"Before fork (PID %d)\n"</span>, <span class="function">getpid</span>());
pid_t pid = <span class="function">fork</span>();
<span class="keyword">if</span> (pid == <span class="number">0</span>) {
<span class="comment">// This runs in the CHILD process</span>
<span class="function">printf</span>(<span class="string">"I am the child! PID = %d, parent = %d\n"</span>,
<span class="function">getpid</span>(), <span class="function">getppid</span>());
} <span class="keyword">else if</span> (pid > <span class="number">0</span>) {
<span class="comment">// This runs in the PARENT process</span>
<span class="function">printf</span>(<span class="string">"I am the parent! PID = %d, child = %d\n"</span>,
<span class="function">getpid</span>(), pid);
} <span class="keyword">else</span> {
<span class="comment">// fork() failed</span>
<span class="function">perror</span>(<span class="string">"fork"</span>);
}
<span class="keyword">return</span> <span class="number">0</span>;
}</code></pre>
<div class="memory-diagram">
Before fork():
Parent (PID 100) ──→ running main()
After fork():
Parent (PID 100) ──→ pid = 200 (child's PID)
Child (PID 200) ──→ pid = 0 (that's how it knows it's the child)</div>
<p>The trick: <code>fork()</code> returns <strong>twice</strong> -- once in the parent (returns child's PID) and once in the child (returns 0). That's how each process knows who it is.</p>
<h3>exec() -- Replace Yourself</h3>
<p><code>exec()</code> replaces the current process's code and memory with a new program. It loads a different executable and starts running it from its <code>main()</code>. The PID stays the same.</p>
<pre><code><span class="lang-label">C</span>
<span class="keyword">#include</span> <span class="string"><unistd.h></span>
<span class="builtin">int</span> <span class="function">main</span>() {
pid_t pid = <span class="function">fork</span>();
<span class="keyword">if</span> (pid == <span class="number">0</span>) {
<span class="comment">// Child: replace myself with "ls -la"</span>
<span class="function">execlp</span>(<span class="string">"ls"</span>, <span class="string">"ls"</span>, <span class="string">"-la"</span>, NULL);
<span class="comment">// If we get here, exec failed</span>
<span class="function">perror</span>(<span class="string">"exec failed"</span>);
}
<span class="keyword">return</span> <span class="number">0</span>;
}</code></pre>
<div class="warning-box">
<div class="label">Key Insight</div>
<p><code>exec()</code> never returns on success -- the old program is completely gone, replaced by the new one. Any code after <code>exec()</code> only runs if exec failed.</p>
</div>
<h3>wait() -- Wait for Your Child</h3>
<p><code>wait()</code> blocks the parent until a child process finishes. This lets you run something and get its exit code.</p>
<pre><code><span class="lang-label">C</span>
<span class="keyword">#include</span> <span class="string"><stdio.h></span>
<span class="keyword">#include</span> <span class="string"><stdlib.h></span>
<span class="keyword">#include</span> <span class="string"><unistd.h></span>
<span class="keyword">#include</span> <span class="string"><sys/wait.h></span>
<span class="builtin">int</span> <span class="function">main</span>() {
pid_t pid = <span class="function">fork</span>();
<span class="keyword">if</span> (pid == <span class="number">0</span>) {
<span class="comment">// Child</span>
<span class="function">printf</span>(<span class="string">"Child doing work...\n"</span>);
<span class="function">sleep</span>(<span class="number">2</span>);
<span class="function">printf</span>(<span class="string">"Child done!\n"</span>);
<span class="function">exit</span>(<span class="number">42</span>); <span class="comment">// exit with code 42</span>
} <span class="keyword">else</span> {
<span class="comment">// Parent waits for child</span>
<span class="builtin">int</span> status;
<span class="function">waitpid</span>(pid, &status, <span class="number">0</span>);
<span class="keyword">if</span> (<span class="function">WIFEXITED</span>(status)) {
<span class="function">printf</span>(<span class="string">"Child exited with code %d\n"</span>,
<span class="function">WEXITSTATUS</span>(status)); <span class="comment">// prints 42</span>
}
}
<span class="keyword">return</span> <span class="number">0</span>;
}</code></pre>
<h3>How a Shell Works (Putting It Together)</h3>
<p>Now you can understand how bash/zsh actually works. When you type <code>ls -la</code> in a shell:</p>
<div class="memory-diagram">
Shell (PID 100)
│
├─ 1. Read your command: "ls -la"
├─ 2. fork() ──→ Child (PID 200) created
│ │
│ ├─ 3. exec("ls", "ls", "-la")
│ │ (child becomes ls)
│ ├─ 4. ls runs, prints output
│ └─ 5. ls exits
│
├─ 6. wait() returns (child done)
└─ 7. Print prompt, go to step 1</div>
<p>This fork+exec pattern is also why redirection (<code>></code>, <code><</code>, <code>|</code>) works. Between the <code>fork()</code> and <code>exec()</code>, the shell can manipulate the child's file descriptors (close stdout, open a file on fd 1) before the new program starts. The new program inherits the modified file descriptors and doesn't even know its output is going to a file instead of the terminal.</p>
<div class="tip-box">
<div class="label">Zombie Processes</div>
<p>If a child exits but its parent never calls <code>wait()</code>, the child becomes a <strong>zombie</strong> -- it's dead but its PCB entry stays in the process table (so the parent can check its exit code later). Zombies waste a slot in the process table. If the parent dies too, <code>init</code> (PID 1) adopts the orphan and reaps it.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 5: CPU SCHEDULING -->
<!-- ============================================================ -->
<section id="scheduling">
<h2>5. CPU Scheduling</h2>
<p>The CPU can only run one process at a time (per core). The <strong>scheduler</strong> decides which process runs next and for how long. The goal: make it feel like everything runs simultaneously.</p>
<h3>Key Metrics</h3>
<ul>
<li><strong>Turnaround time</strong> = completion time - arrival time (how long from submission to finish)</li>
<li><strong>Response time</strong> = first-run time - arrival time (how long until first interaction)</li>
<li><strong>Fairness</strong> -- every process gets a reasonable share of CPU</li>
</ul>
<div class="formula-box">
<strong>Scheduling Metrics (Precise Definitions):</strong><br><br>
• <strong>Turnaround time</strong> = completion_time - arrival_time<br>
• <strong>Response time</strong> = first_run_time - arrival_time<br>
• <strong>Waiting time</strong> = turnaround_time - burst_time<br>
• <strong>Throughput</strong> = number_of_processes / total_time
</div>
<h3>Scheduling Algorithms</h3>
<table>
<tr><th>Algorithm</th><th>How It Works</th><th>Pros / Cons</th></tr>
<tr>
<td><strong>FIFO</strong></td>
<td>First come, first served. Run each job to completion.</td>
<td>Simple. But a long job blocks everything behind it (<em>convoy effect</em>).</td>
</tr>
<tr>
<td><strong>SJF</strong></td>
<td>Shortest Job First. Run the shortest job next.</td>
<td>Optimal turnaround time. But you can't always predict job length.</td>
</tr>
<tr>
<td><strong>Round Robin</strong></td>
<td>Give each process a fixed <em>time slice</em> (quantum, e.g. 10ms). Rotate through the ready queue.</td>
<td>Good response time. Fair. But poor turnaround for long jobs.</td>
</tr>
<tr>
<td><strong>MLFQ</strong></td>
<td>Multi-Level Feedback Queue. Multiple priority queues. New jobs start at highest priority. If a job uses its full time slice, it moves down. I/O-bound jobs stay high.</td>
<td>Best of both worlds -- responsive to interactive tasks AND handles long jobs. Used by real OSes.</td>
</tr>
</table>
<div class="example-box">
<div class="label">Example: Round Robin with quantum = 2</div>
<p>Three processes arrive at time 0: A (needs 5 units), B (needs 3 units), C (needs 1 unit).</p>
<pre><code><span class="lang-label">Timeline</span>
Time: 0 1 2 3 4 5 6 7 8
CPU: A A B B C A A B A
└──┘ └──┘ │ └──┘ │ │
A:2 B:2 C done B done A done
t=5 t=8 t=9</code></pre>
<p>C finishes at time 5, B at time 8, A at time 9. Compare with FIFO (A, B, C): C wouldn't start until time 8!</p>
</div>
<h3>Preemption</h3>
<p>Modern schedulers are <strong>preemptive</strong> -- they can forcibly stop a running process and switch to another. This uses a hardware <strong>timer interrupt</strong> that fires periodically (every 1-10ms). When it fires, the OS gets control and can decide to switch processes. Without preemption, a process could hog the CPU forever.</p>
<div class="tip-box">
<div class="label">Linux Uses CFS</div>
<p>Linux uses the <strong>Completely Fair Scheduler (CFS)</strong>. It tracks how much CPU time each process has gotten ("virtual runtime") and always runs the process with the <em>least</em> virtual runtime. This ensures fairness over time. It uses a red-black tree to pick the next process in O(log n).</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 6: THREADS & CONCURRENCY -->
<!-- ============================================================ -->
<section id="threads">
<h2>6. Threads & Concurrency</h2>
<p>A <strong>thread</strong> is a lightweight unit of execution within a process. One process can have multiple threads, and they all share the same address space (code, heap, global data). Each thread has its own <strong>stack</strong> and <strong>registers</strong>.</p>
<h3>Processes vs Threads</h3>
<table>
<tr><th>Aspect</th><th>Process</th><th>Thread</th></tr>
<tr><td>Memory</td><td>Separate address space</td><td>Shared address space</td></tr>
<tr><td>Creation cost</td><td>Expensive (copy page table)</td><td>Cheap (just a new stack)</td></tr>
<tr><td>Communication</td><td>IPC needed (pipes, sockets)</td><td>Read/write shared memory directly</td></tr>
<tr><td>Crash impact</td><td>One crash doesn't affect others</td><td>One crash kills all threads in process</td></tr>
<tr><td>Context switch</td><td>Slow (switch page table)</td><td>Fast (same page table)</td></tr>
</table>
<div class="memory-diagram">
Process (PID 100)
┌──────────────────────────────────┐
│ Code (shared) │
│ Heap (shared) │
│ Global data (shared) │
│ │
│ ┌──────┐ ┌──────┐ ┌──────┐ │
│ │Stack │ │Stack │ │Stack │ │
│ │ T1 │ │ T2 │ │ T3 │ │
│ └──────┘ └──────┘ └──────┘ │
│ Thread 1 Thread 2 Thread 3 │
└──────────────────────────────────┘</div>
<h3>Why Threads Are Useful</h3>
<ul>
<li><strong>Parallelism</strong> -- on a multi-core CPU, threads can run on different cores simultaneously. A 4-core machine can truly run 4 threads at once.</li>
<li><strong>Avoiding blocking</strong> -- if one thread is waiting for I/O, other threads keep running. A web server uses one thread per connection so slow clients don't block fast ones.</li>
<li><strong>Sharing state</strong> -- threads can share data structures without the complexity of inter-process communication.</li>
</ul>
<h3>Creating Threads (pthreads)</h3>
<pre><code><span class="lang-label">C</span>
<span class="keyword">#include</span> <span class="string"><stdio.h></span>
<span class="keyword">#include</span> <span class="string"><pthread.h></span>
<span class="builtin">void</span>* <span class="function">worker</span>(<span class="builtin">void</span>* arg) {
<span class="builtin">int</span> id = *(<span class="builtin">int</span>*)arg;
<span class="function">printf</span>(<span class="string">"Thread %d running\n"</span>, id);
<span class="keyword">return</span> NULL;
}
<span class="builtin">int</span> <span class="function">main</span>() {
pthread_t threads[<span class="number">4</span>];
<span class="builtin">int</span> ids[<span class="number">4</span>] = {<span class="number">0</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>};
<span class="keyword">for</span> (<span class="builtin">int</span> i = <span class="number">0</span>; i < <span class="number">4</span>; i++) {
<span class="function">pthread_create</span>(&threads[i], NULL, worker, &ids[i]);
}
<span class="comment">// Wait for all threads to finish</span>
<span class="keyword">for</span> (<span class="builtin">int</span> i = <span class="number">0</span>; i < <span class="number">4</span>; i++) {
<span class="function">pthread_join</span>(threads[i], NULL);
}
<span class="function">printf</span>(<span class="string">"All threads done\n"</span>);
<span class="keyword">return</span> <span class="number">0</span>;
}</code></pre>
<p>Compile with: <code>gcc -pthread thread_example.c -o thread_example</code></p>
<h3>The Concurrency Problem: Race Conditions</h3>
<p>Shared memory is both the best and worst thing about threads. If two threads modify the same variable without coordination, you get a <strong>race condition</strong>.</p>
<pre><code><span class="lang-label">C</span>
<span class="builtin">int</span> counter = <span class="number">0</span>; <span class="comment">// shared between threads</span>
<span class="builtin">void</span>* <span class="function">increment</span>(<span class="builtin">void</span>* arg) {
<span class="keyword">for</span> (<span class="builtin">int</span> i = <span class="number">0</span>; i < <span class="number">1000000</span>; i++) {
counter++; <span class="comment">// NOT atomic! This is actually 3 steps:</span>
<span class="comment">// 1. Load counter from memory into register</span>
<span class="comment">// 2. Add 1 to register</span>
<span class="comment">// 3. Store register back to memory</span>
}
<span class="keyword">return</span> NULL;
}
<span class="comment">// If 2 threads run increment(), you'd expect counter = 2,000,000</span>
<span class="comment">// But you'll get something less -- maybe 1,500,000 -- because</span>
<span class="comment">// the threads interleave those 3 steps unpredictably</span></code></pre>
<div class="memory-diagram">
Thread A Thread B
───────── ─────────
load counter (= 5)
load counter (= 5)
add 1 (= 6)
add 1 (= 6)
store counter (= 6)
store counter (= 6) ← LOST UPDATE!
Both threads incremented, but counter only went from 5 to 6, not 5 to 7.</div>
<p>This is why we need locks and synchronisation, covered in the next section.</p>
</section>
<!-- ============================================================ -->
<!-- SECTION 7: LOCKS & SYNCHRONIZATION -->
<!-- ============================================================ -->
<section id="locks">
<h2>7. Locks & Synchronization</h2>
<p>A <strong>lock</strong> (mutex) ensures that only one thread can access a shared resource at a time. The pattern is always the same:</p>
<div class="formula-box">
lock(&mutex);
// critical section -- only one thread at a time here
// access shared data safely
unlock(&mutex);
</div>
<pre><code><span class="lang-label">C</span>
<span class="keyword">#include</span> <span class="string"><pthread.h></span>
<span class="builtin">int</span> counter = <span class="number">0</span>;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
<span class="builtin">void</span>* <span class="function">increment</span>(<span class="builtin">void</span>* arg) {
<span class="keyword">for</span> (<span class="builtin">int</span> i = <span class="number">0</span>; i < <span class="number">1000000</span>; i++) {
<span class="function">pthread_mutex_lock</span>(&lock);
counter++; <span class="comment">// safe now -- only one thread at a time</span>
<span class="function">pthread_mutex_unlock</span>(&lock);
}
<span class="keyword">return</span> NULL;
}
<span class="comment">// Now 2 threads will correctly produce counter = 2,000,000</span></code></pre>
<h3>Condition Variables</h3>
<p>Sometimes a thread needs to <em>wait</em> for a condition, not just for a lock. A <strong>condition variable</strong> lets a thread sleep until another thread signals it.</p>
<p>Classic pattern: producer/consumer queue.</p>
<pre><code><span class="lang-label">C</span>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
<span class="builtin">int</span> ready = <span class="number">0</span>;
<span class="comment">// Thread A: producer</span>
<span class="function">pthread_mutex_lock</span>(&lock);
ready = <span class="number">1</span>;
<span class="function">pthread_cond_signal</span>(&cond); <span class="comment">// wake up the consumer</span>
<span class="function">pthread_mutex_unlock</span>(&lock);
<span class="comment">// Thread B: consumer</span>
<span class="function">pthread_mutex_lock</span>(&lock);
<span class="keyword">while</span> (!ready) { <span class="comment">// always use while, not if</span>
<span class="function">pthread_cond_wait</span>(&cond, &lock); <span class="comment">// releases lock, sleeps, re-acquires</span>
}
<span class="comment">// ready == 1 here, process the data</span>
<span class="function">pthread_mutex_unlock</span>(&lock);</code></pre>
<div class="warning-box">
<div class="label">Always Use while, Not if</div>
<p>Use <code>while (!condition)</code>, never <code>if (!condition)</code> before <code>cond_wait</code>. The thread can be woken <em>spuriously</em> (without the condition actually being true). The while loop rechecks and goes back to sleep if it was a false alarm.</p>
</div>
<h3>Semaphores</h3>
<p>A <strong>semaphore</strong> is a generalised lock with a counter. A mutex is a semaphore with value 1. A semaphore with value N lets N threads in simultaneously.</p>
<div class="formula-box">
sem_wait(&sem): if sem > 0, decrement and continue. If sem == 0, block.
sem_post(&sem): increment sem. If threads are waiting, wake one up.
</div>
<p>Use case: limit concurrent database connections to 10.</p>
<pre><code><span class="lang-label">C</span>
<span class="keyword">#include</span> <span class="string"><semaphore.h></span>
sem_t pool;
<span class="function">sem_init</span>(&pool, <span class="number">0</span>, <span class="number">10</span>); <span class="comment">// allow 10 concurrent connections</span>
<span class="comment">// Each worker thread:</span>
<span class="function">sem_wait</span>(&pool); <span class="comment">// decrement (blocks if 0)</span>
<span class="comment">// ... use the connection ...</span>
<span class="function">sem_post</span>(&pool); <span class="comment">// increment (wake up a waiter)</span></code></pre>
</section>
<!-- ============================================================ -->
<!-- SECTION 8: DEADLOCKS -->
<!-- ============================================================ -->
<section id="deadlocks">
<h2>8. Deadlocks</h2>
<p>A <strong>deadlock</strong> occurs when two or more threads are each waiting for a resource held by another, and none can make progress. Everyone's stuck forever.</p>
<div class="memory-diagram">
Thread A Thread B
──────── ────────
lock(mutex1) ✓
lock(mutex2) ✓
lock(mutex2) BLOCKED!
(waiting for B) lock(mutex1) BLOCKED!
(waiting for A)
──→ DEADLOCK! Neither can proceed.</div>
<h3>Four Conditions for Deadlock</h3>
<p>ALL four must be true simultaneously for deadlock to occur (Coffman conditions):</p>
<ol>
<li><strong>Mutual exclusion</strong> -- resources can't be shared (only one thread holds a lock at a time)</li>
<li><strong>Hold and wait</strong> -- a thread holds one resource while waiting for another</li>
<li><strong>No preemption</strong> -- you can't forcibly take a lock from a thread</li>
<li><strong>Circular wait</strong> -- A waits for B, B waits for C, C waits for A</li>
</ol>
<p>Break any one condition and deadlock becomes impossible.</p>
<div class="formula-box">
<strong>Coffman Conditions for Deadlock (All Four Must Hold):</strong><br><br>
1. <strong>Mutual Exclusion:</strong> At least one resource is non-sharable<br>
2. <strong>Hold and Wait:</strong> A process holds resources while waiting for others<br>
3. <strong>No Preemption:</strong> Resources cannot be forcibly taken from a process<br>
4. <strong>Circular Wait:</strong> A cycle exists in the resource-allocation graph<br><br>
<strong>Break any one condition → no deadlock possible.</strong>
</div>
<h3>Prevention Strategies</h3>
<table>
<tr><th>Strategy</th><th>How</th><th>Breaks Which Condition</th></tr>
<tr><td>Lock ordering</td><td>Always acquire locks in the same global order</td><td>Circular wait</td></tr>
<tr><td>Lock all at once</td><td>Grab all needed locks atomically before doing work</td><td>Hold and wait</td></tr>
<tr><td>Try-lock</td><td>Use <code>trylock()</code> -- if you can't get the lock, release everything and retry</td><td>Hold and wait</td></tr>
<tr><td>Single lock</td><td>Use one big lock instead of many fine-grained ones</td><td>Circular wait (but hurts performance)</td></tr>
</table>
<div class="tip-box">
<div class="label">Practical Advice</div>
<p><strong>Lock ordering</strong> is the most common real-world solution. If every thread always locks mutex1 before mutex2, circular wait is impossible. Assign a global order to all locks and enforce it everywhere.</p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 9: MEMORY & ADDRESS SPACES -->
<!-- ============================================================ -->
<section id="memory">
<h2>9. Memory & Address Spaces</h2>
<p>Every process thinks it has its own private, contiguous block of memory starting at address 0. This is a <strong>virtual address space</strong> -- an illusion created by the OS and hardware.</p>
<h3>Layout of a Process's Address Space</h3>
<div class="memory-diagram">
High addresses
┌─────────────────────────┐ 0xFFFFFFFF...
│ Stack │ ← Local variables, function call frames
│ ↓ │ Grows downward
│ │
│ (free space) │
│ │
│ ↑ │
│ Heap │ ← malloc/new allocations
│ │ Grows upward
├─────────────────────────┤
│ BSS (uninit data) │ ← Global vars initialized to 0
├─────────────────────────┤
│ Data (init data) │ ← Global vars with initial values
├─────────────────────────┤
│ Code │ ← Your compiled machine instructions
│ (Text) │ (read-only)
└─────────────────────────┘ 0x00000000
Low addresses</div>
<h3>Virtual vs Physical Addresses</h3>
<p>When your program accesses address <code>0x00401000</code>, that's a <strong>virtual address</strong>. The CPU's Memory Management Unit (MMU) translates it to a <strong>physical address</strong> in actual RAM. Different processes can use the same virtual address but they map to different physical locations.</p>
<div class="memory-diagram">
Process A Physical RAM
Virtual addr 0x1000 ──────→ Physical addr 0x50000
Virtual addr 0x2000 ──────→ Physical addr 0x80000
Process B
Virtual addr 0x1000 ──────→ Physical addr 0xA0000 (different!)
Virtual addr 0x2000 ──────→ Physical addr 0xC0000 (different!)</div>
<p>This is why processes can't read each other's memory -- their virtual address 0x1000 maps to completely different physical locations.</p>
<h3>Stack vs Heap</h3>
<table>
<tr><th>Stack</th><th>Heap</th></tr>
<tr><td>Automatic allocation/deallocation</td><td>Manual (<code>malloc</code>/<code>free</code>, <code>new</code>/<code>delete</code>)</td></tr>
<tr><td>Very fast (just move stack pointer)</td><td>Slower (search for free block)</td></tr>
<tr><td>Fixed size (~1-8 MB typically)</td><td>Can grow to fill available memory</td></tr>
<tr><td>Local variables, function args</td><td>Dynamic data, objects, arrays of unknown size</td></tr>
<tr><td>LIFO order</td><td>Any order</td></tr>
</table>
<h3>The malloc/free Dance</h3>
<p><code>malloc()</code> doesn't always make a syscall. It manages a <em>free list</em> of previously-freed blocks in user space. Only when it runs out does it call <code>sbrk()</code> or <code>mmap()</code> to ask the kernel for more memory.</p>
<pre><code><span class="lang-label">C</span>
<span class="comment">// Allocate 100 ints on the heap</span>
<span class="builtin">int</span>* arr = <span class="function">malloc</span>(<span class="number">100</span> * <span class="keyword">sizeof</span>(<span class="builtin">int</span>));
<span class="keyword">if</span> (!arr) { <span class="comment">/* out of memory */</span> }
arr[<span class="number">0</span>] = <span class="number">42</span>;
arr[<span class="number">99</span>] = <span class="number">99</span>;
<span class="comment">// MUST free when done -- OS doesn't free it for you (until process exits)</span>
<span class="function">free</span>(arr);
arr = NULL; <span class="comment">// good practice: avoid dangling pointer</span></code></pre>
<div class="warning-box">
<div class="label">Common Memory Bugs</div>
<ul>
<li><strong>Memory leak</strong> -- <code>malloc()</code> without <code>free()</code>. Memory usage grows forever.</li>
<li><strong>Use after free</strong> -- access memory after <code>free()</code>. Undefined behavior.</li>
<li><strong>Double free</strong> -- call <code>free()</code> twice on the same pointer. Corrupts the allocator.</li>
<li><strong>Buffer overflow</strong> -- write past the end of an array. Can overwrite other data or code.</li>
</ul>
<p>Use <code>valgrind</code> to detect these: <code>valgrind ./my_program</code></p>
</div>
</section>
<!-- ============================================================ -->
<!-- SECTION 10: PAGING & VIRTUAL MEMORY -->
<!-- ============================================================ -->
<section id="paging">
<h2>10. Paging & Virtual Memory</h2>
<p>The OS divides both virtual and physical memory into fixed-size chunks called <strong>pages</strong> (typically 4 KB). The mapping from virtual pages to physical frames is stored in a <strong>page table</strong>.</p>
<h3>Address Translation</h3>
<div class="formula-box">
Virtual address = Page Number + Offset within page
Example with 4 KB (4096-byte) pages:
Virtual address 0x00005A30
Page number = 0x00005A30 / 4096 = 0x5 (page 5)
Offset = 0x00005A30 % 4096 = 0xA30 (byte 2608 within the page)
Look up page 5 in page table → physical frame 0x7C
Physical address = 0x7C * 4096 + 0xA30 = 0x7CA30
</div>
<h3>Page Table Entry</h3>
<p>Each entry in the page table contains:</p>
<ul>
<li><strong>Physical frame number</strong> -- where this page lives in RAM</li>
<li><strong>Valid bit</strong> -- is this page actually in RAM? (0 = not mapped or swapped out)</li>
<li><strong>Protection bits</strong> -- read/write/execute permissions</li>
<li><strong>Dirty bit</strong> -- has this page been modified? (needs writing to disk before eviction)</li>
<li><strong>Referenced bit</strong> -- has this page been accessed recently?</li>
</ul>
<h3>TLB -- Making It Fast</h3>
<p>Looking up the page table on every memory access would be unbearably slow. The <strong>Translation Lookaside Buffer (TLB)</strong> is a tiny, ultra-fast cache inside the CPU that stores recent page-to-frame translations.</p>
<div class="memory-diagram">
CPU generates virtual address