⚡ TechVani: AI, Technology, Apps, Coding & Digital World
TechVaniAI • Technology • Apps • Coding • Digital World
HomeAI & TechAppsCodingFree AI ToolsStudent TechSecurityAboutContactPrivacy
TECHVANI // LEARN. BUILD. TEST.

Learn the tech. Build the idea.

Clear study notes, tested lab files and practical guides for coding, AI and digital safety.

Explore Latest →
šŸ¤– AI & TechAI news, tools & guides šŸ“± Apps & ToolsUseful apps & websites šŸ’» CodingProgramming & web development šŸŽ“ Student TechStudy & career technology šŸ” Cyber SecuritySafety & awareness

Latest Posts

Circuit Notebook theme

Exam Notes

šŸ“š BTech CSE Exam Notes

Find Semester 1-8 subjects in one place. Choose a semester and open the notes you need. This is a general study guide, not an official syllabus.

Open Exam Notes →🧪 Open Lab Files →

Exam Numericals & Study Series

Practice CPU scheduling and explore OS and DBMS topics in separate, easy-to-follow parts. New topics will appear in the hub as they are published.

Open Numericals Hub →

Start here and stay in touch

New to TechVani? Start with our free AI tools guide for students. It covers which tools to try and what to check before relying on an answer.

For step-by-step videos, visit SiteSudhar on YouTube.

Join TechVani on WhatsApp

Get new AI tools and coding guides in your WhatsApp Updates tab.

Browse Topics

Popular Posts

TechVani

Process States in OS: Diagram, PCB and Context Switching

OS Notes Part 1: Process States, PCB and Context Switching

The basic process states in OS are Ready, Running and Blocked: Ready waits for a CPU, Running uses it, and Blocked waits for an event such as I/O completion. Scheduler dispatch changes Ready to Running; I/O completion changes Blocked to Ready, not directly to Running. The five-state model also includes New and Terminated.

When you open a program, the operating system creates a process: a running instance of that program with memory and other resources. A saved program file is not itself a running process. This guide explains the common three-state model, shows a trace you can follow in an exam, and clears up two frequent mistakes.

Process state transitions

Ready: waits for CPU
Dispatch -> Running
Preempt -> Ready
I/O wait -> Blocked
I/O complete -> Ready
Concept map. Follow the stated algorithm and assumptions in the worked examples below.

These are general BTech CSE study notes, not an official university syllabus. For the broad subject overview, start with Operating Systems Semester 3 Core Notes. For practical C exercises, use the Operating Systems Lab File.

1. Process versus program versus thread

TermPlain meaningExample
ProgramInstructions stored in a fileAn editor application installed on disk
ProcessOne running instance, with its own address space and execution stateAn editor instance opened by a student
ThreadA path of execution inside a process; threads share that process's address space but have separate execution stacksA background task in the editor

Two instances of the same program may be separate processes. A process can also have several threads. Do not use "process" and "program" as synonyms in an answer.

2. The three basic process states

  • Running: the process is executing on a CPU.
  • Ready: it can run but is waiting for CPU time.
  • Blocked (waiting): it cannot continue until an event occurs, such as an I/O operation finishing.

These are a simplified teaching model. Some syllabi add New and Terminated, making a five-state diagram. Real systems may use more detailed states. Always match your course's diagram when writing a labelled exam answer.

3. State-transition diagram

Follow each arrow only when its label is true. The diagram shows the three-state teaching model; New and Terminated sit outside it.

Three-state process diagram: each row is one valid transition
From stateEvent on the arrowTo state
Ready⟶ scheduler dispatchesRunning
Running⟶ I/O request needs waitingBlocked
Blocked⟶ I/O completesReady
Running⟶ timer preemptsReady

4. State transitions in one worked trace

