0% found this document useful (0 votes)
35 views29 pages

AOS Module 1

The document provides an overview of process management and scheduling in the Linux kernel, detailing the kernel's functions, process types, states, and lifecycle. It explains key concepts such as process creation using system calls like fork(), vfork(), and clone(), as well as the structure of the task_struct that holds process information. Additionally, it covers process termination, including normal and abnormal termination, and the role of signals in managing process states.

Uploaded by

Anju Jaimon
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)
35 views29 pages

AOS Module 1

The document provides an overview of process management and scheduling in the Linux kernel, detailing the kernel's functions, process types, states, and lifecycle. It explains key concepts such as process creation using system calls like fork(), vfork(), and clone(), as well as the structure of the task_struct that holds process information. Additionally, it covers process termination, including normal and abnormal termination, and the role of signals in managing process states.

Uploaded by

Anju Jaimon
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

MODULE 1: PROCESS MANAGEMENT AND SCHEDULING

1.1 The Linux Kernel:

The Linux kernel is the core part of the Linux operating system, responsible for managing system
resources and enabling communication between hardware and software. It is open-source, highly
modular, and widely used in various devices, from servers and desktops to embedded systems and
mobile devices.

Functions of the Linux Kernel

1. Process Management: Handles the creation, execution, and termination of processes. It


manages resources like CPU time and ensures efficient scheduling of processes.

2. Memory Management: Allocates and manages memory for processes, ensuring efficient
utilization and preventing conflicts.

3. Device Drivers: Facilitates communication between the operating system and hardware
components.

4. File System Management: Manages data storage and retrieval on disk drives and other
storage devices.

5. Networking: Provides support for network protocols and data communication between
systems.

Introduction to Process in Linux :

A process is a running instance of a program. The Linux kernel handles processes by managing their
life cycles, allocating resources, and ensuring system stability. Each process has a unique identifier
called a PID (Process ID).

Key Concepts in Process Management

1. Types of Processes:

o Foreground Processes: Run interactively and require user input.

o Background Processes: Run without user interaction, often as daemons (e.g., system
services).

2. Process States:

o Running: The process is actively executing instructions.

o Waiting: The process is waiting for a resource or event.

o Stopped: The process is paused, often by user intervention.

o Zombie: The process has completed execution but still has an entry in the process
table.
3. Process Creation: Linux uses a system call called fork() to create a new process. The fork()
call creates a child process that is an exact copy of the parent process. The child process can
execute a different program using the exec() family of system calls.

4. Process Scheduling: The kernel uses scheduling algorithms (e.g., Completely Fair Scheduler)
to determine which process gets CPU time, ensuring fairness and efficiency.

5. Inter-Process Communication (IPC): Processes often need to communicate and share data.
Linux provides mechanisms like pipes, shared memory, message queues, and signals to
enable IPC.

6. Process Termination: A process can terminate normally (e.g., by completing its task) or
abnormally (e.g., due to an error or signal). The kernel reclaims resources allocated to the
terminated process.

Key Commands for Process Management

 ps: Displays information about running processes.

 top or htop: Shows real-time process activity and system resource usage.

 kill: Sends signals to terminate processes.

 nice/renice: Adjusts the priority of a process.

1.2 Process descriptor and the Task Structure:

In the Linux kernel, the process descriptor is a fundamental data structure that contains all the
information about a process. It is represented by the task_struct structure, which is defined in the
Linux kernel source code (typically in include/linux/sched.h).

The task_struct is the heart of Linux process management, storing everything the kernel needs to
know about a process.

Process Descriptor (task_struct)

The task_struct is a large and complex data structure because it encapsulates a wide range of
information about a process. Some of its key fields include:

1. Process Identification

 pid: The Process ID, a unique identifier for the process.

 tgid: Thread Group ID, shared among all threads in the same process.

 ppid: Parent Process ID.

2. State Information

 state: Represents the current state of the process, such as:

o TASK_RUNNING: The process is runnable or currently running.

o TASK_INTERRUPTIBLE: Waiting for an event and can be interrupted.


o TASK_UNINTERRUPTIBLE: Waiting for an event but cannot be interrupted.

o TASK_ZOMBIE: The process has terminated, but its descriptor has not been released.

o TASK_STOPPED: The process is stopped (e.g., via a signal).

