0% found this document useful (0 votes)
2 views

OS Lab Manual

The lab manual for CSE 2306 at the University of Liberal Arts focuses on essential skills in shell commands and scripting within an operating system environment, emphasizing practical exercises. It outlines course objectives, outcomes, and instructions for lab conduct, alongside detailed tasks on UNIX commands and system calls. By the end of the course, students are expected to proficiently apply operating system concepts to solve real-world problems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

OS Lab Manual

The lab manual for CSE 2306 at the University of Liberal Arts focuses on essential skills in shell commands and scripting within an operating system environment, emphasizing practical exercises. It outlines course objectives, outcomes, and instructions for lab conduct, alongside detailed tasks on UNIX commands and system calls. By the end of the course, students are expected to proficiently apply operating system concepts to solve real-world problems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Lab Manual

Course Code:CSE 2306


Course Title: Operating System Lab

Department of Computer Science & Engineering

University of Liberal Arts

Semester: Spring 2024

1
Preamble

This manual is designed to equip you with essential skills in using shell commands and scripting
within an operating system environment. Through practical exercises in this manual, you'll learn
how to navigate, automate tasks, and create scripts efficiently. Operating system concepts are
vital for solving real-world challenges. This lab manual will guide you in understanding and
applying principles like process management, memory allocation, and file systems.

By course end, you'll be proficient in shell commands, scripting, and applying operating systems
concepts to tackle real-world issues effectively. Let's dive into this journey together, enhancing
your skills for a successful computing career!

2
Course Objectives:
The course aims to provide exposure to problem-solving through programming. It aims to train
the student to the basic concepts of the C-programming language. This course involves a lab
component which is designed to give the student hands-on experience with the concepts that
develop problem solving and coding skills.

Course Outcome:
Delivery
Domain/level
CO methods
CO Statement of learning Assessment tools
No. and
taxonomy
activities
Lecture,
Demonstrate basic shell Psychomotor/ Class Quiz/Mid-term
1
commands and scripts L2, Affective / Participation exam/Assignments
L2
Lecture, Project, Mid-term
Apply operating systems Psychomotor/ Discussion, exam, Final exam.
2 concepts for solving L3, Affective / Group Work
real-world problems L3

Text and Reference Materials


Text Book(s):

Online Resources:

Lab Instructions
● All students must arrive on time for the class.
● Just after entering and before class started, all students were required to submit their lab
reports (if any).
● All computers must be handled with care.
● Use only the software needed for the course.
● No haste should be done during the class period.
● After a class period, all computers must be shut down.
● Perfect discipline should be maintained and useless talking should be avoided while
performing LAB.
● Food and Drinks are not allowed in the LAB.
● LAB will be used for academic purposes only.

3
OS Lab Manual Contents

Course Objectives 3
Course Outcome 3
Text and Reference Material 3
Lab Instruction 3
Lab Task 1 5
Lab Task 2 10
Lab Task 3 15
Lab Task4 18
Lab Task 5 21
Lab Task 6 23
Lab Task 7 26
Lab Task 8 31
Lab Task 9 34
Lab Task 10 37
Lab Task 11 42

4
Lab Task 01: Introduction to Unix
Part A
A. Overview:
This is the introductory class. An overview of the UNIX operating system, Linux, and required tools are
discussed. Here, expectations from the students, course outcomes, overall lab assessment criteria, etc. are
also covered. Students are informed about the project that they must turn in at the end of the semester as
well.

B. Learning Outcome:
After this lecture, the students will be able to:
a. Learn about the Unix operating system, Linux
b. Install UbuntuWeek 6

C. Possible Challenges and Their Solutions


Problem: Students might face problems installing Ubuntu on their computers.
Solutions: The faculty will ensure that the students have properly installed the required version of Ubuntu.

D. Acceptance and Evaluation


This is a preliminary setup. Students won’t be evaluated for this task.

E. Background:

UNIX:
It is a multi-user operating system. It is a stable, multi-user, multi-tasking system for servers, desktops,
and laptops. Ken Thomson and Dennis Ritchie developed it from MULTICS (Multiplexed Information
and Computing Service) OS at AT & T Bell Industries, USA in 1969. It was created in an effort to
provide a multiuser, multitasking system for use by programmers By1980, UNIX had been completely
rewritten using C language.
The UNIX operating system is made up of three parts:
● Kernel
● Shell and
● Programs.

LINUX:
Linux is one of the most popular versions of the UNIX operating System. It was created by Linus
Torvalds. All UNIX commands work in Linux. Linux is an open-source software. The main feature of
Linux is coexisting with other OS such as Windows and UNIX.

