IV Sem - Aiml - Os Lab Manual-2024-25
IV Sem - Aiml - Os Lab Manual-2024-25
PROGRAM - B.E
PRINCIPLES OF OPERATING SYSTEMS (22 AMC 09)
( CSE-AI&ML)
SEMESTER - IV
R-22 Regulation
1|Page
CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE
LEARNING (AI&ML)
No
Syllabus 7
Course Introduction 8
2|Page
LABORATORY / PRACTICAL
Exp Pag
Laboratory / Practical CO BTL
No e No
1 Shell programming.
1 2,3 28
2 Demonstration and Performance Evaluation of CPU scheduling
algorithms
3 Implementation of memory management techniques like 4 2,3,4 71
paging and segmentation.
4 Implementation of Linked, Indexed and Contiguous file 4 2,3,4 77
allocation methods.
5 Demonstration of Linux/Unix file related system calls: mkdir, 1,2 2,3 14
link, unlink, mount, unmount, users+, chown, chmod, open,
close, read, write, lseek, stat, sync.
6 Implementation of producer-consumer, readers- writers and dining philosophers
problem using semaphores
7 Demonstration of Bankers Algorithm for Deadlock Avoidance. 5 2,3,4 37
2 Demonstrate non preemptive Shortest Job First or Shortest Job 4,5 3,4 48
next CPU scheduling.
3 Demonstrate pre-emptive Shortest Job First or Shortest Job 4,5 3,4 49
next CPU scheduling
4 Demonstrate Round Robin CPU scheduling 4,5 3,4 52
3|Page
Note:
a) Minimum 12 experiments should be included in every course other than
experiments beyond syllabus.
b) Add project/ case studies/ student defined experiments for the courses having
experiments less than 12 in syllabus.
c) Include Minimum 2 experiments beyond prescribed experiments meeting industry
problems to challenge student learning.
4|Page
CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in
Vision of Institute
To be the Centre of Excellence in Technical Education and
Research.
Mission of Institute
To address the Emerging needs through Quality Technical
Education and Advanced Research.
Quality Policy
CBIT imparts value based Technical Education and Training to
meet the requirements of students, Industry, Trade/
Profession, Research and Development Organizations for Self-
sustained growth of Society.
5|Page
CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE
LEARNING (AI&ML)
PEO1: Using a solid foundation in mathematical, scientific, engineering, and current computing
Principles, formulate, analyse, and resolve engineering issues.
PEO2: Apply artificial intelligence theory and concepts to analyse the requirements, realise technical
Specifications, and design engineering solutions.
PEO3: Through cross-disciplinary projects and a variety of professional activities, demonstrate
technical proficiency, AI competency, and foster collaborative learning and a sense of teamwork.
PEO4: Provide graduates with solid knowledge, competence, and soft skills that will enable them to
ethically contribute to societal demands and achieve sustainable advancement in emerging
computer technologies through lifelong learning.
6|Page
CHAITANYA BHARATHI INSTITUTE OF TECHNOLOGY
(An Autonomous Institution, Affiliated to Osmania University, Approved by AICTE,
Accredited by NAAC with A++ Grade and Programs Accredited by NBA)
Chaitanya Bharathi Post, Gandipet, Kokapet (Vill.), Hyderabad, Ranga Reddy - 500 075, Telangana
www.cbit.ac.in
DEPARTMENT OF ARTIFICIAL INTELLIGENCE
AND MACHINE LEARNING (AI&ML)
7|Page
Environment and sustainability: Understand the impact of the
professional engineering solutions in societal and environmental contexts,
and demonstrate the knowledge of, and need for sustainable development.
Life-long learning: Recognise the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest context
of technological change.
PSO2. Apply the knowledge gained pertaining to data storage, data analytics
and AI concepts to solve real world business problems.
8|Page
20AMC09
PRINCIPLES OF OPERATING SYSTEMS LAB
Instruction 3 Hours per week
Duration of End Examination 3 Hours
Semester End Examination 50 Marks
Continuous Internal Evaluation 50 Marks
Credits 1
Course Outcomes: On Successful completion of this course, student will be able to,
1. Understand Linux/Unix environment.
2. Understand and implement shell programming.
3. Simulate memory management and file allocation techniques.
4. Analyze process and file management system calls by creating and/or modifying concurrent programs.
5. Build network-oriented applications using system calls.
List of Experiments:
1. Shell programming.
2. Demonstration and Performance Evaluation of CPU scheduling algorithms
3. Implementation of memory management techniques like paging and segmentation.
4. Implementation of Linked, Indexed and Contiguous file allocation methods.
5. Demonstration of Linux/Unix file related system calls: mkdir, link, unlink, mount, unmount, users+, chown,
chmod, open, close, read, write, lseek, stat, sync.
6. Implementation of producer-consumer, readers- writers and dining philosophers problem using semaphores
7. Demonstration of Bankers Algorithm for Deadlock Avoidance.
8. Development of applications using Linux/Unix system calls: signal, socket, accept, snd, recv, connect.
Text Books:
1. Galvin, Silberschatz, “Operating System Concepts”, 10th Edition, John Wiley & Sons, 2018.
2. Dhananjay Dhamdhare, “Operating Systems-A Concept Based Approach”, 3rd Edition, McGraw Hill Education,
2017.
Suggested Reading:
1. Ekta Walia, “Operating System Concepts”, Khanna Book Publishing, 2020.
2. William Stallings, “Operating Systems Internals and Design Principles”, Pearson Ed., 2012.
3. Charles Crowley, “Operating Systems –A Design Oriented Approach”, McGraw Hill Education, 2017.
1. Andrew S. Tanenbaum, Albert S Woodhull, “Operating systems Design and Implementation”, Pearson Ed., 2009.
Mapping of Course Outcomes with Program Outcomes and Program Specific Outcomes:
PO/PSO PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO PSO
CO 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO 1 2 1 1 1 1 1
CO 2 2 2 1 1 1
CO 3 2 2 1 2 1
CO 4 2 2 2 1 1 1 1
CO 5 2 1 1 1 1 1 1
9|Page
COURSE INTRODUCTION
Name of the Lab Course:
PRINCIPLES OF OPERATING SYSTEMS LAB (20AMC09)
An Operating Systems (OS) Lab course is designed to complement theoretical
knowledge gained in an Operating Systems lecture course by providing hands-on
experience with practical aspects of operating system concepts. The lab course
typically involves a series of experiments and projects that allow students to apply
their understanding of operating systems principles to real-world scenarios. Here are
key aspects typically covered in an Operating Systems Lab course: Environmental
Setup, Process management, Memory management, concurrency and synchronization,
File allocation techniques, paging , segmentation, networking and distributed sytems,
security and protection.
5. Networking Concepts:
10 | P a g e
Application: Implementing simple networking protocols and socket programming.
Benefits: Students gain practical exposure to networked environments, understanding
communication between processes over a network.
6. Security Measures:
Application: Implementing security mechanisms and access control.
Benefits: Students learn about authentication, encryption, and protection mechanisms to
enhance system security.
8. Project-Based Learning:
Application: Working on comprehensive OS projects.
Benefits: Students apply integrated knowledge to solve real-world problems, enhancing
problem-solving and project management skills.
9. Performance Analysis:
Application: Analyzing system performance under different scenarios.
Benefits: Students explore tools for performance monitoring and gain insights into
optimizing system efficiency.
ASSESSMENT PROCEDURE AND AWARD OF
CIE MARKS
Following is the subdivision for the internal marks (50) of the Lab:
Two tests are to be conducted i.e one test after 1st cycle of experiments
and second test after the second cycle. Average of two tests marks put
together should be consider (20 maximum)
For the CIE 30 marks will be awarded based on the rubrics provided below.
This Rubrics are general guideline. Based on the lab type (programming or
hardware) and complexity of the course Rubrics can be customized by the
department in tune to program and course offered. Performance Indicators of the
Rubrics also can be changed by the departments/Program based on the need.
11 | P a g e
RUBRICS
S.
Parameter
No
12 | P a g e
Descriptors and Score
S.
Parameter
No
TOTAL SCORE 50
13 | P a g e
ASSESSMENT PROCEDURE AND AWARD OF
SEE MARKS
Paramete Descriptors and Score
r Very
Outstanding Good Fair Poor
Poor
Record The content of all The content of The content The content The
5M the experiments most of the of the most of the few content
is well-organized, experiments of experiments of the all
recorded the are well- experiments is not well- the
tables and neatly organized, are well- organized, experime
drawn graphs. recorded the organized, recorded the nts is not
Results and tables, neatly recorded the tables, neatly well-
discussions are drawn graphs. tables, drawn organize
well presented. Results and neatly drawn graphs. d,
(5M) discussion are graphs. Results and recorded
presented. (4M) Results and discussion are the
discussion not presented tables,
are not (2M) neatly
presented drawn
(3M) graphs.
Results
and
discussio
n are not
presente
d (1M)
Write up Presentation of Presentation of Presentation Presentation Presentat
about the the given the given of the given of the given ion of the
experiment experiment/progr experiment/pro experiment/ experiment/pr given
10M am is very well gram is program is ogram is experime
organized with organized with organized minimal with nt/progra
the required the required and is clear m is
content, content, without clear specifications minimum
specifications, specifications, specification and without
plan/procedure plan/procedure s and plan/design. clear
of the conduct of the conduct. plan/design. (4M) specificat
and all the (8M) (6M) ions and
required plan/desi
additional gn.
information. (2M)
(10M)
Conduction Conducts Conducts Conducts Conducts Failed to
of the experiment / experiment / experiment / experiment / Conducts
experiment Simulate the Simulate the Simulate the Simulate the experime
and problem with problem with problem with problem with nt /
observation proper connections / proper improper Simulate
s connections / all with most of connections / connections / the
15M possible test the test cases. less test less test problem
cases. All the Failed to note cases. cases. (6M) with
possible all observations (9M) improper
observations are (12M) connectio
noted. (15M) ns / less
test
cases.
(3M)
Results & Demonstrates Demonstrates Demonstrate Demonstrates Failed to
Analysis the experimental the s the the partial Demonst
10M results with experimental experimental experimental rate the
adequate results with results, results with results
analysis / required failed to least and
14 | P a g e
Paramete Descriptors and Score
r Very
Outstanding Good Fair Poor
Poor
simulation/ analysis / maximum analysis / least
findings simulation/ analysis / simulation/ analysis /
/obtained findings simulation/ findings. simulatio
results /plotting /obtained findings. (4M) n/
the graphs. results /plotting (6M) findings.
(10M) the graphs. (2M)
(8M)
Viva-Voce Answers most of Answers most Answers only Answers only Failed to
10M the questions of the questions few of the few of the answer
with good with good questions questions questions
analytical explanation. with good with nominal . (2M)
explanation. (8M) explanation. explanation.
(10M) (6M) (4M)
TOTAL SCORE 50
16 | P a g e
Pag
Exp No Laboratory / Practical CO BTL
e No
WEEK 1 & 2:
Explore the Linux/Unix Commands
i) File/Directory Related
1 1 1 17
ii) Process Related
iii) Network Related
Write a shell script to:
Write a shell script to
i) Check given number is prime or not
ii) Check given number is palindrome number
2 iii) Check given number is Armstrong number 3 2 31
iv) Convert decimal to binary
v) Convert decimal to base 5
vi) Convert base 5 to decimal
WEEK 3:
A.
FILE RELATED COMMANDS:
1. Pwd Command:
DESCRIPTION: It displays the present working directory
SYNTAX: pwd
OUTPUT:
2. Cd Command:
DESCRIPTION: It changes the working directory i.e., change the current working to some other folder.
SYNTAX: cd [option] [directory]
OUTPUT:
3. Ls Command:
DESCRIPTION: It lists the content/files listed in a particular UNIX directory
SYNTAX: ls [options] [filename]
OUTPUT:
4. Rm command:
DESCRIPTION: It removes files or directories
SYNTAX: rm [option …] filelist
OUTPUT:
Before using rm command:
18 | P a g e
5. Mv command:
DESCRIPTION: It is used to move files or directories from one place to another or renames the files.
SYNTAX: mv [option] [sourceFile] [destFile]
If destination file doesn’t exist then it will be created else it will overwrite and the source file is deleted.
OUTPUT:
Renaming the file present in directory
6. Cat Command:
DESCRIPTION: It allows us to create single or multiple files, view content of file, concatenate files and
redirect output in terminal or files.
SYNTAX: cat [option …] [file …]
OUTPUT:
Text file is created
7. Cmp Command:
DESCRIPTION: It compares two files, and if they differ, tells the first byte and line number where they
differ.
SYNTAX: cmp [option …] fromfile tofile
OUTPUT:
19 | P a g e
8. Cp Command:
DESCRIPTION: It copies the files
SYNTAX: cp [option] source destination
OUTPUT:
9. Echo Command:
DESCRIPTION: It is used for displaying a line of string/text that is passed as the arguments
SYNTAX: echo [option] [string]
OUTPUT:
20 | P a g e
12. Rmdir Command:
DESCRIPTION: It removes the directories
SYNTAX: rmdir [options] DirectoryNames
OUTPUT:
21 | P a g e
14. Tail Command:
DESCRIPTION: It displays the tail end of a text file or piped data. It prints the last 10 line sof the
specified file.
SYNTAX: tail [option] [files]
OUTPUT:
22 | P a g e
16. Grep Command:
DESCRIPTION: It prints lines matching a pattern
SYNTAX: grep [options] PATTERN [file]
OUTPUT:
23 | P a g e
19. Man Command:
DESCRIPTION: It is the interface to view the system’s reference manuals.
SYNTAX: man ls
OUTPUT:
24 | P a g e
PROCESS RELATED COMMANDS:
1. Top Command:
DESCRIPTION: To track the running processes on our machine
SYNTAX: top
OUTPUT:
25 | P a g e
2. Ps Command:
DESCRIPTION: ps is short for Process status. It displays the currently-running processes.
SYNTAX: ps
OUTPUT:
3. Kill Command:
DESCRIPTION: It sends a signal to the process. There are different types of signals that we can send
SYNTAX: kill [number]
OUTPUT:
List of different types of signals
4. Nice Command:
DESCRIPTION: The Nice command configures the priority of a Linux process before it is started. The
renice command sets the priority of an already running process.
SYNTAX: nice -nice_value command-arguments; renice -n nice_value –p pid_of_the_process
OUTPUT:
26 | P a g e
NETWORK RELATED COMMANDS:
1. Ping Command:
DESCRIPTION: It allows us to test the reachability of a device on a network
SYNTAX: ping [host]
OUTPUT:
2. Ifconfig Command:
DESCRIPTION: The command ifconfig stands for interface configurator. This command enables us to
initialize an interface, assign IP address, enable or disable an interface. It displays route and network
interface.
SYNTAX: ifconfig
OUTPUT:
27 | P a g e
3. Netstat Command:
DESCRIPTION: The Netstat command displays active TCP connections, ports on which the computer is
listening. The information this command provides can be useful in pinpointing problems in our network
connections.
SYNTAX: netstat
OUTPUT:
4. Nslookup Command:
DESCRIPTION: NsLookUp command is used to find all the IP addresses for given domain name.
SYNTAX: nslookup host
OUTPUT:
28 | P a g e
5. Telnet Command:
DESCRIPTION: It connects destination via the telnet protocol, if telnet connection establishes on any
port means connectivity between two hosts is working fine.
SYNTAX: telnet hostname/IP address
OUTPUT:
6. Traceroute Command:
DESCRIPTION: A handy utility to view the number of hops and response time to get to a remote system
or website is a traceroute.
SYNTAX: traceroute [OPTION...] HOST
OUTPUT:
CONCLUSION:
By executing the above commands, we have understood the commands.
To Study about UNIX vi Editor and its features:
The default editor that comes with the UNIX operating system is vi editor (visual editor).
Using vi editor, we can edit an existing file or create a new file from scratch.
We can also use this editor to just read a text file
Syntax: vi filename
29 | P a g e
Modes of Operation in vi editor:
There are three modes of operation in vi:
- Command Mode:
i. When vi starts up, it is in Command Mode.
ii. This mode is where vi interprets any characters we type as commands and thus does not
display them in the window.
iii. This mode allows us to move through a file, and to delete, copy, or paste a piece of text.
iv. To enter into Command Mode from any other mode, it requires pressing the [Esc] key.
v. If we press [Esc] when we are already in Command Mode, then vi will beep or flash the
screen
- Insert Mode:
i. This mode enables you to insert text into the file.
ii. Everything that’s typed in this mode is interpreted as input and finally, it is put in the file.
iii. The vi always starts in command mode.
iv. To enter text, you must be in insert mode. To come in insert mode you simply type i.
v. To get out of insert mode, press the Esc key, which will put you back into command mode.
- Last Line Mode (Escape Mode):
i. Line Mode is invoked by typing a colon [:], while vi is in Command Mode.
ii. The cursor will jump to the last line of the screen and vi will wait for a command.
iii. This mode enables you to perform tasks such as saving files, executing commands.
Vi Commands:
To switch from command to insert mode:
- i – Start typing before the current character
- l – Start typing at the start of current line
- a – Start typing after the current character
- A – Start typing at the end of current line
- o – Start typing on a new line after the current line
- O – Start typing on a new line before the current line
To move around a file:
- j – To move down
- k – To move up
- h – To move left
- l – To move right
To delete:
- x – Delete the current character
- X – Delete the character before the cursor
- r – Replace the current character
- xp – Switch two characters
- dd – Delete the current line
- D – Delete the current line from current character to the end of the line
- dG – Delete from the current line to the end of the file
To repeat or undo:
- u – Undo the last command
- . – repeat the last command
To save and quit:
- :wq – Save and quit
- :w – Save
- :q – Quit
- :w fname – Save as fname
- ZZ – Save and quit
- :q! – Quit discarding changes made
- :w! – Save (and write to non-writable file)
Command to cut, copy and paste:
- dd – delete a line
30 | P a g e
- yy – (yank yank) copy a line
- p – Paste after the current line
- P – Paste before the current line
- <n>dd – Delete the specified n number of lines
- <n>yy – Copy the specified n number of lines
Start and end of line:
- 0 – Bring at the start of the current line
- ^ - Bring at the start of the current line
- $ - Bring at the end of the current line
- d0 – Delete till start of a line
- d$ - Delete till end of a line
Joining lines:
- J – Join two lines
- yyp – Repeat the current line
- ddp – Swap two lines
Move forward or backward:
- w – Move one word forward
- b – Move one word backward
- <n>w – Move specified number of words forward
- dw – Delete one word
- yw – Copy one word
- <n>dw – Delete specified number of words
31 | P a g e
2.
Aim: Write a shell script to
a. Check given number is prime or not
b. Check given number is palindrome number
c. Check given number is Armstrong number
d. Convert decimal to binary
e. Convert decimal to base 5
f. Convert base 5 to decimal
Program:
a) A Program to check given number is prime or not
PROGRAM:
echo -n "Enter Number : "
read n
for((i=2; i<=$n/2; i++))
do
ans=$(( n%i ))
if [ $ans -eq 0 ]
then
echo "$n is not a prime number."
exit 0
fi
done
echo "$n is a prime number."
OUTPUT:
32 | P a g e
OUTPUT:
OUTPUT:
35 | P a g e
WEEK-3
1)
Aim: Write a Program to demonstrate First Come First Serve CPU scheduling
Program:
#include<stdio.h>
int main()
{
int p[10],at[10],bt[10],ct[10],tat[10],wt[10],i,j,temp=0,n;
float awt=0,atat=0;
printf("enter no of proccess you want:");
scanf("%d",&n);
printf("enter %d process:",n);
for(i=0;i<n;i++)
{
scanf("%d",&p[i]);
}
printf("enter %d arrival time:",n);
for(i=0;i<n;i++)
{
scanf("%d",&at[i]);
}
printf("enter %d burst time:",n);
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<(n-i);j++)
{
if(at[j]>at[j+1])
{
temp=p[j+1];
p[j+1]=p[j];
p[j]=temp;
temp=at[j+1];
at[j+1]=at[j];
at[j]=temp;
temp=bt[j+1];
bt[j+1]=bt[j];
bt[j]=temp;
}
}
}
ct[0]=at[0]+bt[0];
for(i=1;i<n;i++)
{
temp=0;
if(ct[i-1]<at[i])
36 | P a g e
{
temp=at[i]-ct[i-1];
}
ct[i]=ct[i-1]+bt[i]+temp;
}
printf("\np\t A.T\t B.T\t C.T\t TAT\t WT");
for(i=0;i<n;i++)
{
tat[i]=ct[i]-at[i];
wt[i]=tat[i]-bt[i];
atat+=tat[i];
awt+=wt[i];
}
atat=atat/n;
awt=awt/n;
for(i=0;i<n;i++)
{
printf("\nP%d\t %d\t %d\t %d \t %d \t %d",p[i],at[i],bt[i],ct[i],tat[i],wt[i]);
}
printf("\naverage turnaround time is %f",atat);
2)
Aim: Write a Program to demonstrate Shortest Job First or Shortest Job next CPU scheduling
Program:(preemptive)
#include <stdio.h>
37 | P a g e
int main()
{
int arrival_time[10], burst_time[10], temp[10];
int i, smallest, count = 0, time, limit;
double wait_time = 0, turnaround_time = 0, end;
float average_waiting_time, average_turnaround_time;
printf("\nEnter the Total Number of Processes:\t");
scanf("%d", &limit);
printf("\nEnter Details of %d Processes\n", limit);
for(i = 0; i < limit; i++)
{
printf("\nEnter Arrival Time:\t");
scanf("%d", &arrival_time[i]);
printf("Enter Burst Time:\t");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
burst_time[9] = 9999;
for(time = 0; count != limit; time++)
{
smallest = 9;
for(i = 0; i < limit; i++)
{
if(arrival_time[i] <= time && burst_time[i] < burst_time[smallest] && burst_time[i] > 0)
{
smallest = i;
}
}
burst_time[smallest]--;
if(burst_time[smallest] == 0)
{
count++;
end = time + 1;
wait_time = wait_time + end - arrival_time[smallest] - temp[smallest];
turnaround_time = turnaround_time + end - arrival_time[smallest];
}
}
average_waiting_time = wait_time / limit;
average_turnaround_time = turnaround_time / limit;
printf("\n\nAverage Waiting Time:\t%lf\n", average_waiting_time);
printf("Average Turnaround Time:%lf\n", average_turnaround_time);
return 0;
}
Output:
38 | P a g e
Program(non preemptive):
#include<stdio.h>
int main()
{
int bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,temp;
float avg_wt,avg_tat;
printf("Enter number of processes:");
scanf("%d",&n);
temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;
temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}
wt[0]=0;
for(i=1;i<n;i++)
{
wt[i]=0;
for(j=0;j<i;j++)
wt[i]+=bt[j];
total+=wt[i];
}
avg_wt=(float)total/n;
total=0;
avg_tat=(float)total/n;
printf("\n\nAverage Waiting Time=%f",avg_wt);
printf("\nAverage Turnaround Time=%f\n",avg_tat);
}
Output:
40 | P a g e
3)Aim: Write a Program to demonstrate Round Robin CPU scheduling
Program:
#include<stdio.h>
int main()
{
printf("Arrival Time:\t");
scanf("%d", &arrival_time[i]);
printf("Burst Time:\t");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
42 | P a g e
4) Aim: Write a Program to demonstrate Priority CPU Scheduling
Program(preemptive):
#include<stdio.h>
struct process
{
int WT,AT,BT,TAT,PT;
};
int main()
{
int n,temp[10],t,count=0,short_p;
float total_WT=0,total_TAT=0,Avg_WT,Avg_TAT;
printf("Enter the number of the process\n");
scanf("%d",&n);
printf("Enter the arrival time , burst time and priority of the process\n");
printf("AT BT PT\n");
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&a[i].AT,&a[i].BT,&a[i].PT);
for(t=0;count!=n;t++)
{
short_p=9;
for(int i=0;i<n;i++)
{
if(a[short_p].PT>a[i].PT && a[i].AT<=t && a[i].BT>0)
{
short_p=i;
}
}
a[short_p].BT=a[short_p].BT-1;
// total calculation
total_WT=total_WT+a[short_p].WT;
total_TAT=total_TAT+a[short_p].TAT;
}
}
Avg_WT=total_WT/n;
Avg_TAT=total_TAT/n;
return 0;
}
Output:
Program(Non preemptive):
#include<stdio.h>
struct process
{
int id,WT,AT,BT,TAT,PR;
};
44 | P a g e
struct process a[10];
// function for swapping
void swap(int *b,int *c)
{
int tem;
tem=*c;
*c=*b;
*b=tem;
}
//Driver function
int main()
{
int n,check_ar=0;
int Cmp_time=0;
float Total_WT=0,Total_TAT=0,Avg_WT,Avg_TAT;
printf("Enter the number of process \n");
scanf("%d",&n);
printf("Enter the Arrival time , Burst time and priority of the process\n");
printf("AT BT PR\n");
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&a[i].AT,&a[i].BT,&a[i].PR);
a[i].id=i+1;
// here we are checking that arrival time
// of the process are same or different
if(i==0)
check_ar=a[i].AT;
if(check_ar!=a[i].AT )
check_ar=1;
}
// if process are arrived at the different time
// then sort the process on the basis of AT
if(check_ar!=0)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(a[j].AT>a[j+1].AT)
{
swap(&a[j].id,&a[j+1].id);
swap(&a[j].AT,&a[j+1].AT);
swap(&a[j].BT,&a[j+1].BT);
swap(&a[j].PR,&a[j+1].PR);
}}}
{
min=a[j].PR;
swap(&a[i].id,&a[j].id);
swap(&a[i].AT,&a[j].AT);
swap(&a[i].BT,&a[j].BT);
swap(&a[i].PR,&a[j].PR);
}
a[i].WT=Cmp_time-a[i].AT;
Total_WT=Total_WT+a[i].WT;
// completion time of the process
Cmp_time=Cmp_time+a[i].BT;
}
}
swap(&a[i].BT,&a[j].BT);
swap(&a[i].PR,&a[j].PR);
}
}
a[i].WT=Cmp_time-a[i].AT;
Total_TAT=Total_TAT+a[i].TAT;
Avg_WT=Total_WT/n;
Avg_TAT=Total_TAT/n;
47 | P a g e
Output:
Week 3:
Ans.
PROCEDURE:
In Operating Systems, Paging is a storage mechanism used to retrieve processes from the secondary
storage into the main memory in the form of pages. The main idea behind the paging is to divide each
process in the form of pages. The main memory will also be divided in the form of frames. One page of
the process is to be stored in one of the frames of the memory. The pages can be stored at the different
locations of the memory but the priority is always to find the contiguous frames or holes. Pages of the
process are brought into the main memory only when they are required otherwise they reside in the
secondary storage. Different operating system defines different frame sizes. The sizes of each frame
must be equal. Considering the fact that the pages are mapped to the frames in Paging, page size needs
to be as same as frame size.
CODE:
#include<stdio.h>
#define MAX 50
int main()
{
int page[MAX],i,n,f,ps,off,pno;
int choice=0;
printf("\nEnter the no of peges in memory: ");
scanf("%d",&n);
printf("\nEnter page size: ");
scanf("%d",&ps);
printf("\nEnter no of frames: ");
scanf("%d",&f);
for(i=0;i<n;i++)
page[i]=-1;
printf("\nEnter the page table\n");
printf("(Enter frame no as -1 if that page is not present in any frame)\n\n");
printf("\npageno\tframeno\n-------\t-------");
for(i=0;i<n;i++)
48 | P a g e
{
printf("\n\n%d\t\t",i);
scanf("%d",&page[i]);
}
do
{
printf("\n\nEnter the logical address(i.e,page no & offset):");
scanf("%d%d",&pno,&off);
if(page[pno]==-1)
printf("\n\nThe required page is not available in any of frames");
else
printf("\n\nPhysical address(i.e,frame no & offset):%d,%d",page[pno],off);
printf("\nDo you want to continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1);
return 1;
}
OUTPUT:
Ans.
PROCEDURE:
Segmentation is a memory management technique that splits up the virtual address space of an
application into chunks. By splitting the memory up into manageable chunks, the operating system can
track which parts of the memory are in use and which parts are free. This makes allocating and
deallocating memory much faster and simpler for the operating system. The segments are of unequal
49 | P a g e
size and are not placed in a contiguous way. As it’s a non-contiguous memory allocation technique,
internal fragmentation doesn’t occur. The length is decided on the base of the purpose of the segment in
a user program. Segmentation is a memory management technique which divides the program from the
user’s view of memory. That means the program is divided into modules/segments, unlike paging in
which the program was divided into different pages, and those pages may or may not be loaded into the
memory simultaneously. Segmentation prevents internal fragmentation.
CODE:
#include<stdio.h>
int main()
{
int a[10][10],b[100],i,j,n,x,base,size,seg,off;
printf("Enter the segments count\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<size;j++)
{
x=0;
scanf("%d",&x);
// b[base]=x;
base++;
b[base]=x;
}
}
printf("Enter the segment number and offset value \n");
scanf("%d%d",&seg,&off);
if(off<a[seg][0])
{
int abs=a[seg][1]+off;
printf("the offset is less tha %d",a[seg][0]);
printf("\n %d + %d = %d\n",a[seg][1],off,abs);
printf("the element %d is at %d ",b[abs+1],abs);
}
else
{
printf("Error in locating\n");
}
}
OUTPUT:
50 | P a g e
Week 4:
51 | P a g e
scanf("%d",&a);
f[a]=1;
}
x: printf("Enter index starting block and length: ");
scanf("%d%d", &st,&len);
k=len;
if(f[st]==0)
{
for(j=st;j<(st+k);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("%d-------->%d\n",j,f[j]);
}
else
{
printf("%d Block is already allocated \n",j);
k++;
}
}
}
else
printf("%d starting block is already allocated \n",st);
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if(c==1)
goto x;
else
exit(0);
return 0;
}
OUTPUT:
CODE:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int f[50], index[50],i, n, st, len, j, c, k, ind,count=0;
//clrscr();
for(i=0;i<50;i++)
f[i]=0;
x:printf("Enter the index block: ");
scanf("%d",&ind);
if(f[ind]!=1)
{
printf("Enter no of blocks needed and no of files for the index %d on the disk : \n", ind);
scanf("%d",&n);
}
else
{
printf("%d index is already allocated \n",ind);
goto x;
}
y: count=0;
for(i=0;i<n;i++)
{
scanf("%d", &index[i]);
if(f[index[i]]==0)
count++;
}
if(count==n)
{
for(j=0;j<n;j++)
53 | P a g e
f[index[j]]=1;
printf("Allocated\n");
printf("File Indexed\n");
for(k=0;k<n;k++)
printf("%d-------->%d : %d\n",ind,index[k],f[index[k]]);
}
else
{
printf("File in the index is already allocated \n");
printf("Enter another file indexed");
goto y;
}
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if(c==1)
goto x;
else
exit(0);
return 0;
}
OUTPUT:
int main()
{
int f[50], i, st, len, j, c, k, count = 0;
//clrscr();
for(i=0;i<50;i++)
f[i]=0;
printf("Files Allocated are : \n");
x: count=0;
printf("Enter starting block and length of files: ");
scanf("%d%d", &st,&len);
for(k=st;k<(st+len);k++)
if(f[k]==0)
count++;
if(len==count)
{
for(j=st;j<(st+len);j++)
if(f[j]==0)
{
f[j]=1;
printf("%d\t%d\n",j,f[j]);
}
if(j!=(st+len-1))
printf(" The file is allocated to disk\n");
}
else
printf(" The file is not allocated \n");
printf("Do you want to enter more file(Yes - 1/No - 0)");
scanf("%d", &c);
if(c==1)
goto x;
else
exit(0);
return 0;
}
55 | P a g e
OUTPUT:
56 | P a g e
Week-5
1.
Aim: Demostrate System calls with simple example Program.
Program:
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
int main( ){
pid_t child_pid;
child_pid = fork (); // Create a new child process;
if (child_pid < 0) {
printf("fork failed");
return 1;
} else if (child_pid == 0) {
printf ("child process successfully created!\n");
printf ("child_PID = %d,parent_PID = %d\n",
getpid(), getppid( ) );
} else {
// wait(NULL);
printf ("parent process successfully created!\n");
printf ("child_PID = %d, parent_PID = %d", getpid( ), getppid( ) );
}
return 0;
}
OUTPUT:
2.
Aim: Demostrate following I/O system calls with examples
(Reference Text book : Begining Linux Progrogramming Programmer to Programmer )
i) open
ii) read
iii) Write
iv)lseek
v)ioctl
vi)stat
vi)syn
Program:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/ioctl.h>
#include<sys/stat.h>
#define WR_VALUE _IOW('a','a',int*)
#define RD_VALUE _IOR('a','b',int*)
int main()
{
// if file does not have in directory
// then file foo.txt is created.
int fd = open("sample.txt", O_RDONLY | O_CREAT);
int fd2 = open("file2.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
57 | P a g e
int fd3 = open("file3.txt", O_RDWR);
char c[20];
// reading from sample.txt
read(fd, &c, 20);
printf("Text in file is: %s\n",c);
//writing into file2.txt which was stored in c
write(fd2, c, read(fd, &c, 20));
lseek(fd, 5, SEEK_CUR);
char c1[20];
read(fd, &c1, 20);
printf("Text after lseek 10 characters: %s",c1);
printf("Enter a value to write in the file: ");
int number;
scanf("%d",&number);
ioctl(fd3, WR_VALUE,(int*) &number);
struct stat sfile;
stat("stat.c", &sfile);
printf("st_mode = %o\n",sfile.st_mode);
close(fd);
close(fd2);
close(fd3);
return 0;
}
OUTPUT:
3.
Aim: Demonstrate following File system call with examples
i) link, ii) unlink
58 | P a g e
iii) mount
iv)unmount
v) chmod
vi) chown
4.
Aim: Demonstrate how process is created and allocate memory in /proc folder with example Program.
Program:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
int a;
int fd1=open("kk.txt",O_RDONLY,742); //open system call
59 | P a g e
int fd2=open("kk1.txt",O_RDONLY,S_IRWXU|S_IRGRP|S_IXOTH);
printf(" fd1=%d,fd2=%d\n", fd1,fd2);
printf("Process Id=%d\n",getpid());
scanf("%d",&a);
}
OUTPUT:
Process Program execution output:
proc ls:
ls:
60 | P a g e
WEEK – 5
1.
Aim: Demonstrate System calls with
simple example Program
Program:
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include <stdlib.h>
int main()
{
printf(" Before fork");
int
fd1=open("kk.txt",O_RDONLY,742); //
kk.txt is a shared resource to parent and
child process
int a; // a is shared variable to
parent and child process
printf(" Process Id of parent %d \
n",getpid());
int rf=fork();
if(rf==0) // Upon successful
execution fork() --> Child process will
execute below code in if block
{
printf("Inside child process \n");
printf(" Process Id of child pid=
%d rf=%d \n ",getpid(),rf);
scanf("%d",&a);
printf(" Inside child a value is a=
%d",a);
}
else if (rf> 0) // Upon successful
execution fork() system call --> Parent
process will exceute below code in elseif
block
{
printf("Inside parent process");
printf(" Process Id of parent pid=%d
rf=%d \n",getpid(),rf);
scanf("%d",&a);
printf(" Inside parent a value is a=
%d",a);
}
else{ // Upon uncusccessful
execution fork() system call Parent
process will exceute below code in else
block
61 | P a g e
printf(" Fork unsucessful \n Indide
parent and Process Id of parent pid= %d
rf=%d \n ",getpid(),rf);
}
printf("End of process %d",
getpid());
return 0;
}
OUTPUT:
In proc folder:
2.
Aim: Write a Programt to demonstrate the use of exec system calls
Parent process --> Execute factorial of given number
Child process --> Execute prime number
PROGRAM :
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include <stdlib.h>
int main()
{
printf(" Before fork");
int
fd1=open("kk.txt",O_RDONLY,742); //
kk.txt is a shared resource to parent and
child process
int a; // a is shared variable to
parent and child process
printf(" Process Id of parent %d \
n",getpid());
int rf=fork();
62 | P a g e
{
printf("Inside child process \n");
printf(" Process Id of child pid=
%d rf=%d \n ",getpid(),rf);
printf("Child process: to execute
the prime number Program\nEnter a
number: ");
scanf("%d",&a);
int flag = 0;
for(int i=2;i<=a/2;i++){
if (a%i==0){
flag=1;
break;
}
}
if(flag==0){
printf("Given number %d is a
prime number\n",a);
}
else{
printf("Given number %d is not a
prime number\n",a);
}
}
else if (rf> 0) // Upon successful
execution fork() system call --> Parent
process will exceute below code in elseif
block
{
printf("Inside parent process");
printf(" Process Id of parent pid=%d
rf=%d \n",getpid(),rf);
printf("Parent process: to execute the
factorial of a number\nEnter a number:
");
scanf("%d",&a);
int total = 1, i = 1;
while(i<=a){
total=total*i;
i=i+1;
}
printf("Factorial value is: %d\
n",total);
}
else{ // Upon uncusccessful
execution fork() system call Parent
process will exceute below code in else
block
printf(" Fork unsucessful \n
Indide parent and Process Id of parent
63 | P a g e
pid= %d rf=%d \n ",getpid(),rf);
}
printf("End of process %d\n",
getpid());
return 0;
}
OUTPUT:
3.
Aim:
Write a program to demonstrate use following exe functions
i. int execl(const char* path,
const char* arg, …)
ii. int execlp(const char* file,
const char* arg, …)
iii. int execle(const char* path,
const char* arg, …, char*
const envp[])
iv. int execv(const char* path,
const char* argv[])
v. int execvp(const char* file,
const char* argv[])
vi. int execvpe(const char* file,
const char* argv[], char
*const envp[])
Program:
Exec.c
#include<stdio.h>
#include<unistd.h>
int main()
{
int i;
printf("I am Demo file called by
execvp() ");
printf("\n");
return 0;
}
64 | P a g e
Execv.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
char *args[]={"./exec",NULL};
execv(args[0],args);
printf("Ending-----");
return 0;
}
Output:
Execvp.c
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
char
*args[]={"./3_6_demo",NULL};
execvp(args[0],args);
printf("Ending-----");
return 0;
}
Output:
4.
Aim: Write a Program to demonstrate the
use of vfork()
PROGRAM :
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include <stdlib.h>
int main()
{
printf(" Before fork");
int
fd1=open("kk.txt",O_RDONLY,742); //
kk.txt is a shared resource to parent and
65 | P a g e
child process
int a,b; // a is shared variable to
parent and child process
printf(" Process Id of parent %d \
n",getpid());
int rf=vfork();
if(rf==0) // Upon successful
execution fork() --> Child process will
execute below code in if block
{
printf("Inside child process \n");
printf(" Process Id of child pid=
%d rf=%d \n ",getpid(),rf);
scanf("%d",&b);
printf(" Inside child b value is b=
%d",b);
OUTPUT:
66 | P a g e
5. Aim: Write a Program to demonstrate
Orphan process
PROGRAM :
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// Create a child process
int pid = fork();
if (pid > 0)
printf("in parent process\n");
6.
Aim: Write a Program to demonstrate
Zombie process
PROGRAM :
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
int main()
67 | P a g e
{
pid_t pid;
char *message;
int n;
int exit_code;
printf("fork Program starting\n");
pid = fork();
switch(pid)
{
case -1:
perror("fork failed");
exit(1);
case 0:
message = "This is the child";
n = 3;
exit_code = 37;
break;
default:
message = "This is the parent";
n = 5;
exit_code = 0;
break;
}
for(; n > 0; n--) {
puts(message);
sleep(1);
}
}
OUTPUT:
68 | P a g e
WEEK 6
Program 1
Aim: Write a Program to demonstrate the use of atexit() exit handler
Program :
#include <stdio.h>
#include <stdlib.h>
#include<fcntl.h>
#include<unistd.h>
//File Discriptors
int fd1;
int fd2;
read(fd1,buf,10);
write(1,buf,10);
printf("\nCompleted the operation A \n");
atexit(functionA );
read(fd2,buf,10);
write(1,buf,10);
printf("\nCompleted the operation B \n");
atexit(functionB );
return(0);
}
Output:
Program 2
Aim: Write a Program to demonstrate the use of exit() and _exit() system call
Program :
i)use of exit():
#include<stdio.h>
#include<stdlib.h>
70 | P a g e
void func(){
printf("Exiting\n");
}
int main(){
atexit(func);
exit(10);
}
ii)use of _exit():
#include<stdio.h>
#include<stdlib.h>
void func(){
printf("Exiting\n");
}
int main(){
printf("Start of the Program\n");
atexit(func);
_Exit(10);
printf("End of the Program\n");
}
Output:
Exit():
_exit():
Program 3
Aim: Write a Program to demonstrate the use of wait() , waitpid() and waitid()
Program:
Wait() function:
#define _POSIX_SOURCE
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include<stdlib.h>
#include <time.h>
int main() {
pid_t pid;
time_t t;
71 | P a g e
int status;
if ((pid = fork()) < 0)
perror("fork() error");
else if (pid == 0) {
time(&t);
printf("child (pid %d) started at %s", (int) getpid(), ctime(&t));
sleep(5);
time(&t);
printf("child exiting at %s", ctime(&t));
exit(42);
}
else {
printf("parent has forked child with pid of %d\n", (int) pid);
time(&t);
printf("parent is starting wait at %s", ctime(&t));
if ((pid = wait(&status)) == -1)
perror("wait() error");
else {
time(&t);
printf("parent is done waiting at %s", ctime(&t));
printf("the pid of the process that ended was %d\n", (int) pid);
if (WIFEXITED(status))
printf("child exited with status of %d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("child was terminated by signal %d\n",
WTERMSIG(status));
else if (WIFSTOPPED(status))
printf("child was stopped by signal %d\n", WSTOPSIG(status));
else puts("reason unknown for child termination");
}
}
Output:
Waitpid() function:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int
72 | P a g e
main(int argc, char *argv[])
{
pid_t cpid, w;
int status;
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
}
}
Output:
Terminal 1
Terminal 2
73 | P a g e
Waitid() function:
#define pr_exit(n) printf("%d\n", n)
#define err_sys perror
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int status;
siginfo_t info;
err_sys("wait error");
pr_exit(status); /* and print its status */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) /* child */
abort(); /* generates SIGABRT */
if (waitid(P_PID,pid,&info,WEXITED) != pid) /* wait for child */
err_sys("wait error");
pr_exit(status); /* and print its status */
if ((pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) /* child */
status = 0; /* divide by 0 generates SIGFPE */
if (waitid(P_PID,pid,&info,WEXITED) != pid) /* wait for child */
74 | P a g e
err_sys("wait error");
pr_exit(status);
exit(0);
}
Output:
Program 4
Program:
Wait3() function:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
int
main(int argc, char *argv[])
{
pid_t cpid, w;
int status;
struct rusage Use;
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Code executed by child */
printf("Child PID is %ld\n", (long) getpid());
if (argc == 1)
pause(); /* Wait for signals */
_exit(atoi(argv[1]));
} else { /* Code executed by parent */
do {
w = wait3(&status, WUNTRACED | WCONTINUED, &Use);
if (w == -1) {
perror("waitpid");
exit(EXIT_FAILURE);
75 | P a g e
}
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
}
Output:
Terminal 1
Terminal 2
Wait4() function:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
int
main(int argc, char *argv[])
{
pid_t cpid, w;
int status;
76 | P a g e
struct rusage Use;
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (WIFEXITED(status)) {
printf("exited, status=%d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("killed by signal %d\n", WTERMSIG(status));
} else if (WIFSTOPPED(status)) {
printf("stopped by signal %d\n", WSTOPSIG(status));
} else if (WIFCONTINUED(status)) {
printf("continued\n");
}
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
}
}
Output:
Terminal 1
Teminal 2
77 | P a g e
Week – 7
PROCEDURE:
It is a banker algorithm used to avoid deadlock and allocate resources safely to each process in the
computer system. The 'S-State' examines all possible tests or activities before deciding whether the
allocation should be allowed to each process. It also helps the operating system to successfully share the
resources between all the processes. The banker's algorithm is named because it checks whether a
person should be sanctioned a loan amount or not to help the bank system safely simulate allocation
resources. For example, suppose the number of account holders in a particular bank is 'n', and the total
money in a bank is 'T'. If an account holder applies for a loan; first, the bank subtracts the loan amount
from full cash and then estimates the cash difference is greater than T to approve the loan amount.
These steps are taken because if another person applies for a loan or withdraws some amount from the
bank, it helps the bank manage and operate all things without any restriction in the functionality of the
banking system.
Similarly, it works in an operating system. When a new process is created in a computer system, the
process must provide all types of information to the operating system like upcoming processes, requests
for their resources, counting them, and delays. Based on these criteria, the operating system decides
which process sequence should be executed or waited so that no deadlock occurs in a system. Therefore,
it is also known as deadlock avoidance algorithm or deadlock detection in the operating system.
CODE:
#include <stdio.h>
int main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10];
int p, r, i, j, process, count;
count = 0;
printf("Enter the no of processes : ");
scanf("%d", &p);
for(i = 0; i< p; i++)
completed[i] = 0;
printf("\n\nEnter the no of resources : ");
scanf("%d", &r);
printf("\n\nEnter the Max Matrix for each process : ");
for(i = 0; i < p; i++)
78 | P a g e
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}
printf("\n\nEnter the allocation for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
for(i = 0; i < r; i++)
scanf("%d", &avail[i]);
for(i = 0; i < p; i++)
}
else
printf("\nThe system is in an unsafe state!!");
}
OUTPUT:
80 | P a g e
2. Demonstration of Bankers Algorithm for Deadlock Avoidance.
# Number of processes
P=5
# Number of resources
R=3
81 | P a g e
# Mark all processes as infinish
finish = [0] * P
found = True
82 | P a g e
if (found == False):
print("System is not in safe state")
return False
return True
# Driver code
if __name__ =="__main__":
processes = [0, 1, 2, 3, 4]
Output:
System is in safe state.
Safe sequence is: 1 3 4 0 2
83 | P a g e
Week – 8
1. WAP program to demonstrate the use of setuid(), setgid() system calls and sticky bit.
Ans.
AIM: A program to demonstrate the user of setuid(), setgid() and sticky bit system calls
PROCEDURE:
Setuid(): This bit is present for files which have executable permissions. The setuid bit simply indicates
that when running the executable, it will set its permissions to that of the user who created it (owner),
instead of setting it to the user who launched it. Similarly, there is a setgid bit which does the same for
the gid.
To locate the setuid, look for an ‘s’ instead of an ‘x’ in the executable bit of the file permissions.
Setgid(): The setgid affects both files as well as directories. When used on a file, it executes with the
privileges of the group of the user who owns it instead of executing with those of the group of the user
Who executed it.
When the bit is set for a directory, the set of files in that directory will have the same group as the group
of the parent directory, and not that of the user who created those files. This is used for file sharing since
they can be now modified by all the users who are part of the group of the parent directory.
To locate the setgid bit, look for an ‘s’ in the group section of the file permissions
Sticky bit: The sticky bit was initially introduced to ‘stick’ an executable program’s text segment in the
swap space even after the program has completed execution, to speed up the subsequent runs of the
same program. However, these days the sticky bit means something entirely different.
When a directory has the sticky bit set, its files can be deleted or renamed only by the file owner,
directory owner and the root user. Simply look for a ‘t’ character in the file permissions to locate the
sticky bit. The snippet below shows how we can set the sticky bit for some directory “Gatos”, and how
it prevents the new user from deleting a file in the directory.
CODE:
1. Setuid()
Setting a user set bit using ‘chmod u+s <filename’ command
Creating a new user and checking him in /etc/passwd (in users file)
84 | P a g e
Switching to other user and trying to modify the file which has the set bit turned on
2. Sticky bit
Creating a directory and making its sticky bit on by command ‘chmod +t <filename>’
3. Setgid()
Setting gid using command ‘chmod g+s <filename>’ and checking to modify from other user
85 | P a g e
2. WAP program to demonstrate the use of setuid(), setguid(), seteuid(), getgid(), geteuid(),
getegid()
Ans.
AIM: Program to demonstrate the use of setuid(), setgid(), seteuid(), getgid(), geteuid(), getegid()
PROCEDURE:
Setuid(): This bit is present for files which have executable permissions. The setuid bit simply indicates
that when running the executable, it will set its permissions to that of the user who created it (owner),
instead of setting it to the user who launched it. Similarly, there is a setgid bit which does the same for
the gid.
To locate the setuid, look for an ‘s’ instead of an ‘x’ in the executable bit of the file permissions.
Setgid(): The setgid affects both files as well as directories. When used on a file, it executes with the
privileges of the group of the user who owns it instead of executing with those of the group of the user
Who executed it.
When the bit is set for a directory, the set of files in that directory will have the same group as the group
of the parent directory, and not that of the user who created those files. This is used for file sharing since
they can be now modified by all the users who are part of the group of the parent directory.
To locate the setgid bit, look for an ‘s’ in the group section of the file permissions
Seteuid(): The process effective user ID is reset if the UID parameter is equal to either the current real
or saved user IDs or if the effective user ID of the process is the root user.
Getgid(): The getuid subroutine returns the real user ID of the current process.
Geteuid(): The geteuid subroutine returns the effective user ID of the current process.
Getegid(): The getegid subroutine returns the effective group ID of the current process.
CODE:
#include<stdio.h>
#include<unistd.h>
int main()
{
uid_t uid;
printf("Before setting the uid and gid\nreal user id: %d\nreal grp id: %d\neffective user id: %d\
neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());
setuid(1003);
setgid(1002);
printf("After setting the uid and gid\nreal user id: %d\nreal grp id: %d\neffective user id: %d\
neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());
86 | P a g e
return 0;
}
OUTPUT:
3. WAP to demonstrate the use of set setresuid(), setresgid(), setfsuid() and setfsgid()
Ans.
AIM: A program to demonstrate the use of setresuid(), setresgid(), setfsuid() and setfsgid()
PROCEDURE:
Setresuid(): setresuid() sets the real user ID, the effective user ID, and the saved set-user-ID of the
calling process. An unprivileged process may change its real UID, effective UID, and saved set-user-ID,
each to one of: the current real UID, the current effective UID, or the current saved set-user-ID
Setresgid(): setresgid() sets the real GID, effective GID, and saved set-group-ID of the calling process
(and always modifies the file system GID to be the same as the effective GID), with the same
restrictions for unprivileged processes.
Setfsuid(): The system call setfsuid() sets the user ID that the Linux kernel uses to check for all
accesses to the file system. Normally, the value of fsuid will shadow the value of the effective user ID.
In fact, whenever the effective user ID is changed, fsuid will also be changed to the new value of the
effective user ID.
Setfsgid(): The system call setfsgid() sets the group ID that the Linux kernel uses to check for all
accesses to the file system. Normally, the value of fsgid will shadow the value of the effective group ID.
In fact, whenever the effective group ID is changed, fsgid will also be changed to the new value of the
effective group ID.
CODE:
#include<stdio.h>
#include<unistd.h>
int main()
{
uid_t uid;
printf("Before setting the uid and gid\nreal user id: %d\nreal grp id: %d\neffective user id: %d\
neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());
setresuid(1001,1001,1001);
setresgid(1002,1002,1002);
printf("After using resuid and resgid\nreal user id: %d\nreal grp id: %d\neffective user id: %d\
neffective grp id: %d\n",getuid(),getgid(),geteuid(),getegid());
87 | P a g e
setfsuid(1001);
setfsgid(1002);
printf("After using fsuid and fsgid\nreal user id: %d\nreal grp id: %d\neffective user id:
OUTPUT:
used (in conjunction with the supplementary group IDs) to determine permissions when performing file-
system operations such as opening files, changing file ownership, and modifying file permissions.
Normally, the file-system user and group IDs have the same values as the corresponding effective IDs
(and thus typically are the same as the corresponding real IDs). Furthermore, whenever the effective
user or group ID is changed, either by a system call or by execution of a set-user-ID or set-group-ID
program, the corresponding file-system ID is also changed to the same value
89 | P a g e
90 | P a g e
Week – 10
91 | P a g e
5. WAP to demonstrate the SIGCHLD and SIGINT handling
AIM: A program to demonstrate the SIGCHLD and SIGINT handling
DESCRIPTION:
A signal is a software generated interrupt that is sent to a process by the OS because of when user press
ctrl-c or another process tell something to this process. There are fix set of signals that can be sent to a
process. signal are identified by integers. Signal number have symbolic names. For example SIGCHLD
is number of the signal sent to the parent process when child terminates.
CODE:
SIGINT handling:
#include<stdio.h>
#include<signal.h>
// Handler for SIGINT, caused by
// Ctrl-C at keyboard
void handle_sigint(int sig) // Signal Handler
{
printf("Caught signal %d\n", sig);
}
int main()
{
signal(SIGINT, handle_sigint); // Registering a Signal
while (1)
{
printf(“hello world\n”);
sleep(1);
}
return 0;
}
SIGCHLD handling:
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
// Handler for SIGINT, caused by
// Ctrl-C at keyboard
void handle_sigchild(int sig) // Signal Handler
{
printf("Inside child signal %d \n", sig);
//signal(SIGINT,SIG_DFL); //De registering Signal
}
int main()
{
signal(SIGCHLD, handle_sigchild); // Registering a Signal
int p=fork();
if(p==0)
{
printf("Inside Child process \n");
//
printf("End of child Process \n");
}
else if(p>=0)
92 | P a g e
{
printf("Inside parent process \n");
wait();
SIGCHLD:
a memory segment in the address space of several processes so that those processes can read and write
in that memory segment. Two functions:shmget() and shmat() are used for IPC using shared memory.
shmget() function is used to create the shared memory segment while shmat() function is used to attach
the shared segment with the address space of the process.
CODE:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/shm.h>
#include<string.h>
int main()
{
int i;
void *shared_memory;
char buff[100];
int shmid;
/*creates shared memory segment with key 2345, having size 1024 bytes. IPC_CREAT is used to create
the shared segment if it does not exist. 0666 are the permisions on the shared segment*/
OUTPUT:
94 | P a g e
a Program for Process Synchronization using Semaphores to understand the implementation of
sem_wait() and sem_signal() to avoid a race condition.
CODE:
#include<pthread.h>
#include<stdio.h>
#include<semaphore.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
sem_t s; //semaphore variable
int main()
{
sem_init(&s,0,1); //initialize semaphore variable - 1st argument is address of variable, 2nd is number of
processes sharing semaphore, 3rd argument is the initial value of semaphore variable
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last updated value of shared variable
}
void *fun1()
{
int x;
sem_wait(&s); //executes wait operation on s
x=shared;//thread1 reads value of shared variable
printf("Thread1 reads the value as %d\n",x);
x++; //thread1 increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread1 is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
sem_post(&s);
}
void *fun2()
{
int y;
sem_wait(&s);
y=shared;//thread2 reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread2 increments its value
printf("Local updation by Thread2: %d\n",y);
sleep(1); //thread2 is preempted by thread 1
shared=y; //thread2 updates the value of shared variable
printf("Value of shared variable updated by Thread2 is: %d\n",shared);
sem_post(&s);
}
OUTPUT:
95 | P a g e
8. WAP to demonstrate the use of Mutex – IPC
Ans.
AIM: A program to demonstrate the use of mutex - IPC
DESCRIPTION:
A situation where several processes access and manipulate the same data concurrently and the outcome
of the execution depends on the particular order in which the access takes place is called a race
condition. This Program uses threads to simulate race condition.
CODE:
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
int main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
96 | P a g e
y=shared;//thread two reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread two increments its value
blocking on full pipes. Message queues send blocks of data from one process to another. Each block of
data is considered to have a type. There is an upper limit on the maximum size of each block and also a
limit on the maximum total size of all blocks on all queues in the system.
CODE:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#define MAX_TEXT 512 //maximum length of the message that can be sent allowed
struct my_msg{
long int msg_type;
char some_text[MAX_TEXT];
};
int main()
{
int running=1;
int msgid;
struct my_msg some_data;
char buffer[50]; //array to store user input
msgid=msgget((key_t)14534,0666|IPC_CREAT);
97 | P a g e
if (msgid == -1) // -1 means the message queue is not created
{
printf("Error in creating queue\n");
exit(0);
}
while(running)
{
OUTPUT:
or on different systems as network sockets. Sockets allow communication between two different
processes on the same or different machines. To be more precise, it's a way to talk to other computers
using standard Unix file descriptors. In Unix, every I/O action is done by writing or reading a file
descriptor. A file descriptor is just an integer associated with an open file and it can be a network
connection, a text file, a terminal, or something else. A Unix Socket is used in a client-server application
framework. A server is a process that performs some functions on request from a client. Most of the
application-level protocols like FTP, SMTP, and POP3 make use of sockets to establish connection
between client and server and then for exchanging data.
CODE:
SOCKET:
#include <stdio.h>
#include <netdb.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
for (;;) {
bzero(buff, MAX);
// Driver function
int main()
{
int sockfd, connfd, len;
struct sockaddr_in servaddr, cli;
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h> // bzero()
#include <sys/socket.h>
#include <unistd.h> // read(), write(), close()
#define MAX 80
#define PORT 8080
#define SA struct sockaddr
void func(int sockfd)
{
char buff[MAX];
int n;
for (;;) {
bzero(buff, sizeof(buff));
printf("Enter the string : ");
n = 0;
while ((buff[n++] = getchar()) != '\n')
;
write(sockfd, buff, sizeof(buff));
bzero(buff, sizeof(buff));
read(sockfd, buff, sizeof(buff));
printf("From Server : %s", buff);
int main()
{
int sockfd, connfd;
struct sockaddr_in servaddr, cli;
!= 0) {
printf("connection with the server failed...\n");
exit(0);
}
else
printf("connected to the server..\n");
102 | P a g e