3. Process Priority and Scheduling

 prio: The priority of the process.

 static_prio: The static (base) priority.

 rt_priority: Real-time priority, used for processes with real-time scheduling policies.

 policy: The scheduling policy (e.g., SCHED_NORMAL, SCHED_FIFO, SCHED_RR).

 se: The scheduling entity, used by the Completely Fair Scheduler (CFS).

4. Process Relationships

 parent: Pointer to the parent process.

 children: A linked list of child processes.

 sibling: Links to sibling processes.

 group_leader: Points to the leader of the process group.

5. Memory Management

 mm: Points to the memory descriptor (mm_struct), which contains details about the
process's address space.

 active_mm: Used when the process is executing kernel code but still references the user-
space memory layout.

6. File and I/O Information

 files: Points to the file descriptor table (files_struct).

 fs: Contains information about the file system context (e.g., current working directory).

 io_context: I/O scheduling context for the process.

7. Process Accounting

 start_time: The time when the process started.

 utime: User mode CPU time used by the process.

 stime: System mode CPU time used by the process.

8. Signals

 signal: Points to the signal handling structure (signal_struct), which manages signals sent to
the process.

 blocked: Indicates which signals are currently blocked by the process.


9. Thread Information

 thread: Stores hardware-specific information for the process, such as CPU registers, stack
pointers, and other thread-specific data.

10. Kernel Context

 flags: Flags that describe the state and behavior of the process.

 cpu: The CPU on which the process is running or last ran.

 stack: Pointer to the process's kernel-mode stack.

Structure of task_struct

Here is a simplified example of what the task_struct might look like (heavily summarized for
readability):

struct task_struct

pid_t pid; // Process ID

long state; // Current state of the process

struct mm_struct *mm; // Pointer to memory descriptor

struct files_struct *files; // Pointer to file descriptor table

struct signal_struct *signal; // Signal handling

struct list_head children; // List of child processes

struct task_struct *parent; // Pointer to parent process

struct sched_entity se; // Scheduling information

unsigned int prio; // Process priority

...

};

Why Is task_struct Important?

 Centralized Information: It centralizes all key information about a process.

 Kernel Efficiency: By storing all process-related details in a single structure, the kernel can
quickly access and manage processes.

 Scheduling and Resource Allocation: The kernel uses task_struct to decide CPU scheduling,
memory allocation, and more.
Process Creation in Linux:

In Linux, processes are created using system calls, primarily fork(), vfork(), and clone(). Each
process is represented by a task_struct, and new processes are created by duplicating this
structure.

1. fork() System Call

 Purpose: Creates a new process by duplicating the calling process.

 Behavior:

o The new process (child) is an exact copy of the parent process.

o The child gets a unique process ID (PID) but shares no memory or file descriptors
with the parent.

 Parent and Child Differentiation:

o fork() returns 0 to the child process.

o fork() returns the child's PID to the parent process.

2. vfork() System Call

 Purpose: Similar to fork(), but more efficient for processes that immediately call exec() to
replace their memory space.

 Behavior:

o The child shares the parent's memory space temporarily.

o The parent is suspended until the child calls exec() or _exit().

 Use Case: Optimized for creating processes that quickly execute a new program.

3. clone() System Call

 Purpose: A more flexible system call used to create processes or threads.

 Behavior:

o Allows fine-grained control over what resources (e.g., memory, file descriptors) are
shared between the parent and child.

o Used internally by libraries (like pthread) to implement threads.


Steps in Process Creation

1. Copying the Process Descriptor (task_struct):

o The kernel allocates a new task_struct for the child process.

o Depending on the system call (fork, vfork, clone), certain fields are copied or shared.

2. Copying Address Space:

o For fork(), the kernel creates a copy of the parent's memory using a technique called
Copy-On-Write (COW).

o For clone() with the CLONE_VM flag, the parent and child share the same memory
space.

3. Assigning Unique Identifiers:

o A new PID is assigned to the child process.

o If the clone() system call is used, thread IDs (TIDs) are assigned instead.

4. Adding to the Process Table:

o The new process is added to the kernel's process table.

o Scheduler-related data structures are updated.

5. Starting Execution:

o The child process begins execution from the instruction immediately following the
system call.

1.3 Linux Implementation of Threads:

In Linux, threads are treated as lightweight processes. They share certain resources with
other threads in the same process, such as memory and file descriptors. However, each
thread has its own task_struct, stack, and CPU registers.

Threads vs Processes

Aspect Thread Process

Shared among threads in a


Memory Separate memory space
process

File
Shared Not shared
Descriptors

Independent execution
Control Independent execution paths
paths

Lower (less resource Higher (requires duplicating


Creation Cost
duplication) memory)
Thread Implementation Using clone()

Threads in Linux are created using the clone() system call, which provides fine-grained
control over resource sharing. The clone() flags determine what is shared between the
parent and the child.

Common clone() Flags:

 CLONE_VM: Share memory space.

 CLONE_FS: Share file system information (e.g., current working directory).

 CLONE_FILES: Share file descriptors.

 CLONE_SIGHAND: Share signal handlers.

 CLONE_THREAD: Make the new thread part of the same thread group.

POSIX Threads (Pthreads)

The Linux kernel provides low-level threading support, and higher-level APIs like POSIX
threads (Pthreads) are built on top of it. Pthreads use clone() internally to create threads.

Example: Creating a Thread with Pthreads

#include <pthread.h>

#include <stdio.h>

#include <stdlib.h>

void *thread_function(void *arg)

{ printf("Thread is running. Argument: %d\n", *(int *)arg);

return NULL;

int main()

pthread_t thread;

int arg = 42;

// Create a new thread

if (pthread_create(&thread, NULL, thread_function, &arg) != 0)

perror("pthread_create failed");

exit(1);
}

// Wait for the thread to finish

pthread_join(thread, NULL);

printf("Thread has finished.\n");

return 0;

Threads and Scheduling

 Each thread in Linux has its own task_struct, which allows the kernel to schedule threads
independently.

 Threads in the same process share resources like memory, which makes inter-thread
communication efficient.

 The Linux scheduler treats threads and processes equally, using the same scheduling
policies.

1.4 Process Termination in Linux:

Process termination is the final step in a process's lifecycle. It occurs when a process finishes
executing its task or is explicitly killed. During termination, the operating system cleans up
resources and updates its internal state to reflect the process's exit.

How a Process Terminates

A process can terminate in the following ways:

1. Normal Termination

 Voluntary Termination: The process completes its execution and calls the exit() system call
(or returns from main() in user programs).

 Examples:

o Returning from the main function: return 0;

o Explicitly calling exit(): exit(0);

2. Abnormal Termination
 Crash or Error: The process encounters an error (e.g., segmentation fault) and is terminated
by the kernel.

 Signal Handling: The process receives a signal (e.g., SIGKILL, SIGTERM) that forces it to
terminate.

 Examples:

o Unhandled exception (e.g., division by zero).

o Explicit use of the kill command or kill() system call.

3. Parent-Driven Termination

 A parent process can explicitly terminate a child process using system calls like kill().

Steps in Process Termination

1. Calling the exit() System Call:

o The process invokes the exit() system call, which performs cleanup tasks.

o This call marks the process as terminated and sets the exit code.

2. Kernel Cleanup:

o The kernel performs the following:

 Closes all open file descriptors.

 Frees allocated memory (via mm_struct).

 Releases other resources like sockets or devices.

o Signals are sent to other processes waiting on this process (e.g., via wait()).

3. State Transition:

o The process enters the zombie state:

 The process's task_struct remains in the process table, but the process itself
is no longer running.

 This ensures the parent can retrieve the child's exit status using the wait() or
waitpid() system calls.

4. Removal of Zombie Process:

o When the parent calls wait() or waitpid(), the kernel removes the process from the
process table, freeing its task_struct.

o If the parent does not call wait(), the zombie process persists until the parent exits
or the system reaps it.

Key System Calls for Termination


1. exit()

 Terminates the calling process.

 Performs cleanup tasks and notifies the kernel of the process's exit status.

Example:

#include <stdlib.h>

int main()

exit(0); // Normal termination with status 0

2. _exit()

 Similar to exit(), but does not flush standard I/O buffers.

 Used in system-level programming where flushing is not required.

3. wait() and waitpid()

 Used by the parent process to retrieve the termination status of child processes and clean
up zombie processes.

Example:

#include <sys/types.h>

#include <sys/wait.h>

#include <unistd.h>