STRUCTURE OF A LINUX SYSTEM:


It consists of three parts.
a) UNIX kernel
b) Shells
c) Tools and Applications

UNIX KERNEL:
The Linux kernel is its central component. It oversees all of this operating system's important functions. It
comprises different modules and directly communicates with the underlying hardware. The kernel offers
the necessary abstraction to shield the low-level hardware specifications from the user.

5
SHELL:
Shell is the command interpreter in the UNIX OS. It accepts commands from the user and analyses and
interprets them. Most accounts on our clusters have the bash shell by default.

TOOLS AND APPLICATIONS:


They are responsible to do specialized, individual-level tasks.

Activity List for Part A


1. Read the installation guide of Ubuntu. Follow the steps carefully to ensure the flawless
installation of this operating system.

Part B

A. Objective
An overview of the basic UNIX commands.

B. Learning Outcome:
After this lecture, the students will be able to:
a. Learn about Unix shell commands

C. Possible Challenges and Their Solutions


Problems: Students might face problems with writing the proper syntax.
Solutions: The faculty will ensure that the students write the syntax properly.

D. Acceptance and Evaluation


This is a preliminary setup. Students won’t be evaluated for this task.

E. Activity List
Basic UNIX commands are shown below. Students need to write commands and check the output.

a) date: used to check the date and time


Syntax: $date
Format Purpose Example Result

+%m To display only month $date+%m 06

+%h To display month name $date+%h June

+%d To display day of month $date+%d O1

+%y To display last two digits of years $date+%y 09

+%H To display hours $date+%H 10

+%M To display minutes $date+%M 45

+%S To display seconds $date+%S 55

6
b) cal: used to display the calendar
Syntax: $cal 2 2009

c)echo: used to print the message on the screen.


Syntax: $echo “text”

d)ls: used to list the files. Your files are kept in a directory.
Syntax: $lsls–s
All files (include files with prefix)
ls–l Lodetai (provide file statistics)
ls–t Order by creation time
ls– u Sort by access time (or show when last accessed together with –l)
ls–s Order by size
ls–r Reverse order
ls–f Mark directories with /, executable with* , symbolic links with @, local sockets with =,
named pipes(FIFOs)with
ls–s Show file size
ls– h“ Human Readable”, show file size in Kilo Bytes & Mega Bytes (h can be used
together with –l or)
ls[a-m]*List all the files whose name begin with alphabets From „a‟ to „m‟
ls[a]*List all the files whose name begins with „a‟ or „A‟
Eg:$ls>my list Output of „ls‟ command is stored to a disk file named „my list‟

e)lp: used to take printouts


Syntax:$lp filename

f)man: used to provide manual help on every UNIX command.


Syntax :$man unix command
$man cat

g)who & whoami: it displays data about all users who have logged into the system currently. The next
command displays the current user only.
Syntax: $who $whoami

h)uptime: tells you how long the computer has been running since its last reboot or power-off.
Syntax: $uptime

i)uname: it displays the system information such as hardware platform, system name, and processor, OS
type.
Syntax:$uname–a

j)hostname: displays and sets system hostname

Syntax :$ hostname

7
FILE MANIPULATION COMMANDS

a)cat–this creates, views, and concatenates files.


Creation:
Syntax:$cat>filename
Viewing:
Syntax:$cat filename
Add text to an existing file:
Syntax:$cat>>filename
Concatenate:
Syntax:$catfile1file2>file3
$catfile1file2>>file3 (no overwriting of file3)

b)grep–used to search a particular word or pattern related to that word from the file.
Syntax:$grep search word filename
Eg:$grep anu student

c)rm–deletes a file from the file system


Syntax:$rm filename

d)touch–used to create a blank file.


Syntax:$touch file names

e)cp–copies the files or directories


Syntax:$cpsource file destination file
Eg:$cp student stud

f)mv–to rename the file or directory


Syntax:$mv old file new file
Eg:$mv–i student student_list(-i prompt when overwrite)

g)cut–it cuts or pickup a given number of character or fields of the file.


Syntax:$cut<option><filename>
Eg: $cut –c filename
$cut–c1-10emp
$cut–f 3,6emp
$ cut –f 3-6 emp
-c cutting columns
-f cutting fields

h)head–displays10 lines from the head(top)of a given file


Syntax:$head filename
Eg:$head student
To display the top two lines:
Syntax:$head-2student

i)tail–displays last 10 lines of the file

8
Syntax:$tail filename
Eg:$tail student
To display the bottom two lines;
Syntax:$ tail -2 student

