Show 25 50 100
PDF
10 result(s) in Operating System Clear

Index

Showing 10 topics
  1. What is an Operating System
  2. Process vs Thread
  3. Process States
  4. CPU Scheduling Algorithms
  5. Process Synchronization
  6. Deadlock
  7. Memory Management and Paging
  8. Virtual Memory and Page Replacement
  9. System Calls and User/Kernel Mode
  10. File System and Disk Scheduling
1 Index

An operating system is system software that manages computer hardware and provides services to programs. Examples: Windows, Linux, macOS, Android.

The OS is the layer between programs and hardware

The OS is the layer between programs and hardware

Main functions: process management, memory management, file system management, device (I/O) management, security and protection, user interface.

TypeIdeaExample
BatchJobs grouped and run without interactionEarly mainframes
MultiprogrammingSeveral programs in memory, CPU switches when one waits for I/O—
Time-sharing (multitasking)CPU time is sliced between users/programsUnix, Windows
Real-timeMust respond within a strict deadlineAir-bag controller, RTOS
DistributedMany computers act like one systemCluster systems

Q & A

  1. What is the kernel?
    The core part of the OS that runs in privileged mode and directly controls CPU, memory and devices.
  2. Monolithic vs microkernel?
    Monolithic: all services (drivers, file system) run inside the kernel, fast (Linux). Microkernel: only minimal services in the kernel, the rest in user space, more stable and secure but slower (Minix, QNX).
2 Index

A process is a program in execution, with its own memory space. A thread is the smallest unit of execution inside a process; threads of the same process share its memory.

ProcessThread
HeavyweightLightweight
Own memory (code, data, heap, stack)Shares code, data and heap; has its own stack and registers
Context switch is slowContext switch is fast
Communicate via IPC (pipes, sockets, shared memory)Communicate directly through shared memory
One crashing does not affect othersOne crashing thread can crash the whole process

PCB (Process Control Block) stores everything about a process: PID, state, program counter, registers, memory info, open files, priority.

Context switch: saving the state of the running process in its PCB and loading the next one.

3 Index

New → Ready → Running → Waiting → Terminated

New → Ready → Running → Waiting → Terminated

  • New — being created.
  • Ready — waiting for the CPU.
  • Running — instructions are executing.
  • Waiting / Blocked — waiting for I/O or an event.
  • Terminated — finished.

Zombie process: finished but its parent has not read its exit status. Orphan process: its parent ended first (adopted by init).

4 Index

Terms: Burst time (CPU time needed), Arrival time, Completion time, Turnaround time = Completion − Arrival, Waiting time = Turnaround − Burst, Response time = first run − arrival.

AlgorithmTypeIdeaProblem
FCFSNon-preemptiveFirst come, first servedConvoy effect (short jobs wait behind a long one)
SJFNon-preemptiveShortest burst first; minimum average waiting timeStarvation of long jobs; burst time must be known
SRTFPreemptive SJFShortest remaining time firstStarvation
PriorityEitherHighest priority firstStarvation → fixed by aging
Round RobinPreemptiveEach process gets a time quantum in turnToo small quantum = many context switches
Multilevel QueueEitherSeparate queues (system, interactive, batch)Rigid

Round Robin example with its waiting and turnaround times

Round Robin example with its waiting and turnaround times

FCFS average waiting time C++ 7 lines
// FCFS waiting time: each process waits for all bursts before it
int burst[] = {24, 3, 3}, n = 3, wait = 0, total = 0;
for (int i = 0; i < n; i++) {
    total += wait;
    wait += burst[i];
}
cout << "Average waiting = " << (double)total / n;   // (0 + 24 + 27) / 3 = 17
5 Index

When processes/threads share data, a race condition happens if the result depends on the order they run. The code that touches shared data is the critical section.

A correct solution needs: Mutual exclusion (one at a time), Progress and Bounded waiting.

MutexSemaphore
Lock with owner: only the thread that locked can unlockInteger counter changed by wait() / signal()
Binary: locked / unlockedBinary (0/1) or counting (0..n)
Protect one critical sectionAlso limits access to n identical resources
Semaphore operations C 13 lines
// wait (P) and signal (V) — both are atomic
wait(S) {
    while (S <= 0) ;   // busy wait
    S--;
}
signal(S) {
    S++;
}

