0% found this document useful (0 votes)
2 views16 pages

CH3 Processes Notes

Uploaded by

sp24-bse-048
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views16 pages

CH3 Processes Notes

Uploaded by

sp24-bse-048
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Operating Systems

Chapter 3: Processes
Detailed Study Notes — Simple Language + Examples
Exam Preparation Guide

1. What is a Process?
Simple Definition: A process is simply a program that is currently running on the
computer. When you double-click an app, it becomes a process.
Technical Definition: A process is a program in execution. It must progress in a
sequential fashion — one instruction at a time, in order.
📌 Real Life Example:
Think of a RECIPE (program) vs. COOKING (process).
The recipe just sits on paper — that is the PROGRAM (passive).
When the cook starts following it step by step — that is the PROCESS (active).

On your computer:
→ '[Link]' sitting on your hard disk = Program
→ Chrome actually running and loading a webpage = Process

1.1 What is inside a Process? (Parts of a Process)


A process in memory is divided into several sections:
● Text Section (Code): The actual program instructions/code. This is what the CPU
reads and executes.
💡 Example: The code like 'if (x > 5) print x' is stored here.
● Data Section: Stores global variables — variables that are declared outside any
function and are available throughout the whole program.
💡 Example: int totalStudents = 100; (declared globally — lives in Data Section)
● Heap: Memory that is dynamically allocated WHILE the program is running. It grows
and shrinks as needed.
💡 Example: When you use malloc() in C or 'new' in Java/C++ to create something at
runtime — that memory comes from the Heap.
● Stack: Stores temporary data — local variables, function parameters, and return
addresses. It works like a stack of plates: last in, first out (LIFO).
💡 Example: When you call a function myFunc(a, b):
→ Parameters a and b are pushed onto the Stack
→ When function finishes, they are popped off

Each function call creates a new 'stack frame'


● Program Counter (PC): A special register that keeps track of which instruction is
going to be executed NEXT.
💡 Example: If line 5 of your code just ran, the PC now points to line 6.
● CPU Registers: Small, very fast storage inside the CPU. The process uses them
for calculations and temporary values.
🔑 KEY DIFFERENCE — Program vs Process:
Program = Passive (just a file on disk, like a recipe book)
Process = Active (the program is loaded into memory and running)

One Program can become MANY Processes!


Example: Open Google Chrome twice → two separate Chrome processes running
(Same program, two processes, each with their own memory)

2. Process States
As a process runs on a computer, it keeps changing its state (situation/condition). Think of
it like a student's day:
📌 Real Life Analogy — Think of a Student:
NEW → Student just enrolled (being created)
READY → Student is sitting in class, waiting for the teacher to call them
RUNNING → Student is presenting/answering (actively using CPU)
WAITING → Student raised hand and is waiting for the teacher to respond (waiting
for I/O)
TERMINATED → Student finished and left the class (process done)

2.1 Five Process States in Detail


● NEW: The process is being created. The OS is setting it up. It has NOT yet been
admitted to the ready queue.
Example: You just double-clicked an app. The OS is loading it into memory.
● READY: The process is loaded in memory, ready to run, and WAITING for the CPU
to be assigned to it. It is in the ready queue.
Example: 5 programs are open. Only one can use CPU at a time. The others are in
READY state — waiting for their turn.
● RUNNING: The process is currently being executed. The CPU is actively working
on it. Only ONE process per CPU core can be RUNNING at any instant.
Example: You are typing in MS Word. Word is in the RUNNING state right now.
● WAITING (Blocked): The process cannot run right now because it is waiting for
something to happen — like waiting for keyboard input, a file to load from disk, or a
network response.
Example: Your program asked for input from user → goes to WAITING state
Or: Program is downloading a file → WAITING for the download to finish
CPU does NOT just sit idle — it goes and runs another process!
● TERMINATED: The process has finished execution. The OS cleans up its memory
and resources.
Example: You close a program → process goes to TERMINATED state → OS frees
the memory.

2.2 State Transitions (How Process Moves Between States)