j)chmod–used to change the permissions of a file or directory.


Syntax:$ch mod category operation permission file
Where Category–is the user type
Operation–is used to assign or remove permission
Permission–is the type of permission
File–are used to assign or remove permission all

Examples:
$chmodu-wx student
Removes write and execute permission for users
$ch modu+rw,g+rwstudent
Assigns read and write permission for users and groups
$chmodg=rwx student
Assigns absolute permission for groups of all read, write and execute permissions

k)wc–it counts the number of lines, words, characters in a specified file(s) with the options as –l,-w,-c
Category Operation Permission

u– users +assign r– read


g–group -remove w– write
o– others =assign absolutely x-execute
Syntax: $wc –l filename
$wc –w filename
$wc–c filename

Post Lab Exercise:


1. Self-study the basic of Ubuntu OS
2. Preparing the Ubuntu operating system.

9
Lab Task 02: Introduction to System Call
Part A
A. Overview:
● To understand about Linux system calls and their use in processes.
● To write C Programs using the following system calls of the UNIX operating system: fork, exec,
getpid, exit, wait, close, stat, opendir, readdir.
B. Learning Outcome:
After this lecture, the students will be able to learn about the Unix System Calls: fork, exec, getpid, exit, wait, close,
stat, opendir, readdir

C. Possible Challenges and Their Solutions


Students might face problems in understanding how a system call works. The teacher will give a brief
introduction of system call.
D. Acceptance and Evaluation
Students are expected to complete all tasks during the class. This lab will be graded. No home assignment is allowed for
the lab.

BACKGROUND:
What are system calls?
System calls provide the means for a user program to ask the operating system to perform tasks reserved for
the operating system on the user program’s behalf. A system call is invoked in a variety of ways, depending
on the functionality provided by the underlying processor. In all forms, it is the method used by a process to
request action by the operating system.

Some Examples of Windows and UNIX system calls:

Windows UNIX

Process Control CreateProcess() fork()


ExitProcess() exit()
WaitForSingleObject() wait()

File Manipulation CreateFile() open()


ReadFile() read()
WriteFile() write()
CloseHendle() close()

Device Manipulation SetConsoleMode() ioctl()


ReadConsole() read()
WriteConsole() write()

10
Process Control System Calls of UNIX System:

I. fork() ● Has a return value


● Parent process => invokes fork() system call
● Continue execution from the next line after fork()
● Has its own copy of any data
● Return value is > 0 //it’s the process id of the child process. This value is
different from the Parents own process id.
● Child process => process created by fork() system call
● Duplicate/Copy of the parent process //LINUX
● Separate address space
● Same code segments as parent process
● Execute independently of parent process
● Continue execution from the next line right after fork()
● Has its own copy of any data
● Return value is 0

II. wait () ● Used by the parent process


● Parent’s execution is suspended
● Child remains its execution
● On termination of child, returns an exit status to the OS
● Exit status is then returned to the waiting parent process //retrieved by wait
()
● Parent process resumes execution
● #include <sys/wait.h>
● #include <sys/types.h>

III. exit() ● Process terminates its execution by calling the exit() system call
● It returns exit status, which is retrieved by the parent process using wait()
command
● EXIT_SUCCESS // integer value = 0
● EXIT_FAILURE // integer value = 1
● OS reclaims resources allocated by the terminated process (dead process)
Typically
● performs clean-up operations within the process space before returning
control back
● to the OS
● Terminates the current process without any extra program clean-up
● Usually used by the child process to prevent from erroneous release of
resources
● belonging to the parent process

IV. sleep() ● Takes a time value as a parameter (in seconds on Unix-like OS and in
milliseconds on Windows OS)
sleep(2) // sleep for 2 seconds in Unix
Sleep(2*1000) // sleep for 2 seconds in Window

V. getpid() ● returns the PID of the current process

11
VI. getppid() ● returns the PID of the parent of the current process

Activity List:
➔ All programs are shown in the Green boxes.
➔ All the programs should be written in C language.
➔ In the blue box write the appropriate output for each program.

12
Process Tree:

In Lab Exercise:
1. Create a program that creates a child process. The child process prints “I am a child
process” 100 times in a loop. Whereas the parent process prints “I am a parent process”
100 times in a loop.

13
2. Create a program named stat that takes an integer array as an input(delimited by some
character such as $). The program then creates 3 child processes each of which does
exactly one task from the following.
a) Adds them and print the result on the screen. (done by child 1)
b) Shows the average on the screen. (done by child 2)
c) Print the maximum number on the screen. (done by child 3)

