Os Lab
Os Lab
Of
OS Lab
__________________________________________________________________________________________
_
Deenbandhu Chhotu Ram University of Science and Technology
Murthal, Sonipat- INDIA,
A Haryana State Government University
Index
Operating System
An operating system acts as an interface between the software and different
parts of the computer or the computer hardware. The operating system is
designed in such a way that it can manage the overall resources and
operations of the computer.
It comes up with a clean desktop environment that looks minimal and easy to use. It also
comes up with a pre-loaded application like Microsoft Excel, PowerPoint, Microsoft Edge
browser, Microsoft store, some basic games, and many other applications come. It allows
the user to do multitask, play games, watch videos, browse the internet, chats with
friends/family, and even you can install any software without any issue.
Control Panel: Windows provides a Control Panel feature that includes many tools to
configure and manage the resources on their computer. For example, users can change
settings for audio, video, printers, mouse, keyboard, network connections, date and time,
power saving options, user accounts, installed applications, etc.
File Explorer: It is also known as Windows Explorer, which displays your files and folders
on the computer. It allows users to browse the data on the hard drive, SSD and other
inserted removable disks like pen drives and CDs, and you can manage the content
according to the requirements such as delete, rename, search, and transfer the data.
Internet browser: As the internet browser is very important to search for anything, view
pages, online shopping, play games, watch videos, etc. Windows come with a pre-installed
internet browser. in Windows 10, the Edge internet browser is the default browser.
Furthermore, Internet Explorer was the default browser in Microsoft Windows from the
Windows edition 95 to 8.1 version.
Microsoft Paint: Since November 1985, Microsoft Windows comes with pre-installed
Microsoft Paint. It is a simple software to create, view, and edit an image. It offers several
tools to draw an image, crop, resize, and save an image with a different file extension.
Taskbar: Windows comes with a taskbar that displays currently opened programs, it also
allows users to access any specific programs. Additionally, it includes the notification area
on the right side that shows date and time, battery, network, volume, and other background
running applications.
Start menu: Microsoft Windows contains a start menu to the left side of the taskbar. It
displays programs and utilities that are installed on the computer. It can be simply opened
by clicking on the Start menu button or pressing the start key on the keyboard.
Task Manager: Windows includes the task manager feature that provides detail of the
running applications or programs on the computer. You can also check how much of the
system resources, such as RAM, CPU, disk I/O, are being used by each of the applications .
Recycle Bin: It is a place where all the deleted files and applications are stored. It provides
a facility of restore point where we can restore any deleted files or applications of our
system. If you delete any files or applications from the recycle bin then you will no longer
restore them, they will be permanently deleted.
The Linux Operating System is a type of operating system that is similar to Unix, and it is
built upon the Linux Kernel. The Linux Kernel is like the brain of the operating system
because it manages how the computer interacts with its hardware and resources. It makes
sure everything works smoothly and efficiently. But the Linux Kernel alone is not enough to
make a complete operating system. To create a full and functional system, the Linux Kernel
is combined with a collection of software packages and utilities, which are together called
Linux distributions. These distributions make the Linux Operating System ready for users
to run their applications and perform tasks on their computers securely and effectively.
Linux distributions come in different flavors, each tailored to suit the specific needs and
preferences of users.
Linux Distribution
Bootloader-A bootloader is responsible for managing the boot process of the computer
and for starting the Linux kernel. It can also be used to manage systems that boot more
than one OS.
Kernel – This is the one piece of the whole that is actually called ‘Linux’. The kernel is the
core of the system and manages the CPU, memory, and peripheral devices. The kernel is the
lowest level of the OS.
Init system.-The first process to run once the kernel is loaded. A process is an instance of a
program running on a computer, and the init system initializes the system to enable it to
run other processes. Init is a daemon program that acts as the parent process to all other
processes running on the system. Init can be configured to start specific processes at
system initialization. For example, when the system will be running a web server the init
system can be configured to load all necessary web server software.
Daemons.-This is a program that runs in the background, handling requests for a service. A
web server running on a Linux server depends on a daemon, usually named httpd, to listen
for web server requests.
Graphical server – This is the sub-system that displays the graphics on your monitor. It is
commonly referred to as the X server or just X.
Desktop environment – This is the piece that the users actually interact with. There are
many desktop environments to choose from (GNOME, Cinnamon, Mate, Pantheon,
Enlightenment, KDE, Xfce, etc.). Each desktop environment includes built-in applications
(such as file managers, configuration tools, web browsers, and games).
Applications – Desktop environments do not offer the full array of apps. Just like Windows
and macOS, Linux offers thousands upon thousands of high-quality software titles that can
be easily found and installed. Most modern Linux distributions (more on this below)
include App Store-like tools that centralize and simplify application installation. For
example, Ubuntu Linux has the Ubuntu Software Center (a rebrand of GNOME Software)
which allows you to quickly search among the thousands of apps and install them from one
centralized location.
macOS is built on a Unix-based architecture and provides users with a stable, reliable, and
user-friendly experience. The operating system is designed to be intuitive and easy to use,
focusing on simplicity and elegance. The user interface of macOS is clean, organized, and
aesthetically pleasing, making it a pleasure to use for both casual and professional users
alike.
In addition to its sleek design and user-friendly interface, macOS is also known for its
stability and security. With its robust security features, the operating system helps to
protect users' data and privacy, making it a popular choice for individuals and
organizations.
macOS is the operating system that powers the Apple Mac computer line. It offers users a
rich set of features and functionality that provides a seamless and intuitive computing
experience.
Desktop Interface
o Clean and uncluttered interface, with a focus on simplicity and ease of use
o The Dock, located at the bottom of the screen, provides quick access to frequently
used applications and documents.
o The Launchpad offers a grid-like interface for easily accessing and organizing all
installed applications.
o Built-in apps for tasks such as email, web browsing, and productivity
o Advance1d features like Continuity, which allows users to start a task on one Apple
device and continue on another
o The ability to use multiple virtual desktops to organize and separate workspaces
o Built-in security features, such as FileVault encryption, to protect users' data and
privacy
o Regular software updates to address security vulnerabilities and improve the
overall stability of the operating system.
Every software that runs on a computer, whether in the background or in the frontend, is a
process. In an operating system, process management os( Operating
System) refers to the set of activities involved in creating, scheduling, and
terminating processes . The operating system determines which processes have access to
the processor and how much processing time every process has in a multiprogramming
environment.
The operating system kernel manages the processes and resources of the system . For
processor management, the OS performs the following tasks:
Process Scheduling
Process scheduling is an essential part of a Multiprogramming operating systems. It refers
to the mechanism that the operating system uses to determine which process to
execute next. Multiprogramming operating systems allow more than one process to be
loaded into the executable memory at a time and the loaded process shares the CPU using
time multiplexing.
There are different scheduling algorithms that an operating system can use to
schedule processes. Here are some of the commonly used scheduling algorithms:
Proper utilization of CPU. Since the proper utilization of the CPU is necessary. Therefore,
the OS makes sure that the CPU should be as busy as possible.
Since every device should get a chance to use the processor. Hence, the OS makes sure
that the devices get fair processor time.
Increasing the efficiency of the system.
In Windows operating system, process management involves several key components and
mechanisms:
Process Creation: When a program is executed, Windows creates a process to manage its
execution. This involves allocating memory space, initializing data structures, and creating
a primary thread for execution.
Process Address Space: Each process in Windows has its own virtual address space,
which includes sections such as code, data, stack, and heap. Processes are isolated from
each other, preventing direct access to each other's memory.
Thread Management: Threads are the smallest units of execution within a process.
Windows allows processes to create multiple threads to perform concurrent tasks. The
operating system schedules threads for execution based on priority and other factors.
Process Monitoring and Management: Windows provides tools for monitoring and
managing processes. Task Manager is a built-in utility that allows users to view information
about running processes, CPU usage, memory usage, and other system resources.
Administrators can use Task Manager to terminate or prioritize processes as needed.
The operating system manages the Primary Memory or Main Memory. Main memory is
made up of a large array of bytes or words where each byte or word is assigned a certain
address. Main memory is fast storage and it can be accessed directly by the CPU.
For a program to be executed, it should be first loaded in the main memory. When the
program is completed, the memory region is released and can be used by other programs.
Therefore, there can be more than one program present at a time. Hence, it is required to
manage the memory.
It keeps track of primary memory, i.e., which bytes of memory are used by which
user program. The memory addresses that have already been allocated and the
memory addresses of the memory that has not yet been used.
In multiprogramming, the OS decides the order in which processes are granted
memory access, and for how long.
It Allocates the memory to a process when the process requests it and deallocates
the memory when the process has terminated or is performing an I/O operation.
The common memory management techniques used by OS are Partioning and Virtual
Memory.
a) Partitioning
The total memory is divided into various partitions of same sizeor different
sizes.
This helps to accommodate number of programs in the memory.
The partition can be fixed i.e. memory is allocated when a program is loaded
on to the memory.
The later approach causes less wastage of memory but in due course of time,
it may become fragmented.
b) Virtual Memory
A computer can address more memory than the amount physically installed on the
system. This extra memory is actually called virtual memory and it is a section of a hard
disk that's set up to emulate the computer's RAM.
The main visible advantage of this scheme is that programs can be larger than physical
memory. Virtual memory serves two purposes. First, it allows us to extend the use of
physical memory by using disk. Second, it allows us to have memory protection, because
each virtual address is translated to a physical address.
Memory management in the Windows operating system involves several core components
and techniques:
Virtual Memory: Windows uses virtual memory to abstract physical RAM and provide
each process with its own virtual address space. This allows processes to operate as if they
have access to a large, contiguous block of memory, even if physical RAM is limited.
Page File: Windows uses a page file (swap file) as a complement to physical memory.
When physical memory becomes scarce, the Memory Manager swaps out less frequently
used pages from RAM to the page file, freeing up space for other processes.
Page Replacement: In cases where physical memory is full, the Memory Manager uses
page replacement algorithms (e.g., Least Recently Used) to determine which pages to swap
out to the page file. This ensures that the most essential and frequently accessed pages
remain in RAM.
Working Sets: Windows manages the working sets of processes, which represent the set of
memory pages actively used by a process. The Memory Manager dynamically adjusts the
size of a process's working set based on its memory usage patterns and system resource
availability.
The operating system’s file system can manage single and group files in a
computer system. The operating system’s file management manages all of the files
on the computer system with different extensions(such as .exe, .pdf, .txt,
.docx, etc.).
So, file management is one of the basic but important features of the operating
system.
File Management in Windows Operating System
The Windows operating system manages files through its File System, which is
primarily the New Technology File System (NTFS) in modern versions like
Windows 10 and Windows 11. Here's how file management works in Windows:
File System: Windows uses the New Technology File System (NTFS) as its
primary file system. NTFS offers features such as file and folder permissions,
encryption, compression, disk quotas, and more. These features help manage files
securely and efficiently.
File Explorer: File Explorer is the graphical user interface through which users
interact with files and folders in Windows. It allows users to navigate through the
file system, create, copy, move, rename, and delete files and folders.
File Attributes: Each file in Windows has attributes such as read -only, hidden,
system, and archive. These attributes help in managing and organizing files based
on their properties.
Search: Windows provides a search feature that allows users to quickly find files
and folders based on their names, content, properties, and metadata.
Recycle Bin: When users delete files and folders in Windows, they are typically
moved to the Recycle Bin rather than being permanently deleted. This allows
users to restore deleted files if needed.
File Associations: Windows associates specific file types with corresp onding
applications. For example, double-clicking a .docx file may open it in Microsoft
Word by default.
Backup and Restore: Windows provides built-in tools for backing up and
restoring files and folders, allowing users to protect their data against accidental
loss or corruption.y
4. Device Management in Operating System
1. Keeps track of all devices and the program which is responsible to perform
this is called the I/O controller.
2. Monitoring the status of each device such as storage drivers, printers, and
other peripheral devices.
3. Enforcing preset policies and taking a decision on which process gets the
device when and for how long.
4. Allocates and deallocates the device in an efficient way.
Some important features of device management in operating systems are listed below:
The operating system’s device management system automatically detects new hardware
devices as they are connected to the system, and configures them to work with the
operating system.
Device drivers are software components that allow the operating system to communicate
with hardware devices.
The device management system is responsible for allocating system resources such as
memory, processor time, and input/output bandwidth to hardware devices and
applications that use them.
The device management system controls access to hardware devices to prevent conflicts
and ensure that only authorized applications and users can access the devices.
Device management in the Windows operating system involves several key components
and processes:
Device Drivers: Windows uses device drivers to facilitate communication between
hardware devices and the operating system. These drivers translate hardware-specific
commands into a language that the operating system can understand and vice versa.
Device Manager: Device Manager is a built-in Windows tool that allows users to view and
manage hardware devices installed on their computer. It provides information about
device status, drivers, and allows users to update, disable, or uninstall devices as needed.
Plug and Play (PnP): Windows supports Plug and Play technology, which enables the
automatic detection and configuration of hardware devices as they are connected or
disconnected from the computer. PnP allows for seamless integration of new devices
without requiring manual configuration.
Device Classes and Interface Classes: Windows categorizes devices into classes based on
their functionality and characteristics. Device classes provide a standardized way of
interacting with similar types of devices, while interface classes define common
programming interfaces for device drivers.
Power Management: Windows includes power management features that allow users to
optimize the power consumption of hardware devices, particularly in portable devices like
laptops and tablets. Power management settings can be adjusted to extend battery life and
reduce energy consumption.
Device Policies and Restrictions: Administrators can enforce device policies and
restrictions using Group Policy settings to control which devices users can connect to their
computers, restrict access to specific device types, or prevent unauthorized access to
sensitive hardware components.
Windows 2000
Windows 2000 was a direct successor to Windows NT 4.0 and was followed
by Windows XP. This version of Windows OS offered better and more stable
support for computer hardware than prior Microsoft OSes.
System Requirements
Windows 2000 is an operating system developed by Microsoft and released in
2000. Here is a brief overview of the system requirements for Windows 2000:
3. Life Cycle:
a. Mainstream support for Windows 2000 ended on June 30, 2005.
b. Extended support, including security updates and patches, continued until
July 13, 2010.
Windows 11
Windows 11 is the latest major release of Microsoft's Windows NT operating
system, released on October 5, 2021. It succeeded Windows 10 (2015) and is
available for free for any Windows 10 devices that meet the new Windows 11
system requirements.
Features of Windows 11 OS
Redesigned Start Menu: Windows 11 introduces a centered Start Menu,
which is more simplified and visually appealing compared to Windows 10.
System Requirements
Processor: 1 gigahertz (GHz) or faster with 2 or more cores on a compatible
64-bit processor or System on a Chip (SoC).
RAM: 4 gigabyte (GB).
System firmware: UEFI, Secure Boot capable. Check here for information on
how your PC might be able to meet this requirement.
TPM: Trusted Platform Module (TPM) version 2.0. Check here for instructions
on how your PC might be enabled to meet this requirement.
Graphics card: Compatible with DirectX 12 or later with WDDM 2.0 driver.
#include<stdio.h>
wt[0] = 0;
void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {
int main() {
findAverageTime(processes, n, burst_time);
return 0;
Output-
Experiment-4(d)
#include <stdio.h>
void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum) {
int rem_bt[n];
rem_bt[i] = bt[i];
int t = 0;
while (1) {
int done = 1;
if (rem_bt[i] > 0) {
t += quantum;
rem_bt[i] -= quantum;
}
else {
t = t + rem_bt[i];
wt[i] = t - bt[i];
rem_bt[i] = 0;
if (done == 1)
break;
void findTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) {
total_wt += wt[i];
total_tat += tat[i];
int main() {
int quantum = 2;
return 0;
}
Experiment-4(b)
#include <stdio.h>
#include <stdlib.h>
struct Process {
};
int total_waiting_time = 0;
total_waiting_time += processes[i].burst_time;
int main() {
// Example processes
{1, 6, 0},
{2, 8, 0},
{3, 7, 0},
{4, 3, 0}
};
int n = sizeof(processes) / sizeof(processes[0]);
sjfScheduling(processes, n);
return 0;
Output-
Experiment-4(e)
#include <stdio.h>
#include <stdlib.h>
struct Process {
};
total_waiting_time += processes[i].burst_time;
int main() {
// Example processes
{1, 6, 2, 0},
{2, 8, 1, 0},
{3, 7, 3, 0},
{4, 3, 4, 0}
};
priorityScheduling(processes, n);
return 0;
Output-
Experiment-4(c)
#include <stdio.h>
#include <stdlib.h>
struct Process {
int process_id;
int arrival_time;
int burst_time;
int remaining_time;
int completion_time;
};
*xp = *yp;
*yp = temp;
swap(&processes[j], &processes[j+1]);
int main() {
scanf("%d", &n);
printf("Enter arrival time and burst time for process %d: ", i+1);
processes[i].process_id = i + 1;
processes[i].remaining_time = processes[i].burst_time;
total_burst_time += processes[i].burst_time;
sort_by_arrival_time(processes, n);
printf("\nGantt Chart:\n");
printf("0 ");
min_remaining_time = processes[i].remaining_time;
min_index = i;
if (min_index == -1) {
printf("IDLE ");
time++;
} else {
processes[min_index].remaining_time--;
time++;
if (processes[min_index].remaining_time == 0) {
processes[min_index].completion_time = time;
total_turnaround_time += turnaround_time;
total_waiting_time += waiting_time;
printf("%d\t%d\t\t%d\t\t%d\t\t%d\t\t\t%d\n",
processes[i].process_id, processes[i].arrival_time, processes[i].burst_time,
processes[i].completion_time, turnaround_time, waiting_time);
}
printf("\nAverage Turnaround Time: %.2f\n", total_turnaround_time / n);
free(processes);
return 0;
Output-
Experiment-9
#include <stdio.h>
// Number of processes
#define P 5
// Number of resources
#define R 3
int need[P][R];
int work[R];
work[i] = avail[i];
int count = 0;
int found = 0;
if (!finish[p])
int j;
break;
if (j == R)
work[k] += allot[p][k];
finish[p] = 1;
found = 1;
count++;
if (!found)
break;
return count == P;
int main()
{3, 2, 2},
{9, 0, 2},
{2, 2, 2},
{4, 3, 3}};
{2, 0, 0},
{3, 0, 2},
{2, 1, 1},
{0, 0, 2}};
else
return 0;
Output-
Experiment-5
Basic commands in Linux are essential for navigating the file system, managing files and
directories, and performing various task. Here’s a list of fundamental linux commands.
Date- The date command in linux is used to display or set the system data and time. It can
be used to display the current date and time in various formats, as well as to set the system
date and time.
Cal- the ‘al’ command in linux is used to display a calendar for a specific month and year. By
default, it display the current month. You can specify a month and year as arguments to the
‘cal’ command to display the calendar for that specific month. For example, ‘cal 5 2024’ will
display the calendar for May 2024.
Echo- the echo command in linux is used to display text or variables on the terminal. It
simply outputs the text or variables passed to it as assignment.
Ls- the ‘ls’ command in linux is used to list files and directories in the current directory. It
displays the names of files and directories in the specified directory.
Lp- the lp command in linux is used to send files to a printer for printing. It allows you to
specify various printing options such as printer destination, number of copies, page ranges,
and print filters. It is part of the common linux printing system which is the printing system
used to most linux distributions.
Who- the who command in linux displays information about users who are currently
logged in, including their username, terminal, and login time. Ir can also show details about
system’s run-level.
Uptime- the uptime command in linux displays the current time, how long the system has
been running , the number of users currently logged in, and the system load averages for
the past 1, 5 and 15 minutes. It is a quick way to check the system’s uptime and load status.
Hostname- the hostname command in linux is used to view or set the hostname of the
system. When used without any argument it displays the current hostname of the system. If
you provide an argument, it sets the hostname to the specified value temporarily.
Bc- the ‘bc’ command in linux is a calculator that allows you to perform arithmetic
calculations at the command line. It stands for “basic calculator”. It can handle basic
mathematical functions, as well as more complex calculations using variables and
functions.
Output-
Cat- The ‘cat’ command in linux is short for “concatenate” and is used to display the
contents of one or more file to the standard output(usually the terminals). It can also be
used to concatenate files by combining them and sending the output to a new file or to the
standard output.
Grep- ‘grep’ is a command-line utility in Linux and Linux-like operating systems used for
searching plain text data sets for lines that matches a regular expression. It stands for
“Global Regular Expression Print”. It is commonly used to search files for pattern of text or
to filter the output of other commands.
Rm- The ‘rm’ command in Linux is used to remove directories. It stands for “remove”. Be
cautions when using it because it permanently deletes the separated files files or
directories and they cannot be easily recovered.
Touch- The ‘touch’ command in Linux is used to create new empty files or update the time
stamps of existing files. If the file doesn’t exist, touch creates an empty file with the
specified name. if the file already exist, ‘touch’ updates the access and modification time to
the current time, unless specified otherwise.
Cp- The ‘cp’ command in Linux is used to copy files and directories from one location to
another. It duplicates file and directories while preserving their permissions, timestamps
and ownerships.
mv- The ‘mv’ command in Linux is used to move files or directories from one location to
another. It can also be used to rename files or directories.
Cut- The ‘cut’ command in Linux is used to extract sections from each line of input data and
write the result to standard output. It’s particularly useful for working with files that have
fixed-width columns or delimiters such as CSU files with ‘cut’. You can specify which
sections of each line you want to extract based on byte positions, character positions, or
field positions.
Head, tail- the ‘head’ and ‘tail’ commands are used in Linux to display the beginning or end
of a text file, respectively.
Head- displays the first few lines of a file (by default the first 10 lines).
Tail- displays the last few lines of a file (by default, the last 10 lines).
Chmod- ‘chmod’ is a command in Linux and Unix like operating system that is used to
change the permissions of files or directories. It stands for ‘change mode’ with ‘chmod’. You
can modify the read, write and execute permissions for the owner of the file. It is commonly
used to control who can read, write or execute file or directory.
Output-
System calls –
Fork()- Fork refers to a system call used by processes to create a new process. When a
process causes “fork”, it is essential creates a copy of itself, resulting in two processes, the
parent process and the child process.
Exec()-It is used to execute a command replacing the current process. When you run a
command with ‘exec’, it replaces the current shell process with the specified command,
effectively ending the shell session after their command finishes execution.
Getpid- It is used to retrieve the process ID (PID) of the current process. Typically, it is
used with C programs to obtain the PID dynamically during runtime.
Exit- The exit command in Linux is used to close the current shell or terminal session.
When you type ‘exit’ and press enter, the shell session will terminate, and you will be
returned to the previous environment, such as the desktop or another shell if you are in a
nested shell session.
Wait- The wait command is used to wait for the complication of background process. It
pauses the execution of a shell script until all background jobs or specified job ID’s have
finished executing. This command is particularly useful in shell scripting to ensure
sequential execution of commands.
Close- The close command in Linux is typically used to close file descriptor. It is system call
used by programs to release resources associated with a file descriptor after it is no longer
needed. This helps in managing system resources efficiently.
Opendir- The ‘opendir’ command is not a stand alone command in Linux. Instead, it is a
function used in programming with C language to open a directory stream for reading. It is
part of the C standard library and is used to interact with directories within C programs.
Closedir-In Linux, the ‘closedir’ command is used to close a directory stream opened by the
‘opendir’ command. It releases any resources associated with the directory streams. This
command is typically stored you’ve finished reading from a directory using ‘readdir’ and
‘closedir’ ensure proper cleanup.
Output-
Experiment-6
#!/usr/bin/bash
if (($num %2 ==0))
fi
#!/usr/bin/bash
fi
c) Find factorial of a number.
#!/bin/bash
factorial=1
else
factorial=$((factorial * i))
done
Fi
#!/usr/bin/bash
echo "Before swap: first num= $num1 , second num= $num2 "
temp=$num1
num1=$num2
num2=$temp
echo "After swap: first num= $num1 , second num= $num2 "
if [ $num -gt 0 ];
fi
prime_numbers=""
do
is_prime=true
do
if [ $((i%j)) -eq 0 ]
then
is_prime=false
break
fi
done
if $is_prime
then
prime_numbers+=" $i"
fi
done
sum=0
temp=$((num))
temp=$((temp/10))
done
smallest=${array[0]}
largest=${array[0]}
for i in "${array[@]}"; do
smallest="$i"
fi
largest="$i"
fi
done
sum=0
cnt=0
sum=$((sum + num))
cnt=$((cnt + 1))
done
avg=$((sum / cnt))
#include <stdio.h>
#define MAX_PROCESSES 10
#define MAX_RESOURCES 10
int allocation[MAX_PROCESSES][MAX_RESOURCES];
int request[MAX_PROCESSES][MAX_RESOURCES];
int available[MAX_RESOURCES];
int finish[MAX_PROCESSES];
int work[MAX_RESOURCES];
void initialize() {
scanf("%d", &processes);
scanf("%d", &resources);
scanf("%d", &allocation[i][j]);
}
scanf("%d", &request[i][j]);
scanf("%d", &available[i]);
int detect_deadlock() {
finish[i] = 0;
work[i] = available[i];
int count = 0;
while (count < processes) {
int found = 0;
if (!finish[i]) {
int j;
break;
if (j == resources) {
work[k] += allocation[i][k];
finish[i] = 1;
found = 1;
count++;
if (!found) {
}
return 0; // No deadlock
int main() {
initialize();
if (detect_deadlock()) {
printf("Deadlock detected.\n");
} else {
return 0;
Output-
Experiment-7
Aim- WAP to implement producer consumer problem using
semaphores.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define BUFFER_SIZE 5
#define MAX_ITEMS 5
int buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int produced_count = 0;
int consumed_count = 0;
pthread_mutex_t mutex;
pthread_cond_t full;
pthread_cond_t empty;
int item = 1;
pthread_cond_wait(&empty, &mutex);
buffer[in] = item;
item++;
in = (in + 1) % BUFFER_SIZE;
produced_count++;
pthread_cond_signal(&full);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&full, &mutex);
}
int item = buffer[out];
consumed_count++;
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
int main() {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&full, NULL);
pthread_cond_init(&empty, NULL);
pthread_join(producerThread, NULL);
pthread_join(consumerThread, NULL);
pthread_mutex_destroy(&mutex);
thread_cond_destroy(&empty);
return 0;
Output-
Experiment-8
Aim- WAP to implement dining philosoper’s problem.
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
void eat(int);
printf("\nPhilosopher %d is eating",phil);
int main()
int i,a[5];
for(i=0;i<5;i++)
for(i=0;i<5;i++){
a[i]=i;
for(i=0;i<5;i++)
sem_wait(&chopstick[(phil+1)%5]);
eat(phil);
sleep(2);
sem_post(&chopstick[phil]);
sem_post(&room);
Output-
Experiment-11
Aim- WAP to create threads and synchronize them.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 2
int sharedData = 0;
pthread_mutex_t mutex;
long tid;
tid = (long)threadID;
// Acquire lock
pthread_mutex_lock(&mutex);
// Critical section
sharedData++;
// Release lock
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
// Initialize mutex
pthread_mutex_init(&mutex, NULL);
// Create threads
if (rc) {
exit(-1);
// Join threads
pthread_join(threads[t], NULL);
// Destroy mutex
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
Output-
Experiment-12
Aim- WAP to implement memory allocation method for fixed
partitions using first/worst/best fit.
#include <stdio.h>
#include <stdlib.h>
#define NUM_PARTITIONS 5
int id;
int size;
int isOccupied;
} Partition;
Partition memoryPartitions[NUM_PARTITIONS];
int memory[MEMORY_SIZE];
void initializeMemoryPartitions() {
int i;
memoryPartitions[i].id = i;
memoryPartitions[i].isOccupied = 0;
}
void displayMemoryLayout() {
int i;
printf("Memory Layout:\n");
printf("\n");
int i;
memoryPartitions[i].isOccupied = 1;
return i;
return -1;
bestFitPartition = i;
minSize = memoryPartitions[i].size;
if (bestFitPartition != -1) {
memoryPartitions[bestFitPartition].isOccupied = 1;
return bestFitPartition;
worstFitPartition = i;
maxSize = memoryPartitions[i].size;
if (worstFitPartition != -1) {
memoryPartitions[worstFitPartition].isOccupied = 1;
}
return worstFitPartition;
memoryPartitions[partitionId].isOccupied = 0;
int main() {
initializeMemoryPartitions();
do {
printf("6. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
scanf("%d", &processSize);
partitionId = firstFit(processSize);
if (partitionId != -1) {
} else {
break;
case 2:
scanf("%d", &processSize);
partitionId = bestFit(processSize);
if (partitionId != -1) {
} else {
break;
case 3:
scanf("%d", &processSize);
partitionId = worstFit(processSize);
if (partitionId != -1) {
printf("Memory allocated successfully in partition %d\n", partitionId);
} else {
break;
case 4:
scanf("%d", &partitionId);
releasePartition(partitionId);
break;
case 5:
displayMemoryLayout();
break;
case 6:
printf("Exiting...\n");
break;
default:
printf("Invalid choice!\n");
return 0;
}
Output-
Experiment-13
Aim- WAP to implement page replacement algorithms
a) FIFO b) LRU c) LFU d) Optimal
#include <stdio.h>
#include <stdlib.h>
#define NUM_FRAMES 3
#define NUM_PAGES 15
int frames[NUM_FRAMES];
int frameIndex = 0;
int pageFaults = 0;
int i, j;
int found = 0;
if (frames[j] == page) {
found = 1;
break;
if (!found) {
frames[frameIndex] = page;
pageFaults++;
printf("\n");
int frames[NUM_FRAMES];
int frameIndex = 0;
int pageFaults = 0;
int i, j;
}
int *recentlyUsed = (int *)malloc(NUM_FRAMES * sizeof(int));
int found = 0;
if (frames[j] == page) {
found = 1;
break;
if (!found) {
int leastUsedIndex = 0;
leastUsedIndex = j;
frames[leastUsedIndex] = page;
pageFaults++;
}
printf("\n");
free(recentlyUsed);
int main() {
fifo(pages, NUM_PAGES);
printf("\nLRU page replacement algorithm:\n");
lru(pages, NUM_PAGES);
lfu(pages, NUM_PAGES);
optimal(pages, NUM_PAGES);
return 0;
Output-
Experiment-14
Aim- WAP to implement file allocation strategies for student details
(Roll No, Name, Branch)
a) Sequential b) Indexed c) Linked
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_LENGTH 50
#define MAX_BRANCH_LENGTH 20
typedef struct {
int rollNo;
char name[MAX_NAME_LENGTH];
char branch[MAX_BRANCH_LENGTH];
} Student;
if (file == NULL) {
fclose(file);
return;
int offset = 0;
fclose(file);
fclose(indexFile);
if (file == NULL) {
return;
fclose(file);
int main() {
Student students[MAX_STUDENTS];
int numStudents;
scanf("%d", &numStudents);
return 1;
scanf("%d", &students[i].rollNo);
printf("Name: ");
scanf("%s", students[i].name);
printf("Branch: ");
scanf("%s", students[i].branch);
sequentialFile(students, numStudents);
indexedFile(students, numStudents);
linkedFile(students, numStudents);
return 0;
Output-
Experiment-15
Aim- WAP to implement Disk scheduling algorithms
a) FCFS b) SCAN c) C-SCAN
#include <stdio.h>
#include <stdlib.h>
int i, j, temp;
temp = requests[j];
requests[j + 1] = temp;
int totalMovement = 0;
printf("FCFS Disk Scheduling Algorithm:\n");
start = requests[i];
int totalMovement = 0;
int i, j;
sortRequests(requests, numRequests);
if (requests[j] == i) {
direction = -1;
i = 0;
int totalMovement = 0;
int i, j;
sortRequests(requests, numRequests);
if (requests[j] == i) {
current = requests[j];
}
if (requests[j] == i) {
current = requests[j];
int main() {
int requests[MAX_REQUESTS];
scanf("%d", &numRequests);
return 1;
}
printf("Enter the starting position of the head: ");
scanf("%d", &start);
scanf("%d", &requests[i]);
return 0;
Output-