Suppose an editor process P is ready, gets the CPU, requests a file read, waits for the read, and later finishes its work. Track the state after each event:

  1. Scheduler chooses P: Ready → Running. P can now execute instructions.
  2. P requests a file read and must wait: Running → Blocked. It is not merely waiting its turn for the CPU.
  3. The file read finishes: Blocked → Ready. Completion does not mean P instantly owns the CPU.
  4. Scheduler chooses P again: Ready → Running.
  5. P finishes: the process exits. If using a five-state diagram, mark Terminated.

A timer may also take a running process off the CPU while it is still able to run: Running → Ready. By contrast, a blocked process first needs its event before it becomes ready. This is the key distinction in many short-answer questions.

5. What is in a Process Control Block (PCB)?

The OS keeps a record for each process so it can manage and resume it. This record is commonly called the PCB. A teaching-level PCB may include a process identifier, current state, program counter, CPU registers, scheduling information, memory-management information and information about open resources. Exact fields differ by operating system; the list is a model, not a promise about every kernel's structure.

When a running process stops, the OS needs enough saved execution state to continue it later. The program counter points to where execution should continue; saved registers preserve values needed by that execution. A process's entire memory is not copied on every ordinary context switch.

6. Context switch versus state change

A context switch changes which process or thread runs on a CPU by saving one execution context and restoring another. It costs time because the CPU and OS do work other than the students' programs. State changes and context switches are related but not identical: a blocked process may become ready when I/O finishes without immediately running, while a timer can cause a Running → Ready transition and a different ready process to run.

Exam tip: For a trace, write the event first, then the before-and-after states. Do not jump directly from Blocked to Running just because I/O finished.

7. Try it yourself

  1. A process is able to run but another process has the CPU. What state is it in?
  2. A process waits for keyboard input. Does a longer CPU time slice alone unblock it?
  3. After disk I/O completes, what state does the waiting process usually enter before being selected?
  4. Name two execution details the OS may save to resume a process.
Answers
  1. Ready.
  2. No. It needs the input event; it is Blocked while waiting.
  3. Ready.
  4. For example, the program counter and CPU registers.

8. Five-state extension: draw events, not unlabelled arrows

New means creation/admission is not finished; Terminated means execution has ended. Keep Ready, Running and Blocked as the three live execution states in this teaching model. A suspended-state model adds another distinction and is not the same diagram.

New → Ready
admission
Ready → Running → Terminated
dispatch, then exit
Running → Blocked → Ready
wait for an event, then event completes
Running → Ready
preemption while still able to run

Only the dispatch arrow gives CPU ownership. The wakeup arrow makes a process eligible; it does not promise immediate execution. On one CPU, one execution context runs at a time in this simplified model. On multiple cores, different threads can run at the same time.

9. Two-process trace: an I/O completion is not a CPU handover

Start with P and Q Ready and the CPU idle. The following Python validator checks each transition. Idle gaps in the printout are explicit event boundaries, not measured delays. We count process-to-process handovers P→Q, Q→P and P→Q; initial idle→P is excluded. No scheduling policy or time slice is inferred from this trace.

# Teaching model: one CPU, two processes, explicit events.
# This validates a trace; it is not an OS scheduler.
state = {"P": "Ready", "Q": "Ready"}
cpu = None
last = None
switches = 0
events = [("dispatch", "P"), ("block", "P"),
          ("dispatch", "Q"), ("wake", "P"),
          ("preempt", "Q"), ("dispatch", "P"),
          ("exit", "P"), ("dispatch", "Q")]
for event, pid in events:
    if event == "dispatch":
        assert cpu is None and state[pid] == "Ready"
        switches += int(last is not None and last != pid)
        cpu = last = pid
        state[pid] = "Running"
    elif event == "wake":
        assert state[pid] == "Blocked"
        state[pid] = "Ready"  # does NOT replace the current CPU owner
    else:
        assert cpu == pid and state[pid] == "Running"
        state[pid] = {"block": "Blocked", "preempt": "Ready",
                      "exit": "Terminated"}[event]
        cpu = None
    print(f"{event:8} {pid} | P={state['P']:10} Q={state['Q']:10} CPU={cpu or '-'}")
print("Process-to-process switches:", switches)
assert switches == 3 and state == {"P": "Terminated", "Q": "Running"}