14
Lab Task 03: CPU scheduling Algorithm
A. Overview:
Write a C program to simulate the following non-preemptive CPU scheduling algorithms to find the
turnaround time and waiting time for the above problem.
a) FCFS
b) SJF
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of CPU scheduling. Also,
they will be able to learn about different algorithms.

C. Possible Challenges and Their Solutions


Students might face problems in the implementation of different CPU scheduling algorithms if they have
lacking in an understanding of programming concepts.

D. Acceptance and Evaluation


The teacher will discuss all the steps for each algorithm. Students are expected to implement each of the
algorithms in any programming language during the class. This lab will be graded. No home assignment is
allowed for the lab.

Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.

First Come First Serve Algorithm:

AIM: To write a c program to simulate the CPU scheduling algorithm First Come First Serve
(FCFS).

DESCRIPTION:

To calculate the average waiting time using the FCFS algorithm first the waiting time of the first process is
kept at zero and the waiting time of the second process is the burst time of the first process and the waiting
time of the third process is the sum of the burst times of the first and the second process and so on. After
calculating all the waiting times the average waiting time is calculated as the average of all the waiting
times. FCFS mainly says first come first serve the algorithm which came first will be served first.

ALGORITHM:

Step 1: Start the process


Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process name and the burst time Step 4: Set the waiting of the first
process as ‘0’and its burst time as its turnaround time

15
Step 5: for each process in the Ready Q calculate
a).Waiting time (n) = waiting time (n-1) + Burst time (n-1)
b). Turnaround time (n)= waiting time(n)+Burst time(n)
Step 6: Calculate
a) Average waiting time = Total waiting Time / Number of processes
b) Average Turnaround time = Total Turnaround Time / Number of processes
Step 7: Stop the process

16
Shortest Job First (SJF):

AIM: To write a program to stimulate the CPU scheduling algorithm Shortest job first (Non-Preemption)

DESCRIPTION:

To calculate the average waiting time in the shortest job first algorithm the sorting of the process based on
their burst time in ascending order then calculate the waiting time of each process as the sum of the bursting
times of all the processes previous or before that process.

ALGORITHM:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Queue, assign the process id and accept the CPU burst time
Step 4: Start the Ready Queue according to the shortest Burst time by sorting according to lowest to highest burst time.
Step 5: Set the waiting time of the first process as ‘0’ and its turnaround time as its burst time.
Step 6: Sort the processes names based on their Burt time
Step 7: For each process in the ready queue, calculate
a) Waiting time (n) = waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n) = waiting time(n)+Burst time(n)
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of processes
b) Average Turnaround time = Total Turnaround Time /number of processes
Step 9: Stop the process

17
Lab Task 04: CPU scheduling Algorithm
A. Overview:
Write a C program to simulate the following CPU scheduling algorithms to find the turnaround time and
waiting time for the above problem.
a) Round Robin
b) Priority Scheduling
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of CPU scheduling. Also,
they will be able to learn about different algorithms.

C. Possible Challenges and Their Solutions


Students might face problems implementing different CPU scheduling algorithms if they lack an
understanding of programming concepts.

D. Acceptance and Evaluation


The teacher will discuss all the steps for each algorithm. Students are expected to implement each of the
algorithms in any programming language during the class. This lab will be graded. No home assignment is
allowed for the lab.

Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.

Round Robin Algorithm

Aim: To simulate the CPU scheduling algorithm round-robin.

Description:

To aim is to calculate the average waiting time. There will be a time slice, each process should be
executed within that time slice and if not it will go to the waiting state so first check whether the burst
time is less than the time slice. If it is less than it assign the waiting time to the sum of the total times. If
it is greater than the burst time then subtract the time slot from the actual burst time and increment it by
time-slot and the loop continues until all the processes are completed.
Algorithm:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue and time quantum (or) time slice
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Calculate the no. of time slices for each process where No. of time slice for a process (n) = burst
time process (n)/time slice

18
Step 5: If the burst time is less than the time slice then the no. of time slices =1.
Step 6: Consider the ready queue is a circular Q, calculate
a) Waiting time for process (n) = waiting time of process(n-1)+ burst timeof process(n-1 ) + the
time difference in getting the CPU fromprocess(n-1)
b) Turnaround time for process(n) = waiting time of process(n) + burst time of process(n)+ the
time difference in getting CPU from process(n).
Step 7: Calculate
a) Average waiting time = Total waiting Time / Number of processes
b) Average Turnaround time = Total Turnaround Time / Number of process
Step 8: Stop the process