● New → Ready: When OS admits the process into main memory.
● Ready → Running: When the CPU scheduler picks this process to run.
● Running → Waiting: Process needs I/O or some event (keyboard, disk, network).
● Waiting → Ready: I/O or event is completed; process moves back to ready queue.
● Running → Ready: Process's time slice expired (timer interrupt) — CPU taken
away.
● Running → Terminated: Process finishes execution.

3. Process Control Block (PCB)


Every process has its own ID card stored in the OS — this is called the PCB. When the OS
needs to manage, switch, or track a process, it looks at the PCB.
📌 Real Life Analogy:
Think of the PCB as a STUDENT FILE in a university.
The file contains: Student Name, Roll Number, Courses, Grades, Status
(enrolled/suspended), etc.
Just like each student has their own file, each process has its own PCB.

3.1 Information Stored in PCB


● Process State: Current state — New, Ready, Running, Waiting, or Terminated.
● Process ID (PID): A unique number assigned to the process. Like a student roll
number.
Example: Chrome might have PID 1023, MS Word PID 1024, etc.
● Program Counter (PC): The address of the NEXT instruction to execute. Saved
when the process is paused so it can resume from the exact same place.
Example: If process was paused at instruction 500, PC saves 501 so it resumes from
501.
● CPU Registers: All register values (like accumulators, index registers) are saved
here when the process is swapped out.
● CPU Scheduling Information: Priority of the process, scheduling queue pointers,
etc.
● Memory Management Information: Information about memory allocated to the
process — base registers, page tables, segment tables.
● Accounting Information: CPU time used, time limits, job/process numbers.
● I/O Status Information: List of I/O devices allocated to the process, list of open
files.

4. Context Switch
A context switch is when the CPU stops running one process and starts running another. It
must SAVE the current process's state and LOAD the next process's state.
📌 Real Life Analogy:
Imagine you are solving a Math problem (Process A).
Your phone rings — you stop, put a BOOKMARK on the math book, note where you
were.
You pick up the phone (Process B) and attend the call.
When done, you go BACK to the math book, find your bookmark, and continue.

The 'bookmark' = saving context to PCB


Going back to math = loading context from PCB

4.1 Steps During Context Switch


● Save the state of the CURRENT process into its PCB (program counter, registers,
etc.)
● Update the PCB status of the current process (e.g., set to Ready or Waiting).
● Move the current process to the appropriate queue (ready or waiting).
● Select the NEXT process to run (via scheduler).
● Load the state of the NEW process from its PCB.
● Set Program Counter to where the new process left off.
● Start executing the new process.
🔑 IMPORTANT: Context switch time is PURE OVERHEAD.
While switching, the CPU does NO useful work — it just saves and loads data.
The more complex the OS and PCB, the LONGER the context switch takes.
Modern hardware provides multiple register sets to speed this up.
5. Process Scheduling
The goal of scheduling is to maximize CPU use and quickly switch processes onto the
CPU. The CPU should NEVER be sitting idle if there are processes to run.
📌 Real Life Analogy:
Think of a hospital emergency room.
Many patients (processes) are waiting.
The doctor (CPU) sees one patient at a time.
A NURSE (scheduler) decides who goes next — most critical first, or by arrival time.
Different nurses use different rules = different scheduling algorithms.

5.1 Scheduling Queues


● Job Queue: Contains ALL processes in the system (including those on disk).
● Ready Queue: Contains all processes that are in main memory, ready and
WAITING to execute. This is like the waiting room.
● Device Queues: Each I/O device has its own queue. Processes waiting for that
device wait here.
Example:
5 processes want to print → they all go into the Printer Device Queue
3 processes are ready to use CPU → they are in the Ready Queue

5.2 Types of Schedulers