// usage
wait(mutex);
/* critical section */
signal(mutex);

Classic problems: Producer–Consumer (bounded buffer), Readers–Writers, Dining Philosophers.

6 Index

A deadlock is a state where a set of processes wait forever, each holding a resource the other needs.

Resource allocation graph with a cycle

Resource allocation graph with a cycle

Four necessary conditions (Coffman) — all must hold:

  • Mutual exclusion — a resource is used by one process at a time.
  • Hold and wait — a process holds one resource and waits for another.
  • No preemption — a resource cannot be taken away forcibly.
  • Circular wait — P1 waits for P2, P2 waits for P1 (a cycle).

Handling: Prevention (break one condition), Avoidance (Banker's algorithm, only grant requests that keep the system in a safe state), Detection and recovery (kill a process / preempt resources), or Ignore it (Ostrich approach, used by most desktop OSes).

Q & A

  1. Deadlock vs starvation?
    Deadlock: processes wait for each other forever and none progresses. Starvation: one process waits a very long time because others keep getting priority; the system still progresses.
7 Index
  • Contiguous allocation — each process gets one block; strategies First fit, Best fit, Worst fit; causes external fragmentation.
  • Paging — logical memory split into fixed-size pages, physical memory into frames of the same size; a page table maps them.
  • Segmentation — memory divided by logical units (code, stack, data) of different sizes.
  • TLB — fast cache of recent page-table entries.

Pages do not need to be next to each other in physical memory

Pages do not need to be next to each other in physical memory

Internal fragmentationExternal fragmentation
Wasted space inside an allocated blockFree space is split into small holes between blocks
Happens in paging (last page)Happens in contiguous allocation / segmentation
Fix: smaller blocksFix: compaction or paging
8 Index

Virtual memory lets a program use more memory than physically available by keeping only the needed pages in RAM (demand paging). Accessing a page that is not in RAM causes a page fault. Too many page faults = thrashing.

Example: reference string 7 0 1 2 0 3 0 4, 3 frames

AlgorithmIdeaPage faults
FIFOReplace the page that came in first7
LRUReplace the least recently used page6
OptimalReplace the page not needed for the longest time (theoretical best)6

Belady's anomaly: with FIFO, adding more frames can sometimes increase page faults.

LRU page faults C++ 14 lines
int lruFaults(vector<int> refs, int frames) {
    list<int> cache;                       // front = most recently used
    int faults = 0;
    for (int p : refs) {
        auto it = find(cache.begin(), cache.end(), p);
        if (it != cache.end()) cache.erase(it);          // hit
        else {
            faults++;
            if (cache.size() == frames) cache.pop_back(); // evict LRU
        }
        cache.push_front(p);
    }
    return faults;
}
9 Index

A program runs in user mode. To use hardware (files, network, new process) it makes a system call, which switches the CPU to kernel mode.

CategoryExamples (Linux)
Process controlfork(), exec(), exit(), wait()
File managementopen(), read(), write(), close()
Device managementioctl()
Informationgetpid(), time()
Communicationpipe(), socket(), shmget()
fork() C 10 lines
#include <unistd.h>
#include <stdio.h>

int main() {
    pid_t pid = fork();          // creates a child process
    if (pid == 0) printf("Child, pid = %d\n", getpid());
    else          printf("Parent, child pid = %d\n", pid);
    return 0;
}
// fork() returns 0 in the child and the child's pid in the parent
10 Index
  • File allocation: contiguous (fast, fragmentation), linked (no fragmentation, slow random access), indexed (index block holds pointers, e.g. inodes).
  • Disk access time = seek time + rotational latency + transfer time.
AlgorithmIdea
FCFSServe requests in arrival order
SSTFShortest seek time first (nearest track)
SCAN (elevator)Move to one end serving requests, then reverse
C-SCANServe in one direction only, jump back to the start
LOOK / C-LOOKLike SCAN / C-SCAN but turn at the last request, not the disk end