Priority scheduling:

Aim: To write a c program to simulate the CPU scheduling priority algorithm.

Description:
To calculate the average waiting time in the priority algorithm, sort the burst times according to their
priorities and then calculate the average waiting time of the processes. The waiting time of each
process is obtained by summing up the burst times of all the previous processes.
Algorithm:

Step 1: Start the process

19
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Sort the ready queue according to the priority number.
Step 5: Set the waiting of the first process as `0` and its burst time as its turnaround time
Step 6: Arrange the processes based on process priority
Step 7: For each process in the Ready Q calculate
a) Waiting time(n)= waiting time (n-1) + Burst time (n-1)
b) Turnaround time (n)= waiting time(n)+Burst time(n)
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of processes
b) Average Turnaround time = Total Turnaround Time / Number of processes. Print the
results in an order.
Step9:Stop

Task:
The students will be assigned the Open ended Lab Task

20
Lab Task 05: Multi-Level Queue Scheduling
A. Overview:
Write a C program to simulate the multilevel queue scheduling algorithms to find the turnaround time and
waiting time.
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of multilevel queue
scheduling. Also, they will be able to implement the algorithm.

C. Possible Challenges and Their Solutions


Students might face problems in the implementation of the algorithms if they have lacking in an
understanding of programming concepts.

D. Acceptance and Evaluation


The teacher will discuss all the steps for each algorithm. Students are expected to implement the algorithm in
any programming language during the class. This lab will be graded. No home assignment is allowed for the
lab.

Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.
● Students are assigned with a project

Description
Multi-level queue scheduling algorithm is used in scenarios where the processes can be classified into
groups based on properties like process type, CPU time, IO access, memory size, etc. In a multi-level queue
scheduling algorithm, there will be 'n' number of queues, where 'n' is the number of groups the processes are
classified into. Each queue will be assigned a priority and will have its own scheduling algorithm like
round-robin scheduling or FCFS. For the process in a queue to execute, all the queues of priority higher than
it should be empty, meaning the process in those high priority queues should have completed its execution. In
this scheduling algorithm, once assigned to a queue, the process will not move to any other queues.

Algorithm:
All the processes in the system are divided into two categories – system processes and user processes.
System processes are to be given higher priority than user processes. System processes are added in Queue1
(Priority 1) and user processes are added in Queue2 (Priority 2).
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: Create two queues, each with its own priority level.
Step 4: For each process, assign the process ID and accept the CPU burst time
Step 5: Assign each incoming process to the appropriate queue based on its priority level.
Step 6: Implement a scheduling algorithm for each queue, such as Round Robin, First-Come-First-Serve,
or Priority Scheduling.

21
Step 7: If all processes from Queue1 finish execution, then the processes from queue2 will be executed.
Step 8: Calculate
a) Average waiting time = Total waiting Time / Number of processes

b) Average Turnaround time = Total Turnaround Time / Number of processes

Step 9: Stop the process

Project Assignment:

1. The teacher defines the objective, requirements, deadlines, and evaluation criteria of the project.
This will help ensure that students understand what is expected of them and can work effectively
together.
2. Students create their own project groups. Each group contains a maximum of 3 members.
3. The teacher assigns a particular problem to students.

22
Lab Task 06: File allocation strategies
A. Overview:
Write a C program to simulate the following file allocation strategies:
a. Sequential
b. Indexed
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.

C. Possible Challenges and Their Solutions


Students might face problems in the implementation of the algorithms if they have lacking in an
understanding of programming concepts.

D. Acceptance and Evaluation


The teacher will discuss all the steps for each algorithm. Students are expected to implement the algorithm in
any programming language during the class. This lab will be graded. No home assignment is allowed for the
lab.

Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.

Description
A file is a collection of data, usually stored on disk. As a logical entity, a file enables to divide data
into meaningful groups. As a physical entity, a file should be considered in terms of its organization. The term
"file organization" refers to the way in which data is stored in a file and, consequently, the method(s) by
which it can be accessed.

Sequential File Allocation


In this file organization, the records of the file are stored one after another both physically and logically. That
is, record with sequence number 16 is located just after the 15th record. A record of a sequential file can only
be accessed by reading all the previous records.

Algorithm:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations to each in sequential order. Randomly select a
location from available location s1= random(100);
a) Check whether the required locations are free from the selected location.