● Short-Term Scheduler (CPU Scheduler): Decides which process in the READY
queue gets the CPU next. Called very FREQUENTLY — every few milliseconds.
Must be FAST.
Example: Picks next process from ready queue every 10ms (time slice expired)
● Long-Term Scheduler (Job Scheduler): Decides which jobs/processes are
BROUGHT INTO MEMORY from the job pool. Called very INFREQUENTLY —
every few seconds or minutes. Controls the DEGREE OF MULTIPROGRAMMING
(how many processes are in memory at once).
Example: Decides 'OK, we have space for 5 more processes in memory — load them
in.'
● Medium-Term Scheduler: Sometimes used to SWAP processes out of memory to
disk and bring them back later. Helps with memory management when memory is
full.
Example: RAM is full. A process that has been WAITING for a long time gets swapped
to disk.
When it's needed again, it's swapped back in.
5.3 Types of Processes
● I/O-Bound Process: Spends more time doing I/O (input/output) than actual CPU
computation. Has many SHORT CPU bursts. Example: A web browser waiting for
data from internet, a text editor waiting for user input.
● CPU-Bound Process: Spends more time doing calculations (computation). Has
few but LONG CPU bursts. Example: A video encoding program, a scientific
simulation, rendering 3D graphics.
🔑 Long-term scheduler should maintain a GOOD MIX of I/O-bound and CPU-bound
processes.
If all processes are CPU-bound → I/O devices sit idle.
If all processes are I/O-bound → CPU sits idle.
A good mix keeps everything busy!

6. Process Creation
Processes are created by other processes. The creating process is called the PARENT,
and the created process is called the CHILD. This forms a TREE of processes.
📌 Real Life Analogy:
Think of a FAMILY TREE:
Grandparent Process → creates Parent Process → creates Child Process

In Linux/UNIX, when you start your computer:


→ 'init' process starts first (PID = 1) — this is the ancestor of ALL processes
→ init creates login process
→ login creates shell (e.g., bash)
→ shell creates every program you run

6.1 Resource Sharing Options


● Option 1: Parent and child SHARE ALL resources.
● Option 2: Child gets a SUBSET of parent's resources.
● Option 3: Parent and child share NO resources (completely independent).

6.2 Execution Options


● Option 1: Parent and child execute CONCURRENTLY (at the same time).
● Option 2: Parent WAITS until child terminates before continuing.

6.3 Address Space Options


● Child is a DUPLICATE of parent: Same code and data as parent. This is what
fork() does in UNIX.
● Child has NEW program loaded: exec() loads a completely new program into
child's memory space.

6.4 UNIX/Linux Process Creation — fork() and exec()


fork(): Creates a new process that is an EXACT COPY of the parent. Both parent and
child continue from the same point, but fork() returns different values:
● Returns 0 to the CHILD process.
● Returns the child's PID (a positive number) to the PARENT process.
● Returns a negative number if the fork FAILED.
📌 Simple Explanation of fork() code:
pid = fork();
if (pid < 0) → Fork failed! Print error.
if (pid == 0) → I am the CHILD → do child's work (like run ls command)
if (pid > 0) → I am the PARENT → wait for child to finish, then print 'Child Complete'
pid = fork();
if (pid < 0) { // Fork failed
fprintf(stderr, "Fork Failed");
}
else if (pid == 0) { // I am the CHILD
execlp("/bin/ls", "ls", NULL); // Run 'ls' command
}
else { // I am the PARENT
wait(NULL); // Wait for child
printf("Child Complete");
}

exec(): After fork(), the child can call exec() to REPLACE its memory with a completely
new program. The old code is gone; the new program runs in its place.
Example: Shell (bash) creating a new process:
1. Shell calls fork() → creates a copy of itself
2. Child calls exec('chrome') → Chrome's code replaces the shell copy in memory
3. Now Chrome is running as a new process!
4. Parent (shell) waits for Chrome to close, then shows prompt again.

7. Process Termination
A process ends in two main ways: voluntarily (it finishes) or involuntarily (it is killed).

7.1 Normal Termination (exit)


● Process executes its last statement and calls exit() to ask the OS to delete it.
● Child can send output data back to the parent using wait().
● OS deallocates (frees) all resources used by the process — memory, open files,
etc.

7.2 Forced Termination (abort)


A parent can terminate its child process. Reasons:
● Child has EXCEEDED its allocated resources (using too much memory/CPU).
● The TASK assigned to the child is no longer needed.
● The PARENT itself is exiting (in some OS, children must die too).

7.3 Cascading Termination


📌 What is Cascading Termination?
When a parent process is killed, ALL its children, grandchildren, etc. are ALSO
killed.
This 'cascade' continues down the whole family tree.

Example: If you close a web browser (parent),


all its child processes (tabs, plugins, etc.) are also terminated.