#include <stdio.h>

int main()

pid_t pid = fork();

if (pid == 0)

// Child process

printf("Child process terminating.\n");

_exit(0);

else
{

// Parent process

int status;

wait(&status); // Wait for the child to terminate

if (WIFEXITED(status))

printf("Child exited with status %d.\n", WEXITSTATUS(status));

return 0;

4. kill()

 Sends a signal to a process to terminate it.

Example:

#include <signal.h>

#include <unistd.h>

int main()

pid_t pid = fork();

if (pid == 0)

// Child process

while (1); // Keep running

else

// Parent process

sleep(1);

kill(pid, SIGKILL); // Terminate child process

return 0;
}

Process States During Termination

1. Running: The process executes the termination sequence.

2. Zombie: After termination, the process enters the zombie state, waiting for the parent to
acknowledge it.

3. Reaped: Once the parent retrieves the exit status, the process is removed from the process
table.

Signals and Termination

Signals are a common way to terminate processes. Common signals include:

 SIGTERM: Requests graceful termination.

 SIGKILL: Forces immediate termination (cannot be caught or ignored).

 SIGHUP: Sent when a terminal is closed, often leading to process termination.

Orphan and Zombie Processes

 Orphan Process: A process whose parent has terminated. The init process (PID 1) adopts and
reaps orphan processes.

 Zombie Process: A process that has terminated but still has an entry in the process table
because the parent has not retrieved its exit status.

Multitasking in Linux:

Multitasking is the ability of an operating system to execute multiple tasks (processes or threads)
simultaneously. Linux, like most modern operating systems, is a multitasking system that supports
preemptive multitasking, ensuring fair and efficient resource allocation among running processes.

Types of Multitasking

1. Cooperative Multitasking:

o Processes voluntarily yield control of the CPU.

o Less common in modern systems due to potential inefficiency (a single misbehaving


process can monopolize the CPU).

2. Preemptive Multitasking:
o The operating system decides when a process should stop executing and allocates
the CPU to another process.

o Linux uses preemptive multitasking, ensuring that all processes get a chance to
execute.

How Multitasking Works in Linux

1. Process Scheduling

 Linux uses a scheduler to manage multitasking.

 The scheduler decides which process gets the CPU based on priorities, policies, and states.

 Key scheduling policies in Linux:

o Completely Fair Scheduler (CFS): The default scheduler for general-purpose


workloads, focusing on fairness.

o Real-Time Scheduling: Used for processes requiring deterministic execution (e.g.,


SCHED_FIFO, SCHED_RR).

2. Context Switching

 The kernel performs context switching to switch the CPU from one process to another.

 During a context switch:

o The current process's state (registers, program counter, etc.) is saved in its
task_struct.

o The state of the next process is loaded into the CPU, allowing it to resume execution.

 Context switching is fast but has some overhead.

3. Process States

Multitasking depends on the process states:

 Running: The process is actively using the CPU.

 Waiting (Blocked): The process is waiting for an event (e.g., I/O operation).

 Ready: The process is ready to execute but is waiting for CPU time.

 Terminated: The process has completed execution.

4. Time Slicing

 The CPU time is divided into small intervals called time slices.

 Each process gets a time slice to execute.

 If a process does not complete within its time slice, it is preempted, and another process
gets the CPU.
Advantages of Multitasking

1. Increased CPU Utilization:

o The CPU remains busy by executing another process while one is waiting (e.g., for
I/O).

2. Improved Responsiveness:

o User applications (e.g., a web browser) remain responsive while background tasks
execute.

3. Better Resource Sharing:

o Multiple processes share system resources efficiently.

Multitasking in Linux: Processes vs Threads

Linux multitasking applies to both processes and threads:

 Processes:

o Have separate memory spaces.

o Context switching between processes involves more overhead.

 Threads:

o Share memory and resources within a process.

o Context switching between threads is faster than between processes.

Multitasking Example

Simulating Multitasking with Forked Processes

#include <stdio.h>

#include <unistd.h>

void task(const char *name, int duration)

for (int i = 1; i <= duration; i++)

printf("%s: %d seconds\n", name, i);

sleep(1); // Simulates work