if(b[s1].flag==0){
for (j=s1;j<s1+p[i];j++){ if((b[j].flag)==0)count++;

23
}
if(count==p[i]) break;
}
b) Allocate and set flag=1 to the allocated locations.
for(s=s1;s<(s1+p[i]);s++) {
k[i][j]=s; j=j+1; b[s].bno=s; b[s].flag=1;
}
Step 5: Print the results file no, length, Blocks allocated.
Step 6: Stop the program

3.2.3 Indexed File Allocation


Indexed file allocation strategy brings all the pointers together into one location: an index block.
Each file has its own index block, which is an array of disk-block addresses. The ith entry in the index
block points to the ith block of the file. The directory contains the address of the index block. To find
and read the ith block, the pointer in the ith index-block entry is used.

Algorithm:

Step 1: Start the program.


Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations by selecting a location randomly q= random(100);
Check whether the selected location is free .
If the location is free allocate and set flag=1 to the allocated locations.
q=random(100);
if(b[q].flag==0)
b[q].flag=1;

24
b[q].fno=j;
r[i][j]=q;
Step 5: Print the results file no, length, Blocks allocated.
Step 6: Stop the program

enter index block 9


Enter no of files on index 3 1 2 3
Allocated File indexed 9->1:1
9->2;1
9->3:1

25
Lab Task 07: Memory Allocation Techniques

A. Overview:
Write a program to simulate the following contiguous memory allocation techniques
a) Worst-fit b) Best-fit c) First-fit
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.

C. Possible Challenges and Their Solutions


Students might face problems in the implementation of the algorithms if they have lacking in an
understanding of programming concepts.

D. Acceptance and Evaluation


The teacher will discuss all the steps for each algorithm. Students are expected to implement the algorithm in
any programming language during the class. This lab will be graded. No home assignment is allowed for the
lab.

Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.

Description
One of the simplest methods for memory allocation is to divide memory into several fixed-sized partitions.
Each partition may contain exactly one process. In this multiple-partition method, when a partition is free, a
process is selected from the input queue and is loaded into the free partition. When the process terminates, the
partition becomes available for another process. The operating system keeps a table indicating which parts of
memory are available and which are occupied. Finally, when a process arrives and needs memory, a memory
section large enough for this process is provided. When it is time to load or swap a process into main memory,
and if there is more than one free block of memory of sufficient size, then the operating system must decide
which free block to allocate. Best-fit strategy chooses the block that is closest in size to the request. First-fit
chooses the first available block that is large enough. Worst-fit chooses the largest available block.

Program
Worst-Fit
#include<stdio.h>
#include<conio.h>
#define max 25

void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();

26
printf("\n\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

BEST-FIT

Best Fit

27
#include<stdio.h>
#include<conio.h>
#define max 25

void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
clrscr();

printf("\nEnter the number of blocks:");


scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
printf("Block %d:",i);scanf("%d",&b[i]);

printf("Enter the size of the files :-\n");


for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
if(lowest>temp)
{
ff[i]=j;
17
lowest=temp;
}
}
}
frag[i]=lowest;
bf[ff[i]]=1;
lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock Size\tFragment");
for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

28
FIRST-FIT
#include<stdio.h>
#include<conio.h>
#define max 25

void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];
clrscr();

printf("\n\tMemory Management Scheme - Worst Fit");


printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}

29
for(i=1;i<=nf;i++)
{
18
for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i];
if(temp>=0)
if(highest<temp)
{
ff[i]=j;
highest=temp;
}
}
}
frag[i]=highest;
bf[ff[i]]=1;
highest=0;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

30
Lab Task 08: File Organization Techniques

A. Overview:
Write a C program to simulate the following file organization techniques
a) Single level directory
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.

C. Possible Challenges and Their Solutions


Students might face problems in the implementation of the algorithms if they have lacking in an
understanding of programming concepts.

D. Acceptance and Evaluation


The teacher will discuss all the steps for each algorithm. Students are expected to implement the algorithm in
any programming language during the class. This lab will be graded. No home assignment is allowed for the
lab.

Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.

SINGLE LEVEL DIRECTORY:

AIM: Program to simulate Single level directory file organization technique.


DESCRIPTION:
The directory structure is the organization of files into a hierarchy of folders. In a single-level
directory system, all the files are placed in one directory. There is a root directory which has all files.
It has a simple architecture and there are no sub directories. Advantage of single level directory
system is that it is easy to find a file in the directory. In the two-level directory system, each user has
own user file directory (UFD). The system maintains a master block that has one entry for each user.
This master block contains the addresses of the directory of the users. When a user job starts or a
user logs in, the system's master file directory (MFD) is searched. When a user refers to a particular
file, only his own UFD is searched.
This effectively solves the name collision problem and isolates users from one another. Hierarchical
directory structure allows users to create their own subdirectories and to organize their files
accordingly. A tree is the most common directory structure. The tree has a root directory, and every
file in the system has a unique path name. A directory (or subdirectory) contains a set of files or
subdirectories.
SOURCE CODE :