Tested output:

dispatch P | P=Running    Q=Ready      CPU=P
block    P | P=Blocked    Q=Ready      CPU=-
dispatch Q | P=Blocked    Q=Running    CPU=Q
wake     P | P=Ready      Q=Running    CPU=Q
preempt  Q | P=Ready      Q=Ready      CPU=-
dispatch P | P=Running    Q=Ready      CPU=P
exit     P | P=Terminated Q=Ready      CPU=-
dispatch Q | P=Terminated Q=Running    CPU=Q
Process-to-process switches: 3

At wake P, Q remains Running and P becomes Ready. At preempt Q, Q is Ready and the CPU becomes available. A real kernel may select Q again if there is no better candidate: a timer interrupt does not guarantee a switch to a different process.

10. PCB fields: explain why each is kept

Teaching-level fieldWhy the OS needs it
PID and process stateIdentify the process and whether it can be scheduled.
Program counter, stack pointer, saved registersResume the execution context at its saved point.
Scheduling informationChoose eligible work and track policy/accounting.
Memory-management informationFind the address space/page tables; not a full memory copy per switch.
Open-resource referencesTrack open files and other resources held by the process.

The PCB is kernel bookkeeping, not the process's entire address space. Threads need their own saved execution context even when they share process memory and resources. A same-process thread switch can avoid changing address spaces, but it still saves/restores an execution context.

11. Context-switch cost: one transparent numerical

Assume four useful CPU slices of 4 ms each and exactly three handovers, each costing 0.2 ms. Exclude initial dispatch, idle time, interrupts, I/O time and all other costs. These are invented exam inputs, not a benchmark.

  • Useful work = 4 × 4 = 16 ms.
  • Switch overhead = 3 × 0.2 = 0.6 ms.
  • Total elapsed under these assumptions = 16.6 ms.
  • Useful fraction = 16 / 16.6 × 100 ≈ 96.39%.

The arithmetic was checked with Python Decimal. Do not present 0.2 ms as a universal context-switch cost: hardware, kernel, workload and cache effects matter. The final exit-to-idle cost is excluded because this problem defines only three process-to-process handovers. Count the boundaries the question actually includes.

12. Exam mistakes and viva answers

QuestionAnswer and reason
Does every file read block?No. This trace assumes a read that needs waiting; data may already be available or an API may be nonblocking.
Ready versus Blocked?Ready lacks CPU time; Blocked lacks an event/resource needed to continue.
Can Blocked go directly to Running here?Not as one labelled transition: wakeup makes Ready, then dispatch makes Running.
Is a system call automatically a context switch?No. User→kernel mode may return to the same process; a blocking call may instead let another context run.
Does an I/O interrupt always switch processes?No. It can make a waiting process Ready while the current one continues.
Is a zombie just a blocked process?No. A Linux zombie has exited but status is still retained for collection; it is not waiting to resume normal execution.
Does the PCB store all process memory?No. It holds management information/references and saved state in a teaching model.
Does a bigger quantum fix input waiting?No. The input event, not extra CPU time, makes the blocked process runnable.

Linux labels are not a one-to-one copy of the classroom diagram: /proc reports S (interruptible sleep), D (uninterruptible sleep) and Z (zombie), among others. Learn the exam model first and use the kernel documentation for system-specific states.

13. Sources and a final self-check

Grounding: OSTEP process chapter slides for states, saved context and PCB; Linux Kernel Labs process lecture for task structures, wakeup and context switching; Linux /proc/pid/stat manual for real state letters.

Self-check: P is Blocked, Q is Running, then P's input arrives. Answer: P becomes Ready; Q need not stop. Name the later event that could make P Running: scheduler dispatch.

Continue studying

The OS core notes cover scheduling, synchronization, deadlock, virtual memory and files. The OS lab file gives 12 C practicals and sample outputs; use a compatible local system for POSIX-specific exercises. A free deeper reference is Operating Systems: Three Easy Pieces, especially its process and scheduling chapters.

Comments