int main()
{

pid_t pid = fork();

if (pid == 0)

// Child process

task("Child Task", 5);

else

// Parent process

task("Parent Task", 5);

return 0;

Output will alternate between parent and child tasks, demonstrating multitasking.

Real-Time Multitasking

Linux supports real-time multitasking for applications requiring deterministic behavior. Real-time
processes:

 Have higher priority than normal processes.

 Use policies like SCHED_FIFO and SCHED_RR.

Multitasking Challenges

1. Race Conditions: Multiple processes accessing shared resources simultaneously can lead to
data inconsistencies.

2. Deadlocks: Processes waiting indefinitely for resources held by each other.

3. Starvation: Low-priority processes may not get CPU time if high-priority processes dominate.

Linux addresses these challenges using:

 Synchronization primitives like mutexes, semaphores, and spinlocks.

 Fair scheduling policies.


1.5 Linux Process Scheduler and Scheduling Policy :

The Linux process scheduler is a critical component of the kernel responsible for deciding which
process gets to use the CPU at any given moment. It implements preemptive multitasking, allowing
multiple processes and threads to execute concurrently while ensuring fairness, responsiveness, and
efficient resource usage.

Key Features of the Linux Scheduler

1. Preemptive: Processes can be interrupted and replaced by higher-priority tasks.

2. Multilevel Queue Scheduling: Different types of tasks (interactive, batch, or real-time) are
handled with separate scheduling policies.

3. Scalability: Optimized for handling systems with a large number of CPUs and processes.

4. Fairness: Ensures that all tasks get an appropriate share of CPU time.

5. Real-Time Capabilities: Supports scheduling policies for deterministic behavior in time-


sensitive tasks.

Linux Scheduling Classes

The scheduler organizes tasks into scheduling classes, which determine their priority and behavior.
The two main classes are:

1. Normal (CFS - Completely Fair Scheduler)

 Purpose: Handles most user processes (non-real-time tasks).

 Algorithm: Implements a fairness model, ensuring that each process gets a proportional
share of CPU time.

 Mechanism:

o Maintains a red-black tree data structure to keep track of processes, sorted by their
virtual runtime (vruntime).

o The process with the smallest vruntime (least CPU used relative to its weight) runs
next.

 Weight:

o Processes with higher priorities (lower nice values) are assigned more CPU time.

2. Real-Time Scheduling

 Purpose: Used for time-critical tasks requiring deterministic behavior.

 Algorithm: Based on fixed-priority scheduling.

 Policies:
o SCHED_FIFO: First-In-First-Out scheduling. Processes run until they voluntarily yield
or are preempted by a higher-priority task.

o SCHED_RR: Round-Robin scheduling with time slices for each process of equal
priority.

o SCHED_DEADLINE: Ensures that a process meets its specified deadline, used for
high-precision tasks.

Linux Scheduling Policies

Linux supports multiple scheduling policies that determine how processes are prioritized:

Policy Description Use Case

Default policy for normal processes (managed by


SCHED_NORMAL General-purpose processes.
CFS).

Optimized for batch jobs that do not require Background tasks, batch
SCHED_BATCH
interactive responsiveness. processing.

Very low-priority scheduling for processes that Background or optional


SCHED_IDLE
should only run when the CPU is idle. tasks.

Real-time policy with fixed priority, processes run Time-sensitive, deterministic


SCHED_FIFO
until they yield or are preempted. tasks.

Real-time policy, like SCHED_FIFO but with time Real-time tasks with
SCHED_RR
slices for equal-priority tasks. predictable execution.

Real-time policy ensuring deadlines are met based High-precision real-time


SCHED_DEADLINE
on a specified time budget. tasks.

Normal Scheduling (CFS - Completely Fair Scheduler)

Key Concepts:

1. Virtual Runtime (vruntime):

o Each process is assigned a virtual runtime, which increases as the process runs.

o Processes with lower vruntime are scheduled first.

o Higher-priority tasks (lower nice values) accumulate vruntime more slowly, giving
them more CPU time.

2. Dynamic Prioritization:

o The CFS adjusts priorities dynamically based on process behavior, favoring


interactive tasks for better responsiveness.

Nice Values:
 Range: -20 (highest priority) to 19 (lowest priority).

 Affects how much CPU time a process gets relative to others.

Example: Adjusting Process Priority with nice

# Start a process with a lower priority

nice -n 10 ./my_program

# Change the priority of an existing process

renice -n -5 -p <PID>

Real-Time Scheduling

SCHED_FIFO:

 Behavior:

o Processes are scheduled in order of priority.

o A running process will continue until it yields, blocks, or is preempted by a higher-


priority task.

 Use Case: Critical tasks requiring uninterrupted CPU access.

SCHED_RR:

 Behavior:

o Similar to SCHED_FIFO, but processes at the same priority level are scheduled in a
round-robin manner.

o Each process gets a fixed time slice.

SCHED_DEADLINE:

 Behavior:

o Each process specifies a runtime, period, and deadline.

o The scheduler ensures that deadlines are met by allocating CPU time accordingly.

 Use Case: High-precision tasks like multimedia or robotics.

Example: Setting Real-Time Policies

#include <sched.h>
#include <stdio.h>

int main()

struct sched_param param;

param.sched_priority = 10;

// Set the scheduling policy to SCHED_FIFO

if (sched_setscheduler(0, SCHED_FIFO, &param) == -1)

perror("sched_setscheduler");

return 1;

printf("Running with SCHED_FIFO policy.\n");

while (1); // Simulate a real-time task

return 0;

Load Balancing in Multicore Systems

 The scheduler ensures that processes are evenly distributed across all available CPUs.

 Features:

o Migrates tasks from overloaded CPUs to underloaded ones.

o Keeps threads of the same process on the same CPU when possible for cache
optimization.

Factors Affecting Scheduling

1. Priority:

o Real-time tasks always have higher priority than normal tasks.

2. Interactivity:

o Interactive processes (e.g., user input tasks) are prioritized for responsiveness.

3. I/O Bound vs CPU Bound:

o I/O-bound tasks are given higher priority to reduce waiting times for I/O devices.

o CPU-bound tasks get lower priority but are scheduled fairly.


1.6 Linux Scheduling Algorithms:

The Linux kernel employs advanced scheduling algorithms to manage CPU time efficiently across
tasks. These algorithms are designed to balance fairness, responsiveness, throughput, and real-time
requirements.

Key Scheduling Algorithms in Linux

1. Completely Fair Scheduler (CFS)

 Introduced: Linux 2.6.23 (default for normal tasks).

 Purpose: General-purpose scheduling for user processes.

 Key Concept: Fairly distributes CPU time among processes proportional to their priority.

How CFS Works:

1. Virtual Runtime (vruntime):

o Tracks how much CPU time each process has received.

o Processes with smaller vruntime are prioritized for execution.

o vruntime grows slower for processes with higher priority (lower nice values), giving
them more CPU time.

2. Red-Black Tree:

o CFS maintains all runnable processes in a red-black tree (self-balancing binary tree).

o The leftmost node (process with the smallest vruntime) is chosen to run next.

3. Time Slices:

o Processes are assigned dynamic time slices based on their priority and the system
load.

o High-priority tasks receive longer time slices.

Advantages:

 Ensures fairness by equalizing CPU time across tasks.

 Prioritizes interactive tasks (e.g., user-facing applications) for responsiveness.

 Handles workloads efficiently on multicore systems.

2. Real-Time Scheduling Algorithms


Linux supports two real-time scheduling algorithms: SCHED_FIFO and SCHED_RR. Both are designed
for tasks requiring deterministic execution.

SCHED_FIFO (First-In-First-Out):

 Processes are scheduled based on fixed priorities.

 A process runs until it voluntarily yields, blocks, or is preempted by a higher-priority task.

 No time slicing for equal-priority tasks.

SCHED_RR (Round-Robin):

 Similar to SCHED_FIFO, but processes at the same priority level share the CPU in a round-
robin manner.

 Each process gets a fixed time slice before moving to the back of the queue.

SCHED_DEADLINE:

 Designed for hard real-time tasks that require meeting deadlines.

 Processes specify:

o Runtime: The maximum time the process needs to execute.

o Deadline: The time by which the process must finish.

o Period: The time interval between successive deadlines.

 The scheduler ensures that these constraints are met.

3. Batch Scheduling (SCHED_BATCH)

 Optimized for non-interactive, long-running background jobs.

 Designed to maximize CPU throughput without prioritizing responsiveness.

 Suitable for CPU-bound workloads (e.g., data processing).

4. Idle Scheduling (SCHED_IDLE)

 Used for processes that should only run when the CPU has no other tasks.

 Extremely low priority, suitable for optional or maintenance tasks.

Scheduling Algorithm Selection

The Linux kernel allows processes to select their scheduling policy using system calls like
sched_setscheduler() and sched_setparam().
Example: Setting Scheduling Policies

#include <sched.h>

#include <stdio.h>

int main()

struct sched_param param;

param.sched_priority = 10;

// Set the scheduling policy to SCHED_FIFO

if (sched_setscheduler(0, SCHED_FIFO, &param) == -1)

perror("sched_setscheduler");

return 1;

printf("Process running with SCHED_FIFO.\n");

while (1); // Simulate real-time task

return 0;

Key Metrics in Scheduling

1. Turnaround Time: Total time taken by a process from submission to completion.

2. Waiting Time: Time a process spends waiting in the ready queue.

3. Response Time: Time from process submission to its first execution.

Linux Scheduler Features

1. Multicore Load Balancing:

o Distributes tasks evenly across available CPUs.

o Tries to keep processes on the same CPU to optimize cache usage.

2. Interactive Task Prioritization:

o The scheduler identifies interactive tasks and boosts their priority to improve
responsiveness.
3. Dynamic Prioritization:

o Priority is adjusted dynamically based on process behavior (e.g., CPU-bound vs. I/O-
bound tasks).

Comparison of Algorithms

Algorithm Use Case Advantages Disadvantages

General-purpose Fair, scalable, prioritizes Not suitable for hard real-


CFS
workloads responsiveness time

No time-sharing among
SCHED_FIFO Hard real-time tasks Deterministic execution
equal tasks

Fair time-sharing among equal- Overhead from frequent


SCHED_RR Soft real-time tasks
priority tasks time slices

High-precision real- Requires precise


SCHED_DEADLINE Guarantees deadlines are met
time tasks configuration

Non-interactive Maximizes throughput for long-


SCHED_BATCH Low responsiveness
batch jobs running tasks

1.7 Pre-emption and Context Switching Work flow :

1. Interrupt Occurs (e.g., timer interrupt):

o The current process's execution is paused, and control is transferred to the kernel.

2. Scheduler Invoked:

o The scheduler checks if a higher-priority task or one that has waited too long is
ready to run.

3. Context Switching:

o If required, the kernel saves the current process's state and restores the new
process's state.

Pre-emption vs. Context Switching

Aspect Pre-emption Context Switching

Definition Interrupting a process to give Switching the CPU's execution


Aspect Pre-emption Context Switching

CPU time to another. context between processes.

Occurs due to scheduler or Involves saving/restoring process


Scope
interrupts. states.

Timer, higher-priority process, Scheduler decision during


Trigger
or I/O completion. preemption or blocking.

Improve responsiveness and Enable multitasking by switching


Purpose
fairness. between processes.

Occurs as needed (e.g., at Happens during every preemption


Frequency
every timer tick). or blocking event.

Example of Context Switching

Simulating Context Switching in a Multitasking Program

#include <stdio.h>

#include <unistd.h>

#include <pthread.h>

void* task1(void* arg)

for (int i = 0; i < 5; i++)

printf("Task 1 - Iteration %d\n", i + 1);

sleep(1); // Simulate some work

return NULL;

void* task2(void* arg)

for (int i = 0; i < 5; i++)

printf("Task 2 - Iteration %d\n", i + 1);

sleep(1); // Simulate some work

}
return NULL;