31
#include<stdio.h>
struct
{
char dname[10],fname[10][10]; int fcnt;
}dir;
void main()
{
int i,ch; char f[30]; clrscr();
dir.fcnt = 0;
printf("\nEnter name of directory -- ");
scanf("%s", dir.dname);
while(1)
{
printf("\n\n1. Create File\t2. Delete File\t3. Search File \n
4. Display Files\t5. Exit\nEnter your choice -- ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the name of the file -- "); scanf("%s",dir.fname[dir.fcnt]); dir.fcnt++;
break;

case 2: printf("\nEnter the name of the file -- "); scanf("%s",f); for(i=0;i<dir.fcnt;i++) {


if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is deleted ",f); strcpy(dir.fname[i],dir.fname[dir.fcnt-1]); break; }
}
if(i==dir.fcnt)
printf("File %s not found",f);
else
dir.fcnt--;
break;
case 3: printf("\nEnter the name of the file -- ");
scanf("%s",f);
for(i=0;i<dir.fcnt;i++)
{
if(strcmp(f, dir.fname[i])==0)
{
printf("File %s is found ", f);
break;
}

32
}
if(i==dir.fcnt)
printf("File %s not found",f);
break;
Case 4: if(dir.fcnt==0)
printf("\nDirectory Empty");
else
{
printf("\nThe Files are -- ");
for(i=0;i<dir.fcnt;i++)
printf("\t%s",dir.fname[i]);
}
break;
default: exit(0);
}
}
getch();
}

33
Lab Task 09: File Organization Techniques

A. Overview:
Write a C program to simulate the following file organization techniques
a) Two level directory
B. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.

C. Possible Challenges and Their Solutions


Students might face problems in the implementation of the algorithms if they have lacking in an
understanding of programming concepts.

D. Acceptance and Evaluation


The teacher will discuss all the steps for each algorithm. Students are expected to implement the algorithm in
any programming language during the class. This lab will be graded. No home assignment is allowed for the
lab.

Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.

Two Level Directory

Program to simulate two level file organization technique


Algorithm:
Step 1: Start
Step 2: Initialize structure elements struct tree_ element char name[20];
Initialize integer variables x, y, ftype, lx, rx, nc, level;
struct tree_element
*link[5];}
typedef structure tree_element node;
Step 3:start main function
Step 4: Step variables gd=DETECT,gm; node *root; root=NULL;
Step 5:create structure using create(&root,0,"null",0,639,320);
Step 6:initgraph(&gd, &gm,"c:\tc\bgi"); display(root); closegraph();
Step 7: end main function
Step 8: Initialize variables i,gap;
Step 9:if check *root==NULL (*root)=(node*)malloc(sizeof(node));
enter name of ir file namein dname; fflush(stdin);
gets((*root)->name);

34
Step 10: if check lev==0||lev==1 (*root)->ftype=1; else(*root)->ftype=2;
(*root)->level=lev; (*root)->y=50+lev*5; (*root)->x=x; (*root)
->lx=lx; (*root)->rx=rx;
Step 11:for i=0&&i<5 increment i
(*root)->link[i]=NULL;
if check (*root)->ftype==1
Step 12: if check (lev==0||lev==1)
if check(*root)->level==0
print "how many users"
else print"how many files"
print (*root)->name
read (*root)->nc
Step 13:Then (*root)->nc=0; if check(*root)->nc==0 gap=rx-lx;
else gap=(rx-lx)/(*root)->nc;
Step 14:for i=0&&i<(*root)->nc increment i;
create(&((*root)->link[i]),lev+1,(*root)->name,
lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2); then
(*root)->nc=0;
Step 15: Initialize e display function Initialize i set textstyle(2,0,4); set
textjustify(1,1); set fillstyle(1,BLUE);
setcolor(14); step 13:if check root!=NULL
Step 16:for i=0&&i<root->nc increment i
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
Step 17: if check root->ftype==1
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else fill ellipse(root->x,root- >y,20,20);
out textxy(root->x,root->y,root->name);
Step 18:for i=0&&i<root->nc increment i display(root->link[i]);
Step 19:End

35
36
Lab Task 10: Bankers Algorithm for Deadlock Avoidance