8. Interprocess Communication (IPC)


Processes can be INDEPENDENT (don't affect each other) or COOPERATING (they work
together and share data). Cooperating processes need IPC — a way to talk to each other.

8.1 Why Do Processes Cooperate? (Reasons for IPC)


● Information Sharing: Multiple processes might need the same data.
Example: Multiple browser tabs all need to access the same cookie file.
● Computation Speedup: A big task is broken into smaller parts that run in parallel
on multiple CPUs.
Example: Rendering a 3D movie — each frame can be processed by a different
process simultaneously.
● Modularity: System is divided into separate processes, each doing one job cleanly.
Example: A web server has separate processes for: receiving requests, processing,
logging, security check.
● Convenience: A user might run multiple tasks at the same time.
Example: You are editing a document AND listening to music AND downloading a file
— all at once.

8.2 Two Models of IPC


Model 1: Shared Memory
A region of memory is shared between cooperating processes. Processes read and write
to this shared area directly. It is FAST because processes access memory directly — no
OS involvement after setup.
📌 Analogy: Two people sharing a WHITEBOARD.
Person A writes something on the board.
Person B reads it.
They communicate through the shared whiteboard.
Both can access it directly — fast!
Model 2: Message Passing
Processes communicate by sending and receiving MESSAGES through the OS. No
shared memory needed. Good for small amounts of data and works across networks.
📌 Analogy: Sending LETTERS through a POST OFFICE.
Person A writes a letter and puts it in the mailbox.
Post office (OS) delivers it to Person B's mailbox.
Person B reads the letter.
Slower than whiteboard (because it goes through the post office).
But works even if they are far apart (different computers)!

9. Producer-Consumer Problem
This is a classic example of cooperating processes. A PRODUCER process creates data,
and a CONSUMER process uses that data. They communicate through a BUFFER
(shared storage area).
📌 Real Life Example:
PRODUCER = A chef cooking food (creating items)
BUFFER = The counter/pass-through window (limited space)
CONSUMER = A waiter picking up food (consuming items)

If the counter is FULL → Chef (producer) waits


If the counter is EMPTY → Waiter (consumer) waits

Computer Example:
PRODUCER = A program generating data (like a compiler generating output)
CONSUMER = A program printing or using that data (like a printer spooler)

9.1 Two Buffer Types


● Unbounded Buffer: No limit on buffer size. Producer never has to wait (in theory).
● Bounded Buffer: Fixed size buffer (e.g., BUFFER_SIZE = 10). Producer must wait
if buffer is full. Consumer must wait if buffer is empty.
9.2 Bounded Buffer — Shared Memory Solution
#define BUFFER_SIZE 10
item buffer[BUFFER_SIZE];
int in = 0; // next empty position (where producer puts item)
int out = 0; // next full position (where consumer takes item)

// Producer: keeps producing and putting items in buffer


while (true) {
while (((in + 1) % BUFFER_SIZE) == out); // wait if buffer full
buffer[in] = item;
in = (in + 1) % BUFFER_SIZE;
}

// Consumer: keeps taking items from buffer


while (true) {
while (in == out); // wait if buffer empty
item = buffer[out];
out = (out + 1) % BUFFER_SIZE;
}

⚠️Note: This solution only uses BUFFER_SIZE - 1 slots (not all 10) to tell apart full
from empty.

10. Message Passing — IPC


In message passing, processes communicate by sending and receiving messages. Two
basic operations: send(message) and receive(message).
For two processes P and Q to communicate:
● A communication LINK must be established between them.
● Messages are exchanged via send() and receive().

10.1 Direct Communication


Processes NAME each other EXPLICITLY when sending/receiving messages.
send(P, message) // send message directly TO process P
receive(Q, message) // receive message FROM process Q

Properties:
● Links are established AUTOMATICALLY (no setup needed).
● EXACTLY ONE link per pair of processes.
● Typically BIDIRECTIONAL (can send and receive both ways).
Example: Process A sends a file to Process B by naming it: send(B, fileData)
10.2 Indirect Communication (Mailboxes / Ports)
Messages go through a shared MAILBOX (also called a port). Processes don't name each
other — they just name the mailbox.
send(MailboxA, message) // send to Mailbox A
receive(MailboxA, message) // receive from Mailbox A

Properties:
● Link exists ONLY if processes share a common mailbox.
● One link can connect MANY processes (not just two).
● Can be unidirectional or bidirectional.
📌 Analogy: A shared EMAIL INBOX.
Multiple people can send to the same inbox.
Multiple people can read from the same inbox.

Problem: If P1 sends, and P2 and P3 both receive — WHO gets the message?
Solutions:
(a) Allow only 2 processes per link
(b) Allow only ONE receiver at a time
(c) OS randomly picks one receiver and tells the sender who got it

10.3 Synchronization — Blocking vs Non-Blocking


● Blocking Send (Synchronous): Sender is BLOCKED (waits) until the message is
received by the receiver.
● Blocking Receive (Synchronous): Receiver is BLOCKED until a message arrives.
Example: Like a phone call — both parties must be available at the same time
(synchronous).
● Non-Blocking Send (Asynchronous): Sender sends the message and
immediately CONTINUES with its work. Doesn't wait.
● Non-Blocking Receive (Asynchronous): Receiver checks for a message. If no
message, gets NULL and continues.
Example: Like sending an EMAIL — you send it and continue with your work. Receiver
reads when they want.

10.4 Buffering (Queue of Messages)


Messages are stored in a queue attached to the link. Three capacities:
● Zero Capacity (No buffering): Queue holds 0 messages. Sender MUST wait until
receiver is ready. Called RENDEZVOUS.
Like handing something directly to someone — you both must be there at the same
time.
● Bounded Capacity: Queue holds up to N messages. Sender waits only when
queue is FULL.
Like a mailbox with limited slots — if it's full, wait for someone to take messages out.
● Unbounded Capacity: Queue holds infinite messages. Sender NEVER waits.
Like unlimited cloud storage — you can always send more.

11. Real-World IPC Systems


11.1 POSIX Shared Memory
POSIX (Portable Operating System Interface) provides system calls for shared memory:
// Step 1: Create shared memory segment
id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR);

// Step 2: Attach to it (get a pointer to it)


shared_mem = (char *) shmat(id, NULL, 0);

// Step 3: Write to shared memory


sprintf(shared_mem, "Hello from Process A!");

// Step 4: Detach when done


shmdt(shared_mem);

11.2 Mach (Apple's OS)


Mach OS (used in macOS) uses message passing for EVERYTHING — even system calls
are messages.
● Every task (process) gets 2 mailboxes at creation: Kernel mailbox and Notify
mailbox.
● Only 3 system calls needed: msg_send(), msg_receive(), msg_rpc().

11.3 Windows XP — Local Procedure Calls (LPC)


Windows uses LPC (Local Procedure Call) for message passing between processes on
the SAME system. It uses PORTS (like mailboxes):
How LPC works in Windows:
1. Client opens a handle to the server's CONNECTION PORT
2. Client sends a CONNECTION REQUEST
3. Server creates TWO private ports — gives one to client
4. Client and server use their ports to send/receive messages
12. Communication in Client-Server Systems
12.1 Sockets
A socket is an ENDPOINT for communication — like a telephone socket. It is identified by
an IP address + Port number.
📌 Example:
Socket = IP Address + Port Number
[Link]:1625 means:
→ Machine with IP [Link]
→ Port number 1625

Communication happens between a PAIR of sockets:


Client socket (your PC) ←→ Server socket ([Link])

Common Port Numbers:


Port 80 = HTTP (websites)
Port 443 = HTTPS (secure websites)
Port 21 = FTP (file transfer)
Port 22 = SSH (remote login)

12.2 Remote Procedure Calls (RPC)


RPC allows a program to CALL A FUNCTION that runs on a DIFFERENT computer, as if it
were a local function call. It abstracts the networking details.
📌 Real Life Analogy:
Imagine calling a friend who is an expert lawyer.
You say: 'Hey, what is the penalty for speeding in Pakistan?'
Your friend (on another computer/city) looks it up and RETURNS the answer.
From your side, it felt like a normal function call — you didn't deal with
phones, networks, etc. The complexity was hidden!

That hiding is what RPC does — hides the network complexity.


How RPC Works:
● Stub (Client-side): A proxy function on the CLIENT's computer. When you call the
remote function, you actually call the stub. The stub packs (marshalls) the
parameters into a message.
● Marshalling: Converting function parameters into a format that can be sent over a
network.
● Server-side Stub: Receives the message, UNPACKS (unmarshalls) the
parameters, and calls the ACTUAL function on the server.
● Result is sent back to the client through the same process in reverse.
Example Flow:
Client calls: getStudentGrade(rollNo=101)
↓ Client Stub packs '101' into message
↓ Message sent over network to server
↓ Server Stub unpacks '101', calls actual getStudentGrade(101)
↓ Server finds: Grade = 'A'
↓ Result sent back to client
Client receives 'A' — as if they called a local function!

12.3 Pipes
A pipe acts like a TUNNEL or CONDUIT between two processes. Data goes in one end
and comes out the other end.
📌 Real Life Analogy:
Think of a WATER PIPE:
Water enters from one end (producer writes data)
Water comes out the other end (consumer reads data)

In Linux terminal, you use pipes all the time:


ls | grep .txt
→ 'ls' produces a list of files
→ The PIPE '|' sends that output to 'grep'
→ 'grep' reads the input and filters .txt files
Ordinary Pipes
● Unidirectional: Data flows ONE WAY only — one write-end, one read-end.
● Requires parent-child relationship: Only works between related processes.
● Producer writes to the write-end; Consumer reads from the read-end.
Example: Parent process writes data → Ordinary Pipe → Child process reads data
Named Pipes (FIFOs)
● More powerful than ordinary pipes.
● Bidirectional: Data can flow in BOTH directions.
● No parent-child requirement: ANY two processes can communicate using a
named pipe.
● Multiple processes can use the same named pipe.
● Available on both UNIX and Windows systems.
Example: A log-writing process and a log-reading process can communicate through
a named pipe called '/tmp/mylogpipe' — no family relationship needed!
13. Quick Revision — Key Terms at a Glance
● Process: A program currently running in memory (active entity).
● Program: Passive file on disk — not running yet.
● Text Section: The code/instructions of the process.
● Data Section: Global variables of the process.
● Heap: Dynamically allocated memory during runtime (malloc/new).
● Stack: Temporary memory — local variables, function calls, return addresses.
● Program Counter: Stores the address of the NEXT instruction to execute.
● PCB: Process Control Block — the 'ID file' of each process. Stores all info.
● Process State: Current condition: New, Ready, Running, Waiting, Terminated.
● Context Switch: Saving one process's state and loading another's. Pure overhead.
● Short-term Scheduler: Picks which READY process gets CPU next. Very fast,
called often.
● Long-term Scheduler: Decides which jobs enter memory. Controls
multiprogramming degree.
● Medium-term Scheduler: Swaps processes in/out of memory (memory
management).
● I/O-Bound Process: Mostly waits for I/O. Short CPU bursts. Example: text editor.
● CPU-Bound Process: Mostly computes. Long CPU bursts. Example: video
encoder.
● fork(): Creates a child process — exact copy of parent.
● exec(): Replaces process memory with a new program after fork().
● Cascading Termination: When parent dies, all children are also terminated.
● IPC: Inter-Process Communication — how processes share data/communicate.
● Shared Memory: Fast IPC — processes read/write from a shared memory region.
● Message Passing: IPC via OS messages (send/receive). Works across networks.
● Bounded Buffer: Fixed-size buffer used in Producer-Consumer problem.
● Direct Communication: Processes name each other explicitly in send/receive.
● Indirect Communication: Processes use mailboxes/ports (don't name each other).
● Blocking (Synchronous): Sender/receiver waits until the other side is ready.
● Non-Blocking (Async): Sender sends and continues. Receiver gets NULL if no
message.
● Socket: IP address + Port number = endpoint for network communication.
● RPC: Remote Procedure Call — call a function on another computer like a local
one.
● Marshalling: Packing function parameters into a network message (in RPC).
● Ordinary Pipe: Unidirectional pipe; needs parent-child relationship.
● Named Pipe: Bidirectional pipe; no relationship needed; multiple processes can
use it.

— End of Chapter 3: Processes Notes —

You might also like