int main()

pthread_t thread1, thread2;

// Create two threads

pthread_create(&thread1, NULL, task1, NULL);

pthread_create(&thread2, NULL, task2, NULL);

// Wait for threads to finish

pthread_join(thread1, NULL);

pthread_join(thread2, NULL);

return 0;

 Output alternates between Task 1 and Task 2, simulating multitasking with context
switching.

Key Optimizations in Linux

1. Preemptive Kernel:

o Linux allows kernel tasks to be preempted, improving responsiveness.

o Introduced in Linux 2.6.

2. Lazy Context Switching:

o Avoids unnecessary state saving/restoring if the process will continue running on the
same CPU.

3. CPU Affinity:

o Keeps processes on the same CPU whenever possible to reduce cache misses during
context switches.

1.8 Real-Time Scheduling Policies in Linux:


Real-time scheduling policies in Linux are designed to handle tasks that require deterministic, time-
sensitive execution. These policies ensure that critical tasks meet their deadlines and execute with
minimal latency.

Overview of Real-Time Policies

Linux supports three real-time scheduling policies:

1. SCHED_FIFO (First-In-First-Out)

2. SCHED_RR (Round-Robin)

3. SCHED_DEADLINE

These policies prioritize real-time tasks over normal tasks, ensuring timely execution.

1. SCHED_FIFO (First-In-First-Out)

 Description:

o Tasks are scheduled in order of priority, and the highest-priority task runs until it:

 Voluntarily yields the CPU,

 Blocks, or

 Is preempted by a higher-priority task.

o No time slices are allocated for tasks of equal priority.

 Key Features:

o Deterministic execution.

o No automatic switching between tasks of the same priority.

 Use Case:

o Time-critical applications like robotics, audio processing, or control systems.

 Behavior:

o If two tasks have the same priority, the one that starts first will run to completion
(FIFO behavior).

2. SCHED_RR (Round-Robin)

 Description:

o Similar to SCHED_FIFO but introduces time slices for tasks with the same priority.

o After a task's time slice expires, it is moved to the end of the queue for its priority
level.
 Key Features:

o Fair sharing of CPU time among equal-priority tasks.

o Time slices ensure responsiveness for tasks with the same priority.

 Use Case:

o Real-time applications that need both fairness and predictability, like multimedia
streaming or gaming.

 Behavior:

o Tasks of equal priority are scheduled in a round-robin manner.

3. SCHED_DEADLINE

 Description:

o Ensures that tasks meet their deadlines by allocating CPU time based on specified
constraints.

o Tasks specify:

 Runtime (R): Maximum CPU time required per period.

 Deadline (D): Time by which the task must complete.

 Period (T): Time interval between task releases.

 Key Features:

o Based on Earliest Deadline First (EDF) and Constant Bandwidth Server (CBS)
algorithms.

o Guarantees deadlines if the system load is less than 100%.

 Use Case:

o High-precision, periodic tasks like industrial automation, robotics, or video encoding.

 Behavior:

o Tasks are scheduled in order of their earliest deadline.

o Ensures fair CPU bandwidth allocation.

Example: Task Parameters

 A task with R=10ms, D=50ms, and T=50ms:

o Can use up to 10ms of CPU time every 50ms.

o Must complete its work by the 50ms deadline.

Comparison of Real-Time Policies


Policy Preemption Time Slicing Use Case

Preempted by higher-priority Critical, deterministic


SCHED_FIFO No
tasks tasks.

Preempted by higher-priority Yes (among equal- Real-time fairness (e.g.,


SCHED_RR
tasks priority) games).

Preempted by tasks with earlier High-precision, periodic


SCHED_DEADLINE Not applicable
deadlines tasks.

Programming Real-Time Scheduling

Example: Setting Real-Time Scheduling in C

#include <sched.h>

#include <stdio.h>

#include <unistd.h>

int main()

struct sched_param param;

param.sched_priority = 10; // Priority (1-99 for real-time)

// Set scheduling policy to SCHED_FIFO

if (sched_setscheduler(0, SCHED_FIFO, &param) == -1)

perror("sched_setscheduler");

return 1;

printf("Running with SCHED_FIFO policy.\n");

// Simulate a task

while (1)

printf("Real-time task executing...\n");

sleep(1);

return 0;

}
Advantages of Real-Time Scheduling

1. Deterministic Execution:

o Real-time tasks are guaranteed to execute within their deadlines.

2. Prioritized Execution:

o High-priority tasks always preempt lower-priority tasks.

3. Support for Critical Applications:

o Enables Linux to handle industrial, multimedia, and scientific workloads effectively.

Considerations and Limitations

1. System Load:

o Real-time scheduling works best under controlled loads. Overloading the system can
result in missed deadlines.

2. Priority Inversion:

o A low-priority task holding a critical resource can block higher-priority tasks.

3. Configuration Complexity:

o Real-time scheduling requires careful tuning of task priorities and deadlines.

4. Limited CPU Bandwidth:

o SCHED_DEADLINE enforces a total CPU load of less than 100% to ensure deadlines
are met.

You might also like