A. Overview:
B. Write a C program to simulate Bankers algorithm for the purpose of deadlock avoidance.
C. Learning Outcome:
After this lecture, the students will be able to learn about the fundamental concepts of file allocation
strategies. Also, they will be able to implement the algorithm.

D. Possible Challenges and Their Solutions


Students might face problems in the implementation of the algorithms if they have lacking in an
understanding of programming concepts.

E. Acceptance and Evaluation


The teacher will discuss all the steps for each algorithm. Students are expected to implement the algorithm in
any programming language during the class. This lab will be graded. No home assignment is allowed for the
lab.

Activity List:
● The steps for each algorithm will be discussed in class.
● Students can use any programming language for implementation.
● Sample Inputs are shown in the Green boxes.
● In the blue box, students should write the appropriate output for each Algorithm.

Description
In a multiprogramming environment, several processes may compete for a finite number of resources. A
process requests resources; if the resources are not available at that time, the process enters a waiting state.
Sometimes, a waiting process is never again able to change state, because the resources it has requested are
held by other waiting processes. This situation is called a deadlock. Deadlock avoidance is one of the
techniques for handling deadlocks. This approach requires that the operating system be given in advance
additional information concerning which resources a process will request and use during its lifetime. With this
additional knowledge, it can decide for each request whether or not the process should wait. To decide
whether the current request can be satisfied or must be delayed, the system must consider the resources
currently available, the resources currently allocated to each process, and the future requests and releases of
each process. Banker’s algorithm is a deadlock avoidance algorithm that is applicable to a system with
multiple instances of each resource type.

Program
#include<stdio.h>
struct file
{
int all[10];
int max[10];
int need[10];
int flag;

37
};
void main()
{
struct file f[10];
int fl;
int i, j, k, p, b, n, r, g, cnt=0, id, newr;
int avail[10],seq[10];
clrscr();
printf("Enter number of processes -- ");
scanf("%d",&n);
printf("Enter number of resources -- ");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("Enter details for P%d",i);
printf("\nEnter allocation\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("Enter Max\t\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("\nEnter Available Resources\t -- \t");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);

printf("\nEnter New Request Details -- ");


printf("\nEnter pid \t -- \t");
scanf("%d",&id);
printf("Enter Request for Resources \t -- \t");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i] += newr;
29
avail[i]=avail[i] - newr;
}

for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)

38
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
b=b+1;
else
b=b-1;
}
if(b==r)
{
printf("\nP%d is visited",j);
seq[fl++]=j;
f[j].flag=1;
for(k=0;k<r;k++)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("(");
for(k=0;k<r;k++)
printf("%3d",avail[k]);
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("\n REQUEST NOT GRANTED -- DEADLOCK OCCURRED");
printf("\n SYSTEM IS IN UNSAFE STATE");
goto y;
}
}
printf("\nSYSTEM IS IN SAFE STATE");
printf("\nThe Safe Sequence is -- (");

39
for(i=0;i<fl;i++)
printf("P%d ",seq[i]);
printf(")");
y: printf("\nProcess\t\tAllocation\t\tMax\t\t\tNeed\n");
for(i=0;i<n;i++)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
30
printf("%6d",f[i].all[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].max[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].need[j]);
printf("\n");
}
getch();
}

INPUT
Enter number of processes – 5
Enter number of resources -- 3
Enter details for P0
Enter allocation -- 0 1 0
Enter Max -- 7 5 3

Enter details for P1


Enter allocation -- 2 0 0
Enter Max -- 3 2 2

Enter details for P2


Enter allocation -- 3 0 2
Enter Max -- 9 0 2

Enter details for P3


Enter allocation -- 2 1 1
Enter Max -- 2 2 2

Enter details for P4


Enter allocation -- 0 0 2
Enter Max -- 4 3 3

Enter Available Resources -- 3 3 2


Enter New Request Details --
Enter pid -- 1
Enter Request for Resources -- 1 0 2

40
OUTPUT
P1 is visited( 5 3 2)
P3 is visited( 7 4 3)
P4 is visited( 7 4 5)
P0 is visited( 7 5 5)
P2 is visited( 10 5 7)
SYSTEM IS IN SAFE STATE
The Safe Sequence is -- (P1 P3 P4 P0 P2 )

Process Allocation Max Need P0 0 1 0 7 5 3 7 4 3 P1 3 0 2 3 2 2 0 2 0


P2 3 0 2 9 0 2 6 0 0 P3 2 1 1 2 2 2 0 1 1 P4 0 0 2 4 3 3 4 3 1

41
Lab Task 11: Lab Final Exam

Overview:
This Lab is reserved for the Lab Final Exam.

42

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy