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

CS8461 - Oslabmanual - Process

This document outlines the syllabus for the CS8461 Operating Systems Laboratory course offered by the Department of Computer Science and Engineering at St. Joseph's Institute of Technology. The syllabus includes 16 experiments covering topics like UNIX commands, system calls, CPU scheduling algorithms, memory management, file organization techniques, and inter-process communication. It also lists the program outcomes, program educational objectives, and program specific outcomes for the course, which focus on developing skills in areas such as engineering problem solving, design, communication, lifelong learning, and applying knowledge across domains.

Uploaded by

sksharini67
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

CS8461 - Oslabmanual - Process

This document outlines the syllabus for the CS8461 Operating Systems Laboratory course offered by the Department of Computer Science and Engineering at St. Joseph's Institute of Technology. The syllabus includes 16 experiments covering topics like UNIX commands, system calls, CPU scheduling algorithms, memory management, file organization techniques, and inter-process communication. It also lists the program outcomes, program educational objectives, and program specific outcomes for the course, which focus on developing skills in areas such as engineering problem solving, design, communication, lifelong learning, and applying knowledge across domains.

Uploaded by

sksharini67
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 65

C8461-Operating systems Laboratory Department of CSE 2018-2019

INDEX
Name of Lab In-charge:
Ex. Date of
Date Name of the Experiment Staff Sign
No. Submission
1

2A

2B

4A

4B

4C

4D

5A

5B

5C

5D

10

11

12

13A

13B

13C

14A

14B

14C

15A

15B

15C

16

St. Joseph’s Institute of Technology 1


C8461-Operating systems Laboratory Department of CSE 2018-2019

CS8461 OPERATING SYSTEMS LABORATORY LTPC


0 0 4 2
SYLLABUS
1. Basics of UNIX commands
2. Write programs using the following system calls of UNIX operating system fork, exec,
getpid, exit, wait, close, stat, opendir, readdir
3. Write C programs to simulate UNIX commands like cp, ls, grep, etc.
4. Shell Programming
5. Write C programs to implement the various CPU Scheduling Algorithms
6. Implementation of Semaphores
7. Implementation of Shared memory and IPC
8. Bankers Algorithm for Deadlock Avoidance
9. Implementation of Deadlock Detection Algorithm
10. Write C program to implement Threading & Synchronization Applications
11. Implementation of the following Memory Allocation Methods for fixed partition a) First Fit
b) Worst Fit c) Best Fit
12. Implementation of Paging Technique of Memory Management
13. Implementation of the following Page Replacement Algorithms
a) FIFO b) LRU c) LFU
14. Implementation of the various File Organization Techniques
15. Implementation of the following File Allocation Strategies
a) Sequential b) Indexed c) Linked
TOTAL: 60 PERIODS

LIST OF EXPERIMENTS
EXP. NO. NAME OF THE EXPERIMENTS
1 BASICS OF UNIX COMMANDS
2A SYSTEM CALLS IMPLEMENTATION: FORK, EXEC, GETPID, EXIT, WAIT, CLOSE
2B SYSTEM CALLS IMPLEMENTATION: STAT, OPENDIR, READDIR
3 SIMULATE UNIX COMMANDS LIKE CP, LS, GREP
4A SUM OF FIRST ‘N’ NUMBERS
4B ODD OR EVEN NUMBER
4C FACTORIAL OF A NUMBER
4D STRING PALINDROME
5A FCFS SCHEDULING
5B SJF SCHEDULING
5C PRIORITY SCHEDULING
5D ROUND ROBIN SCHEDULING
6 PRODUCER CONSUMER PROBLEM USING SEMAPHORES
7 IMPLEMENT SHARED MEMORY AND IPC
8 IMPLEMENT BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE
9 IMPLEMENT AN ALGORITHM FOR DEAD LOCK DETECTION
10 IMPLEMENT THREADING & SYNCHRONIZATION APPLICATIONS
11 IMPLEMENT MEMORY ALLOCATION METHODS FOR FIXED PARTITION
12 IMPLEMENT PAGING TECHNIQUE OF MEMORY MANAGEMENT
13A FIFO PAGE REPLACEMENT ALGORITHM
13B LRU PAGE REPLACEMENT ALGORITHM
13C OPTIMAL(LFU) PAGE REPLACEMENT ALGORITHM
14A SINGLE LEVEL DIRECTORY
14B TWO LEVEL DIRECTORY
14C HIERARCHICAL DIRECTORY
15A SEQUENTIAL FILE ALLOCATION
15B INDEXED FILE ALLOCATION
15C LINKED FILE ALLOCATION
16 ADDITIONAL EXPERIMENTS: READER WRITER PROBLEM
(A) PROGRAM OUTCOMES(POs)

St. Joseph’s Institute of Technology 2


C8461-Operating systems Laboratory Department of CSE 2018-2019

Engineering graduates will be able to:


1. Engineering Knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
3. Design/development of solutions: Design solution for complex engineering problems and design sys-
tems components or process that meet the specified needs with appropriate consideration for the public
health and safety , and the cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research- based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineer-
ing and IT tools including prediction and modeling to complex engineering activities with an under-
standing of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
7. Environmental and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts and demonstrate the knowledge of, and need for sustainable devel-
opment.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in di-
verse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as , being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work , as a member and leader in a team, to man -
age projects and in multidisciplinary environments.
12. Life-Long learning: Recognize the need for, and have the preparation and ability to engage in inde-
pendent and life-long learning in the broadest context of technological change.

(B) PROGRAM EDUCATIONAL OBJECTIVES (PEOs)


The graduates will be
1. Knowledge competence: Fortified with mathematical foundation, algorithmic principles and designing
concepts to analyze and solve current problems in the field of computer science and engineering.
2. Professionalism and leadership: Equipped with logical and reasoning skills to communicate
effectively with a range of audience to accomplish common goal.
3. Global Engineer: Flourish to adapt and respond to new technologies and methodologies by innovating
ideas for betterment of the society.

(C) PROGRAM SPECIFIC OUTCOMES (PSOs)

PSO 1: Core Oriented - Proficient in the field of metalogic, hardware, software computing, to meet the
desired needs and to solve various problems.
PSO 2: Continuous improvement To sustain in transitional environment of computer science &
engineering to develop algorithms & projects using open source tools and efficient data structures
PSO 3: Intra – disciplinary - Apply Knowledge in different domains like data management science and
cognitive technologies.
PSO 4: Focusing growth - Exalt in innovative world by applying state –of-art methodologies with focus
on optimization and quality related activities.

CS8461 - OPERATING SYSTEMS LABORATORY


St. Joseph’s Institute of Technology 3
C8461-Operating systems Laboratory Department of CSE 2018-2019

COURSE OUTCOMES:
On completion of this lab course, the students will be able to
C217. Know and simulate UNIX commands for various operations, design and implement shell
1 programs, algorithms for CPU scheduling, file allocation and deadlock detection and avoidance
C217. Able to design and implement programs for inter process communication, shared memory, memory
2 allocation, paging techniques, threading and process synchronization

MAPPING BETWEEN CO AND PO, PSO WITH CORRELATION LEVEL 1/2/3

PO10

PO11

PO12

PSO

PSO

PSO

PSO
PO1

PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9
COs

4
C217.1 3 2 3 2 1 - - - 1 2 3 3 3 3 3 3
C217.2 3 2 3 2 2 - - - 2 3 3 3 3 3 3 3

RELATION BETWEEN COURSE CONTENT / EXPERIMENTS WITH CO

Knowledge Course
S.No Experiment
level Outcomes
Cycle – 1
1.
R Basics of various UNIX commands. C217.1
2. Write programs using the following system calls of UNIX operating
U & Ap system fork, exec, getpid, exit, wait, close, stat, opendir, readdir
C217.1
3. Write C programs to simulate UNIX commands like cp, ls, grep,
U & Ap etc.
C217.1
4.
R & Ap Shell Programming. C217.1
5. Implement the following CPU scheduling algorithms
U & Ap C217.1
a)Round Robin b) SJF c) FCFS d) Priority
6.
U & Ap Implement Producer consumer problem with Semaphores C217.2
7. Implement Shared memory and IPC
U & Ap C217.2
Cycle – 2
8.
U & Ap Implement Bankers Algorithm for Dead Lock Avoidance. C217.1
9.
U & Ap Implement an Algorithm for Dead Lock Detection C217.1
10.
U & Ap Implement Threading & Synchronization Applications C217.2
11. Implementation of the following Memory Allocation Meth-
U & Ap C217.2
ods for fixed partition a) First Fit b) Worst Fit c) Best Fit
12.
U & Ap Implement Paging Technique of memory management. C217.2
13. Implement all page replacement algorithms
U & Ap C217.2
a) FIFO b) LRU c) LFU
14.
U & Ap Implement all File Organization Techniques C217.2
15. Implement all file allocation strategies
U & Ap C217.2
a) Sequential b) Indexed c)Linked
16.
U Additional Experiments: Reader Writer Problem C217.2

R – Remember; Ap – Apply; An – Analyze; U – Understand, E- Evaluate, C-Create

Signature of the faculty :

1. 2. 3.

St. Joseph’s Institute of Technology 4


C8461-Operating systems Laboratory Department of CSE 2018-2019

Signature of the Scrutinizing Committee with changes needed:

1 2.

Signature of the HOD:

Ex No: 1 BASICS OF UNIX COMMANDS


Date:

AIM:
To study and execute basics of UNIX commands.

DIRECTORY COMMANDS

1.Create a directory
roo@sys5:~/Desktop$ mkdir cpl
roo@sys5:~/Desktop$

2. Change from one directory to another


roo@sys5:~/Desktop$ cd cpl
roo@sys5:~/Desktop$
roo@sys5:~/Desktop$ cd ..
roo@sys5:~/Desktop$

3. Display the full path of the current working directory


roo@sys5:~/Desktop$ pwd
/home/Desktop
roo@sys5:~/Desktop$

4. Remove a directory
roo@sys5:~/Desktop$ rmdir NewFolder
roo@sys5:~/Desktop$

FILE MANIPULATION COMMANDS

1. Create a file:
roo@sys5:~/Desktop$ cat>a.txt
Hi all
roo@sys5:~/Desktop$

2. Display the contents of a file onto screen:


roo@sys5:~/Desktop$ cat a.txt
Hi all
[roo@sys5:~/Desktop$$

3. List information about files and directories


roo@sys5:~/Desktop$ ls
a.txt b.txt hi.txt
roo@sys5:~/Desktop$

4. List all directories (including .(dot) entries in the long listing.)


roo@sys5:~/Desktop$ ls -a
. .. New Folder a.txt b.txt
roo@sys5:~/Desktop$

5. List all directories with access permission


St. Joseph’s Institute of Technology 5
C8461-Operating systems Laboratory Department of CSE 2018-2019

roo@sys5:~/Desktop$ ls -l
total 12
-rw-rw-r-- 1 user1 user1 21 Oct 13 2016 a.txt
-rw-rw-r-- 1 user1 user1 4 Oct 13 2016 b.txt
roo@sys5:~/Desktop$
6. Copy a file:
roo@sys5:~/Desktop$ cp a.txt c.txt
[roo@sys5:~/Desktop$

7.Move or rename a file:


roo@sys5:~/Desktop$ mv c.txt d.txt
roo@sys5:~/Desktop$ ls
a.txt b.txt d.txt s.txt
roo@sys5:~/Desktop$

8.Remove a file:
roo@sys5:~/Desktop$ rm d.txt
roo@sys5:~/Desktop$ ls
a.txt b.txt c.txt
roo@sys5:~/Desktop$

9. Change the access permission of a file:


roo@sys5:~/Desktop$ ls -l f1.txt
-rw-rw-r-- 1 user1 user1 20 Oct 13 12:30 f1.txt
roo@sys5:~/Desktop$ chmod 777 f1.txt
roo@sys5:~/Desktop$ ls -l f1.txt
-rwxrwxrwx 1 user1 user1 20 Oct 13 12:35 f1.txt
roo@sys5:~/Desktop$

10. Update the content of a file:


roo@sys5:~/Desktop$ cat>>a.txt
Good morning
roo@sys5:~/Desktop$ cat a.txt
Hi all
Good morning
roo@sys5:~/Desktop$

11. Number lines of files


roo@sys5:~/Desktop$ nl a.txt
1 Hi all
2 Good morning
roo@sys5:~/Desktop$

12. Extract specific fields


Remove sections from each line of files
roo@sys5:~/Desktop$ cut -c 4 a.txt
n
m
roo@sys5:~/Desktop$
roo@sys5:~/Desktop$ cut -c 4-6 a.txt
nam
m droo@sys5:~/Desktop$
13. tr command
roo@sys5:~/Desktop$ tr [:lower:] [:`upper:]
hi
HI
how are you
HOW ARE YOU
St. Joseph’s Institute of Technology 6
C8461-Operating systems Laboratory Department of CSE 2018-2019

roo@sys5:~/Desktop$ tr [:lower:] [:upper:] <a.txt


HI ALL
GOOD MORNING
roo@sys5:~/Desktop$

14. Word count command:


It is used to count the number of lines, words and characters in a file.
roo@sys5:~/Desktop$ wc a.txt
1 10 56 a.txt
roo@sys5:~/Desktop$ wc -l a.txt
1 a.txt
roo@sys5:~/Desktop$ wc -w a.txt
10 a.txt
roo@sys5:~/Desktop$ wc -c a.txt
56 a.txt
roo@sys5:~/Desktop$

15. Touch Command:


Update the access and modification times of each FILE to the current time.
roo@sys5:~/Desktop$ ls -l f1.txt
-rw-rw-r-- 1 user1 user1 20 Oct 13 12:30 f1.txt
roo@sys5:~/Desktop$ touch f1.txt
roo@sys5:~/Desktop$ ls -l f1.txt
-rw-rw-r-- 1 user1 user1 20 Oct 13 12:40 f1.txt
roo@sys5:~/Desktop$

SIMPLE UNIX COMMANDS:


1. Calendar Command:
roo@sys5:~/Desktop$ cal
October
Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
2. Date command:
roo@sys5:~/Desktop$ date
Thu Oct 13 12:34:41 IST 2016
roo@sys5:~/Desktop$ date +%a
Thu
roo@sys5:~/Desktop$ date +%A
Thursday
roo@sys5:~/Desktop$ date +%b
Oct
roo@sys5:~/Desktop$ date +%B
October
roo@sys5:~/Desktop$ date +%d
13

3. Who command:
Show who is logged on
roo@sys5:~/Desktop$ who
user1 pts/1 2016-10-13 14:02 (197.168.1.250)
roo@sys5:~/Desktop$

St. Joseph’s Institute of Technology 7


C8461-Operating systems Laboratory Department of CSE 2018-2019

4.Who am I command:
Print the user name associated with the current effective user ID.
roo@sys5:~/Desktop$ whoami
sys5
roo@sys5:~/Desktop$

5. Head Command:
Displays the initial part of the text file. By default, it displays the first 10 lines of a file.
roo@sys5:~/Desktop$ head -n 1 a.txt
my name is user1
roo@sys5:~/Desktop$

6. Tail command:
Displays the last part of the text file. By default, IT displays the last 10 lines of a file.
roo@sys5:~/Desktop$ tail -n 1 a.txt
i am doing computer programming lab.
roo@sys5:~/Desktop$

7. Help command:
To display the help information about a particular command.
roo@sys5:~/Desktop$ man chmod
CHMOD(1) User Commands CHMOD(1)

NAME
chmod - change file access permissions

SYNOPSIS
chmod [OPTION]... MODE[,MODE]... FILE...
chmod [OPTION]... OCTAL-MODE FILE...
chmod [OPTION]... --reference=RFILE FILE...

DESCRIPTION
This manual page documents the GNU version of chmod. chmod changes the permissions of
each given file according to mode, which can be either a symbolic representation of changes to
make, or an octal number repre- senting the bit pattern for the new permissions.

8. echo command:
Display a line of text.
roo@sys5:~/Desktop$ echo "i am a good boy"
i am a good boy
roo@sys5:~/Desktop$

9. bc command
Basic calculator
roo@sys5:~/Desktop$ bc
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
45+34
79
23-13
10

PIPES AND FILTERS

Pipes: A mechanism in which the output of one command is redirected as input to another command.
St. Joseph’s Institute of Technology 8
C8461-Operating systems Laboratory Department of CSE 2018-2019

Example 1: Count the number of lines in who command


roo@sys5:~/Desktop$ who | wc -l
1
roo@sys5:~/Desktop$
Example 2: Copy one file to another file using Pipe
roo@sys5:~/Desktop$ cat a.txt | cat>d.txt
roo@sys5:~/Desktop$ cat d.txt
my name is user1
i am doing computer programming lab.
roo@sys5:~/Desktop$

Grep filter:
It is used to search for a particular pattern from a file or from std. input.
roo@sys5:~/Desktop$ grep name a.txt
my name is user1
roo@sys5:~/Desktop$ grep am a.txt
my name is user1
i am doing computer programming lab.
roo@sys5:~/Desktop$
roo@sys5:~/Desktop$ grep -c am a.txt
2
roo@sys5:~/Desktop$

egrep command:

It is an extension for grep command Multiple Patterns can be searched in a file by issuing a
single command. These multiple patterns should be separated by a pipe ( | ) symbol.
roo@sys5:~/Desktop$ egrep "computer|is" a.txt
my name is user1
i am doing computer programming lab.roo@sys5:~/Desktop$

Usage of pipes and filters together:


An important use of grep using the “^”pattern is to list the directories.

roo@sys5:~/Desktop$ ls | grep "^s"


sam.txt
roo@sys5:~/Desktop$ ls | grep "^f"
a.txt
b.txt
c.txt
d.txt
roo@sys5:~/Desktop$

roo@sys5:~/Desktop$ ls | grep 't$'


a.txt
b.txt
c.txt
d.txt
sam.txt
roo@sys5:~/Desktop$

RESULT: Thus the basic UNIX commands are executed.

Viva Questions:
1. What is unix?
2. List some names of operating systems

St. Joseph’s Institute of Technology 9


C8461-Operating systems Laboratory Department of CSE 2018-2019

3. What is the use of filter/grep/pipe commands?


4. How is unix different from windows
5. Advantages of unix
6. What is the file structure of unix?

Exp No:2A SYSTEM CALLS IMPLEMENTATION:


FORK, EXEC, GETPID, EXIT, WAIT, CLOSE
Date:

AIM:
To write a program to create the hierarchy of Process using system calls of UNIX operating
system fork, exec, getpid, exit, wait, close.

ALGORITHM:
1. Create a process using fork() system call.
2. Create a hierarchy of the process using child address space.
3. Get the each process ID and Parent process ID using getpid() and getppid().
4. Terminate the process after the child process terminate using wait() system call

PROGRAM:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
main()
{
int p1,p2,p3,p4,p5,p7,s1,s2,s3;
p1=fork();
if(p1== -1)
exit(1);
if(p1==0)
{
p2=fork();
if(p2== -1)
exit(1);
if(p2==0)
{
printf("I'M P4.\n");
printf("PROCESS ID OF P4 IS:%d\n",getpid());
printf("PARENT PROCESS ID OF P4 IS:%d\n",getppid());
}
else
{
p3=fork();
if(p3==-1)
exit(1);
if(p3==0)
{
printf("I'M P5.\n");
printf("PROCESS ID OF P5 IS:%d\n",getpid());
printf("PARENT PROCESS ID OF P5 IS:%d\n",getppid());
}
else
St. Joseph’s Institute of Technology 10
C8461-Operating systems Laboratory Department of CSE 2018-2019

{
wait(&s2);
printf("I'M P2.\n");
printf("PROCESS ID OF P2 IS:%d\n",getpid());
printf("PARENT PROCESS ID OF P2 IS:%d\n",getppid());
}
}
}
else
{
p4=fork();
if(p4==-1)
exit(1);
if(p4==0)
{
p5=fork();
if(p5==-1)
exit(1);
if(p5==0)
{
printf("I'M P6.\n");
printf("PROCESS ID OF P6 IS:%d\n",getpid());
printf("PARENT PROCESS ID OF P6 IS:%d\n",getppid());
}
else
{
p7=fork();
if(p7==-1)
exit(1);
if(p7==0)
{
printf("I'M P7.\n");
printf("PROCESS ID OF P7 IS:%d\n",getpid());
printf("PARENT PROCESS ID OF P7 IS:%d\n",getppid());
}
else
{
wait(&s3);
printf("I'M P3.\n");
printf("PROCESS ID OF P3 IS:%d\n",getpid());
printf("PARENT PROCESS ID OF P3 IS:%d\n",getppid());
}
}
}
else
{
wait(&s1);
printf("PROCESS ID OF P1 IS:%d\n",getpid());
}
}
}

OUTPUT:
[m1@cselab14 18-19]$ cc 2a.c
[m1@cselab14 18-19]$ ./a.out
I'M P4.
PROCESS ID OF P4 IS:7239

St. Joseph’s Institute of Technology 11


C8461-Operating systems Laboratory Department of CSE 2018-2019

I'M P6.
PARENT PROCESS ID OF P4 IS:7237
PROCESS ID OF P6 IS:7240
PARENT PROCESS ID OF P6 IS:7238
I'M P5.
I'M P7.
PROCESS ID OF P5 IS:7241
PROCESS ID OF P7 IS:7242
PARENT PROCESS ID OF P5 IS:7237
I'M P2.
PARENT PROCESS ID OF P7 IS:7238
I'M P3.
PROCESS ID OF P2 IS:7237
PARENT PROCESS ID OF P2 IS:7236
PROCESS ID OF P3 IS:7238
PARENT PROCESS ID OF P3 IS:7236
PROCESS ID OF P1 IS:7236

RESULT: Thus the program to create the hierarchy of Process using system calls of UNIX
operating system fork, exec, getpid, exit, wait, close was written, executed and the output was
verified.

Exp No: 2B SYSTEM CALLS IMPLEMENTATION:


STAT, OPENDIR, READDIR
Date:

AIM:
To write a program using system calls of UNIX operating system stat, opendir, readdir.

ALGORITHM:
1. Read the arguments from command line
2. Check the command line arguments are valid or not
3. If valid, open the directory using opendir system call
4. Display the files of the opened directory using readdir system call
5. If the files are a directory open this directory and read their files and display.

PROGRAM:
#include <sys/types.h>
#include <dirent.h>
#include<stdio.h>
#include<sys/stat.h>
#include <unistd.h>
#include<pwd.h>
#include<grp.h>
#include<stdio.h>
#include<ctype.h>
#include <linux/unistd.h>

void display(struct stat *sp,struct dirent *p1);


main(int argv,char **cmdline)
{
DIR *dir;
char *t;
struct dirent *dirp;
char dname[10],ddname[10];

St. Joseph’s Institute of Technology 12


C8461-Operating systems Laboratory Department of CSE 2018-2019

DIR *p;
struct dirent *p1;
struct stat buf;
p=opendir(".");
if(argv==1)
{
p1=readdir(p);
while(p1!=NULL)
{
if(strcmp(p1->d_name,".")==0 || strcmp(p1->d_name,"..")==0)
{
p1=readdir(p);
continue;
}
printf("%s\t",p1->d_name);
p1=readdir(p);
}
printf("\n");
}
else if(argv==2 && strcmp(cmdline[1],"-R")==0)
{
dir=opendir(".");
dirp=readdir(dir);
while(dirp!=NULL)
{
strcpy(dname,dirp->d_name);
printf("\t");
printf("%s\n",dirp->d_name);
dirp=readdir(dir);

}
}
}

OUTPUT:
[m1@cselab14 18-19]$ cc 2b.c
[m1@cselab14 18-19]$ ./a.out
cs6341_oslabmanual.docx CS8461_oslabmanual - Process.docx CS8461_oslabmanual.docx
CS8461_oslabmanual.pdf desktop.ini OS Ex1 & 2.docx os copy.c ls.c
2b.c grep.c Output 2 3~ 2a.c Output 2 3 a.out

[m1@cselab14 18-19]$ ./a.out -R


.
..
cs6341_oslabmanual.docx
CS8461_oslabmanual - Process.docx

RESULT: Thus the program using system calls of UNIX operating system stat, opendir, readdir was
written, executed and the output was verified.

Viva questions:
1. Describe the term directory in UNIX?
2. Describe fork() system call?
St. Joseph’s Institute of Technology 13
C8461-Operating systems Laboratory Department of CSE 2018-2019

3. What is the use of wait() system call?


4. What is the getpid() and getppi()
5. What is command line argument

Ex.No.3 SIMULATE UNIX COMMANDS LIKE CP, LS, GREP


Date

AIM:
To Write C programs to simulate UNIX commands like cp, ls, grep, etc.

ALGORITHM:
1. Start the program.
2. Get the command as the command line arguments and check for the syntax of the command.
3. Check for the existence of the directory/file mentioned in the command.
4. Open the directory/file if exists.
5. Perform the necessary operation based on the command.
6. Close the directory/file.
PROGRAM:
//To cp command
#include<sys/stat.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<stdio.h>
#include<fcntl.h>
main(int argc,char **argv)
{
int f1,f2;
ssize_t s1,s2;
size_t count=sizeof(char);
char c;
f1=open(argv[1],O_RDONLY);
f2=open(argv[2],O_WRONLY|O_CREAT);
if(f1==-1)
printf("%s File does not exist\n",argv[1]);
else
{
while(s1!=0)
{
s2=write(f2,&c,count);
s1=read(f1,&c,count);
}
close(f1);
close(f2);
}
}

OUTPUT:

[m1@cselab14 18-19]$ cc copy.c


[m1@cselab14 18-19]$ ./a.out copy.c move.c

St. Joseph’s Institute of Technology 14


C8461-Operating systems Laboratory Department of CSE 2018-2019

PROGRAM:
//To simulate ls command
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<sys/types.h>
#include<dirent.h>
#include<sys/stat.h>
#include<unistd.h>
#include <linux/unistd.h>

main(int argc,char **argv)


{
DIR *dir;
unsigned int fd,count;
int i,flag1;
char *t;
struct dirent *dirp;
struct stat buf;
char dname[10],ddname[10];
if(argc==1)
{
dir=opendir(".");
dirp=readdir(dir);
while(dirp!=NULL)
{
printf("%s\t",dirp->d_name);
dirp=readdir(dir);
}
printf("\n");
}
}

OUTPUT:

[m1@cselab14 18-19]$ cc ls.c


[m1@cselab14 18-19]$ ./a.out
. .. cs6341_oslabmanual.docx CS8461_oslabmanual - Process.docx
CS8461_oslabmanual.docx CS8461_oslabmanual.pdf desktop.ini OS Ex1 &
2.docxos copy.c ls.c 2b.c grep.c Output 2 3~ 2a.c Output 2 3 a.out
move.c
[m1@cselab14 18-19]$

//To simulate grep Command

#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>

int strmatch(char *buf,char *pat)


{
int n=strlen(buf),i,j,flag=0;
St. Joseph’s Institute of Technology 15
C8461-Operating systems Laboratory Department of CSE 2018-2019

int m=strlen(pat);
if(m>n) return 0;
for(i=0;i<n-m;i++)
{
j=0;
while(j<m && buf[i+j]==pat[j])
j++;
if(j==m) flag=1;
}
if(flag==1)
return 1;
else
return 0;
}

main(int argc,char **argv)


{
int f,i;
ssize_t sz;
size_t count=sizeof(char);
char c,buf[50];
if(strcmp(argv[1],"-a")!=0)
{
printf("Wrong option\n");
exit(1);
}
f=open(argv[3],O_RDONLY);
if(f==-1)
printf("%s file is not found\n",argv[3]);
else
{
do
{
i=0;
sz=read(f,&c,count);
while(c!='\n' && sz!=0)
{
buf[i++]=c;
sz=read(f,&c,count);
}
buf[i]='\0';
if(strmatch(buf,argv[2]))
printf("%s\n",buf);
}
while(sz!=0);
}
}

OUTPUT:

[m1@cselab14 18-19]$ cc grep.c


[m1@cselab14 18-19]$ ./a.out -a Wrong grep.c
printf("Wrong option\n");

RESULT: Thus the C programs to simulate UNIX commands like cp, ls, grep was written,
executed and the output was verified.

Viva questions:
St. Joseph’s Institute of Technology 16
C8461-Operating systems Laboratory Department of CSE 2018-2019

1. What is the use of unix commands?


2. Define grep command
3. What the modes of opening the file?
4. Difference between open and opendir system call
5. What is the use of the read system call?

Exp No:4A SUM OF FIRST ‘N’ NUMBERS


Date:

AIM:
To write a shell program to find the sum of n numbers.

ALGORITHM:
1. Get the number up to which the sum has to be calculated.
2. Initialize sum=0 and starting number i =1
3. While i less than or equal to n, do the following :
sum=sum+i

i=i+1 (Increment to the next number)

4. Display the sum.


5. Stop.

PROGRAM:
echo "SUM OF FIRST N NATURAL NUMBERS"
echo "ENTER THE LIMT N:"
read n
i=1
sum=0
while((i<=n))
do
((sum=sum+i))
((i=i+1))
done
echo "Sum: $sum"

OUTPUT:
roo@sys5:~/Desktop$ sh pgm2a.sh
SUM OF FIRST N NATURAL NUMBERS
ENTER THE LIMIT 5
SUM: 15

St. Joseph’s Institute of Technology 17


C8461-Operating systems Laboratory Department of CSE 2018-2019

RESULT: Thus the shell program for calculating sum of N numbers was written, executed
and the output was verified.
Exp No: 4B ODD OR EVEN NUMBER
Date:

AIM:
To write a shell program to check whether the given number is odd or even.

ALGORITHM:
Step1: Get the number.
Step2: Divide the number by 2.
Step3: If the remainder is equal to 0, then the number is even.
Step4: Else, the number is odd.
Step5: Stop.

PROGRAM:
echo "ODD OR EVEN"
echo "ENTER A NUMBER:"
read n
if((n%2==0))
then
echo "EVEN"
else
echo "ODD"
fi

OUTPUT:
roo@sys5:~/Desktop$ sh pgm2a.sh
ODD OR EVEN-ENTER A NUMBER:
2
EVEN
roo@sys5:~/Desktop$ sh pgm2a.sh
ODD OR EVEN
ENTER A NUMBER:15 ODD

St. Joseph’s Institute of Technology 18


C8461-Operating systems Laboratory Department of CSE 2018-2019

RESULT: Thus the shell program to check whether the given number is odd or even was
written, executed and the output was verified.
Ex.No.4C FACTORIAL OF A NUMBER
Date

AIM:
To write a shell program to find the factorial of a number.

ALGORITHM:
1. Get the number for which factorial has to be calculated as n.
2. Initialize fact =1
3. While n less than 0, do the following :
fact=fact*n

n=n-1

4. Display the factorial.


5. Stop.

PROGRAM:
echo "Enter the number"
read n
((fact=1))
while (($n > 0))
do
((fact=fact*n))
((n=n-1))
done
echo "The factorial of the number is:$fact"

OUTPUT:
Enter the number
6
The factorial of the number is:720

St. Joseph’s Institute of Technology 19


C8461-Operating systems Laboratory Department of CSE 2018-2019

RESULT: Thus the shell program for finding the factorial of a number was written, executed
and the output was verified.
Ex.No.4D STRING PALINDROME
Date:

AIM:
To write a shell program to check whether the given string is a palindrome or not.

ALGORITHM:
1. Input string
2. Calculate length of string .
3. Run a loop i=0 to len/2 of string
4. Compare ith character with len th character
5. If character doesn’t matches within loop then exit saying that it’s not a palindrome
6. If loop is successfully executed print that string is palindrome.

PROGRAM:
echo "enter a string"
read str
rev=`expr $str|rev`
if [ $rev = $str ]
then
echo "the given string is palindrome"
else
echo "the given string is not palindrome"
fi
OUTPUT:
enter a string
Madam
the given string is palindrome

RESULT: Thus the shell program for checking whether the given string is palindrome or not
was written, executed and the output was verified.

St. Joseph’s Institute of Technology 20


C8461-Operating systems Laboratory Department of CSE 2018-2019

Viva Questions:
1. What is meant by unix shell?
2. What is a shell script?
3. What are the operations performed via shell scripts?
4. What are the advantages and disadvantages of shell scripts?
5. Write syntax for “for loop” in shell script

Ex No: 5A IMPLEMENTATION OF FCFS SCHEDULING


Date:
AIM:
To write a ‘C’ program to implement FCFS Scheduling.

ALGORITHM:
Step 1: Include the header files for simulating FCFS scheme.
Step 2: Declare the variables to calculate the essential aspects of FCFS.
Step 3: Initially get the process time, arrival time and burst time.
Step 4: Swap all the processes in such a way that they are arranged in FCFS order.
Step 5: Prepare the gantt chart for each process so that their waiting time, turn around time is
calculated.
Step 6: Calculate the average waiting time and average turn around time and display the result.

PROGRAM:
#include<stdio.h>
#include<stdio.h>
#include<stdlib.h>
void main()
{
int i,n,br[10],wt[10],tr[10],ttr=0,twt=0;
float awat,atur;
printf("Enter no. of process :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the burst time for process %d: ",(i+1));
scanf("%d",&br[i]);
}
printf("\nPROCESS\tBURST TIME\tWAITING TIME\tTURN AROUND TIME\n");
wt[0]=0;
for(i=0;i<n;i++)
{
wt[i+1]=wt[i]+br[i];
tr[i]=wt[i]+br[i];
printf("\n%d\t\t%d\t\t%d\t\t%d\n",i+1,br[i],wt[i],tr[i]);
}
for(i=0;i<n;i++)
{
ttr=ttr+tr[i];
twt=twt+wt[i];
}
printf("\nGAANT CHART\n\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<n;i++)
St. Joseph’s Institute of Technology 21
C8461-Operating systems Laboratory Department of CSE 2018-2019

{
printf(" P%d |",i+1);
}
printf("\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<=n;i++)
{
printf("%d\t",wt[i]);
}
awat=(float)twt/n;
atur=(float)ttr/n;
printf("\n\nTotal waiting time :%d",twt);
printf("\nTotal turn around time :%d",ttr);
printf("\n\nAverage waiting time :%.2f",awat);
printf("\nAverage turn around time :%.2f\n",atur);
}

OUTPUT
[admin@csk Desktop]$ cc 3a.c
[admin@csk Desktop]$ ./a.out
Enter no. of process :3
Enter the burst time for process 1: 4
Enter the burst time for process 2: 2
Enter the burst time for process 3: 1
PROCESS BURST TIME WAITING TIME TURN AROUND TIME
1 4 0 4
2 2 4 6
3 1 6 7
GAANT CHART
------------------------
P1 | P2 | P3 |
------------------------
0 4 6 7
Total waiting time :10
Total turn around time :17
Average waiting time :3.33
Average turn around time :5.67

RESULT: Thus the FCFS scheduling algorithm was written, executed and the output was verified.

St. Joseph’s Institute of Technology 22


C8461-Operating systems Laboratory Department of CSE 2018-2019

Ex No: 5B IMPLEMENTATION OF SJF SCHEDULING


Date:
AIM:
To write a ‘C’ program to implement SJF Scheduling.

ALGORITHM:
Step 1: Include the header files for simulating SJF scheme.
Step 2: Declare the variables to calculate the essential aspects of SJF.
Step 3: Initially get the process time and burst time.
Step 4: Swap all the processes in such a way that they are arranged in shortest job first (SJF) order.
Step 5: Prepare the gantt chart for each process so that their waiting time, turn around time is
calculated.
Step 6: Calculate the average waiting time and average turn around time and display the result.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
main()
{
int i,j,k,n,p[10],br[10],wt[10],tr[10],ttr=0,twt=0,t;
float awat,atur;
printf("\nEnter no. of process :");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\nEnter the burst time for process %d: ",(i+1));
scanf("%d",&br[i]);
p[i]=i+1;}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(br[i]>br[j]){
t=br[i];
br[i]=br[j];
br[j]=t;
t=p[i];
p[i]=p[j];
p[j]=t;}}}
printf("\nPROCESS\tBURST TIME \t WAITING TIME \t TURN AROUND TIME\n");
wt[0]=0;
for(i=0;i<n;i++){
wt[i+1]=wt[i]+br[i];
tr[i]=wt[i]+br[i];}
for(i=0;i<n;i++){
ttr=ttr+tr[i];
twt=twt+wt[i];}
for(i=0;i<n;i++){
printf("\n%d\t\t%d\t\t%d\t\t%d\n",p[i],br[i],wt[i],tr[i]);}
printf("\nGAANT CHART\n\n");
for(i=0;i<n;i++){
printf("--------");}
printf("\n");
for(i=0;i<n;i++)
St. Joseph’s Institute of Technology 23
C8461-Operating systems Laboratory Department of CSE 2018-2019

{
printf(" P%d |",p[i]);
}
printf("\n");
for(i=0;i<n;i++)
{
printf("--------");
}
printf("\n");
for(i=0;i<=n;i++)
{
printf("%d\t",wt[i]);
}
awat=(float)twt/n;
atur=(float)ttr/n;
printf("\nTotal waiting time :%d\n",twt);
printf("\nTotal turnaround time :%d\n",ttr);
printf("\nAverage waiting time :%.2f\n",awat);
printf("\nAverage turn around time :%.2f\n",atur);
}
OUTPUT
[admin@csk Desktop]$ cc 3b.c
[admin@csk Desktop]$ ./a.out
Enter no. of process :3
Enter the burst time for process 1: 6
Enter the burst time for process 2: 3
Enter the burst time for process 3: 2
PROCESS BURST TIME WAITING TIME TURN AROUND TIME
3 2 0 2
2 3 2 5
1 6 5 11
GAANT CHART
------------------------
P3 | P2 | P1 |
------------------------
0 2 5 11
Total waiting time :7
Total turnaround time :18
Average waiting time :2.33
Average turn around time :6.00
[admin@csk Desktop]$
RESULT: Thus the C program for SJF scheduling was successfully executed and the output
was verified.

St. Joseph’s Institute of Technology 24


C8461-Operating systems Laboratory Department of CSE 2018-2019

Ex No: 5C IMPLEMENTATION OF PRIORITY SCHEDULING


Date:
AIM:
To write a ‘C’ program to implement PRIORITY Scheduling.

ALGORITHM:
Step 1: Include the header files for simulating priority scheme.
Step 2: Declare the variables to calculate the essential aspects of priority scheme.
Step 3: Initially get the process time, arrival time and burst time along with their priorities.
Step 4: Execute the process by referring to their priority values.
Step 5: Prepare the gantt chart for each process so that their waiting time, turn around time is
calculated.
Step 6: Calculate the average waiting time and average turn around time and display the result.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
main(){
int i,j,k,n,p[10],pri[10],bur[10],wat[10], tur[10],ttur=0,twat=0,t;
float awat,atur;
printf("\nEnter no. of process :");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("\nEnter the burst time for process %d: ",(i+1));
scanf("%d",&bur[i]);
p[i]=i+1;}
for(i=0;i<n;i++){
printf("\nEnter the priority for process %d: ",(i+1));
scanf("%d",&pri[i]);}
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(pri[i]>pri[j]){
t=bur[i];
bur[i]=bur[j];
bur[j]=t;
t=p[i];
p[i]=p[j];
p[j]=t;
t=pri[i];
pri[i]=pri[j];
pri[j]=t;}}}
printf("\nPROCESS\tBURST TIME \t PRIORITY \t WAITING TIME \tTURNAROUND TIME\n");
wat[0]=0;
for(i=0;i<n;i++){
wat[i+1]=wat[i]+bur[i];
tur[i]=wat[i]+bur[i];}
for(i=0;i<n;i++){
ttur=ttur+tur[i];
twat=twat+wat[i];}
for(i=0;i<n;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d\n",p[i],bur[i],pri[i],wat[i],tur[i]);
printf("\nGAANT CHART\n\n");
St. Joseph’s Institute of Technology 25
C8461-Operating systems Laboratory Department of CSE 2018-2019

for(i=0;i<n;i++)
printf("--------");
printf("\n");
for(i=0;i<n;i++)
printf(" P%d |",p[i]);
printf("\n");
for(i=0;i<n;i++)
printf("--------");
printf("\n");
for(i=0;i<=n;i++)
printf("%d\t",wat[i]);
awat=(float)twat/n;
atur=(float)ttur/n;
printf("\nTotal waiting time :%d\n",twat);
printf("\nTotal turnaround time :%d\n",ttur);
printf("\nAverage waiting time :%.2f\n",awat);
printf("\nAverage turn around time :%.2f\n",atur);
}
OUTPUT
[admin@csk Desktop]$ cc 3c.c
[admin@csk Desktop]$ ./a.out
Enter no. of process :3
Enter the burst time for process 1: 3
Enter the burst time for process 2: 1
Enter the burst time for process 3: 4
Enter the priority for process 1: 3
Enter the priority for process 2: 2
Enter the priority for process 3: 1
PROCESS BURST TIME PRIORITY WAITING TIME TURNAROUND TIME
3 4 1 0 4
2 1 2 4 5
1 3 3 5 8
GAANT CHART
------------------------
P3 | P2 | P1 |
------------------------
0 4 5 8
Total waiting time :9
Total turnaround time :17
Average waiting time :3.00
Average turn around time :5.67

St. Joseph’s Institute of Technology 26


C8461-Operating systems Laboratory Department of CSE 2018-2019

RESULT:
Thus the C program for Priority scheduling was executed successfully.
Ex No: 5D IMPLEMENTATION OF ROUND ROBIN SCHEDULING
Date:
AIM:
To write a ‘C’ program to implement ROUND ROBIN Scheduling.

ALGORITHM:
Step 1: Include the header files for simulating ROUND ROBIN scheduling scheme.
Step 2: Declare the variables to calculate the essential aspects of ROUND ROBIN.
Step 3: Initially get the time slice along with process time and burst time.
Step 4: Start from the 1st process and execute it for the given time slice and move to 2 nd process and
so on till all process gets executed for each of the time slice allotted.
Step 5: Prepare the gantt chart for each process getting executed within the time slice in a round robin
fashion.
Step 6: Calculate the waiting time and turn around time along with their averages display the result.

PROGRAM:
#include<stdio.h>
#include<stdlib.h>
main()
{
int i,x=-1,k[10],m=0,n,t,s=0;
int a[50],temp,b[50],p[10],bur[10],bur1[10];
int wat[10],tur[10],ttur=0,twat=0,tres=0,j=0;
float awat,atur,ares;
printf("Enter no. of process :");
scanf("%d",&n);
for(i=0;i<n;i++){
printf("Enter the burst time for process %d: ",(i+1));
scanf("%d",&bur[i]);
bur1[i]=bur[i];}
printf("\nEnter the slicing time :");
scanf("%d",&t);
for(i=0;i<n;i++){
b[i]=bur[i]/t;
if((bur[i]%t)!=0)
b[i]=b[i]+1;
m=b[i]+m;}
printf("\nGAANT CHART\n\n");
for(i=0;i<m;i++)
printf("--------");
printf("\n");
a[0]=0;
while(j<m){
if(x==n-1)
x=0;
else
x++;
if(bur[x]>=t){
bur[x]=bur[x]-t;
a[j+1]=a[j]+t;
if(b[x]==1){
St. Joseph’s Institute of Technology 27
C8461-Operating systems Laboratory Department of CSE 2018-2019

p[s]=x;
k[s]=a[j+1];
s++;}
j++;
b[x]=b[x]-1;
printf(" P%d |",x+1);}
else if(bur[x]!=0){
a[j+1]=a[j]+bur[x];
bur[x]=0;
if(b[x]==1){
p[s]=x;
k[s]=a[j+1];
s++;}
j++;
b[x]=b[x]-1;
printf(" P%d |",x+1);}}
printf("\n");
for(i=0;i<m;i++)
printf("--------");
printf("\n");
for(j=0;j<=m;j++)
printf("%d\t",a[j]);
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
if(p[i]>p[j]){
temp=p[i];
p[i]=p[j];
p[j]=temp;
temp=k[i];
k[i]=k[j];
k[j]=temp;}}}
for(i=0;i<n;i++)
{
wat[i]=k[i]-bur1[i];
tur[i]=k[i];
}
printf("\nPROCESS\tBURST TIME \t WAITING TIME \t TURN AROUND TIME\t");
printf("RESPONSE TIME\n");
for(i=0;i<n;i++)
{
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d\n",p[i]+1,bur1[i],wat[i],
tur[i],a[i]);
}
for(i=0;i<n;i++)
{
ttur=ttur+tur[i];
twat=twat+wat[i];
tres=tres+a[i];
}
awat=(float)twat/n;
atur=(float)ttur/n;
ares=(float)tres/n;
printf("\nTotal waiting time:%d",twat);
printf("\nTotal turnaround time:%d",ttur);
printf("\nTotal response time:%d",tres);
printf("\nAverage waiting time :%.2f",awat);
printf("\nAverage turn around time :%.2f",atur);
printf("\nAverage response time:%.2f",ares);
St. Joseph’s Institute of Technology 28
C8461-Operating systems Laboratory Department of CSE 2018-2019

OUTPUT
[admin@csk Desktop]$ cc 3d.c
[admin@csk Desktop]$ ./a.out
Enter no. of process :3
Enter the burst time for process 1: 4
Enter the burst time for process 2: 3
Enter the burst time for process 3: 2
Enter the slicing time :2
GAANT CHART
----------------------------------------
P1 | P2 | P3 | P1 | P2 |
----------------------------------------
0 2 4 6 8 9
PROCESS BURST TIME WAITING TIME TURN AROUND TIME RESPONSE
TIME
1 4 4 8 0
2 3 6 9 2
3 2 4 6 4
Total waiting time:14
Total turnaround time:23
Total response time:6
Average waiting time :4.67
Average turn around time :7.67

RESULT:
Thus the C program for round robin scheduling was executed and output was verified
successfully.
Viva Questions:
St. Joseph’s Institute of Technology 29
C8461-Operating systems Laboratory Department of CSE 2018-2019

1. Define process.
2. What are the other scheduling algorithms?
3. Advantage of Round Robin scheduling?
4. What is meant by response time and slice time?
5. What is meant by burst time, waiting time and turn around time?
Ex No: 6 PRODUCER CONSUMER PROBLEM USING SEMAPHORES

Date:
AIM:
To write a program to implement producer consumer problem using semaphore

ALGORITHM:
Step 1: Declare the buffer size variable.
Step 2: Initialize empty, full and the value of mutex.
Step 3: For case 1 , produce the item till the buffer is full after performing the wait operation
of variables empty and mutex.
Step 4: Then perform signal of full.
Step 5: For case 2, consume the item till the buffer is empty. Perform the wait and signal operation..
Step 6: print the contents of the buffer.

PROGRAM:
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define SIZE 3
struct process{
char a[10];
}buffer[SIZE];
int mutex=1,full=0,empty=SIZE,f=0;
int main()
{
int ch,i;
printf("\tProducer Consumer Problem:\n");
while(1){
printf("\n The choices are\n");
printf("1.Producer Routine\n2.Consumer Routine\n3.Buffer Contents\n4.Exit\n");
printf("Enter your Choice:");
scanf("%d",&ch);
switch(ch){
case 1:
empty=wait(empty);
mutex=wait(mutex);
if(f==0){
printf("\nEnter the item to be added:\n");
scanf("%s",&buffer[full]);
full=signal(full);printf("\nItem Produced Successfully:\n");}
else{
printf("\nBuffer is full\n");
f=0;}
mutex=signal(mutex);
break;
case 2:
full=wait(full);
mutex=wait(mutex);
if(f==0){
printf("\nOne Item is Consumed:\n");
St. Joseph’s Institute of Technology 30
C8461-Operating systems Laboratory Department of CSE 2018-2019

printf("\nConsumed item is: %s\n",buffer[0].a);


for(i=0;i<SIZE;i++)
strcpy(buffer[i].a,buffer[i+1].a);
empty=signal(empty);}
else {
printf("\nBuffer is empty\n");
f=0;}
mutex=signal(mutex);
break;
case 3:
if(full!=0){
for(i=0;i<full;i++)
printf("\n%s\n",buffer[i].a);}
else
printf("\nBuffer is empty\n");
break;
case 4:
exit(1);
default:
printf("Enter Correct Option");
break;}}}
int wait(int s){
if(s==0)
f=1;
else
s--;
return s;}
int signal(int s){
s++;
return s;}

OUTPUT
[admin@csk Desktop]$ cc 5.c
[admin@csk Desktop]$ ./a.out
Producer Consumer Problem:
The choices are
1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:1
Enter the item to be added:
item1
Item Produced Successfully:
The choices are
1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:1
Enter the item to be added:
item2
Item Produced Successfully:

The choices are


St. Joseph’s Institute of Technology 31
C8461-Operating systems Laboratory Department of CSE 2018-2019

1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:1
Enter the item to be added:
item3
Item Produced Successfully:

The choices are


1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:3
item1
item2
item3

The choices are


1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:1
Buffer is full

The choices are


1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:2
One Item is Consumed:
Consumed item is: item1

The choices are


1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:2
One Item is Consumed:
Consumed item is: item2

The choices are


1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:2
St. Joseph’s Institute of Technology 32
C8461-Operating systems Laboratory Department of CSE 2018-2019

One Item is Consumed:


Consumed item is: item3

The choices are


1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:2
Buffer is empty

The choices are


1.Producer Routine
2.Consumer Routine
3.Buffer Contents
4.Exit
Enter your Choice:4
[admin@csk Desktop]$

RESULT: Thus the C program for producer consumer problem using semaphores was
executed successfully and the output was verified.
Viva Questions:

1. What is semaphore?
2. Define synchronization. What is the purpose of synchronization?
3. What are the types of semaphores?
4. What are the operations on the semaphore?
5. Define busy waiting, spin lock.

St. Joseph’s Institute of Technology 33


C8461-Operating systems Laboratory Department of CSE 2018-2019

Ex No: 7 IMPLEMENT SHARED MEMORY AND IPC


Date:

AIM:
To write a program to implement inter process communication and shared memory to print
alphabets from a to z.

ALGORITHM:
Step 1: Create and shared memory using shmget.
Step 2: Attach pointer to a memory using shmat.
Step 3: Create child process to write data to memory.
Step 4: Print the shared memory data using server process.
Step 5: Stop the execution.

PROGRAM
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#define SHMSZ 27
main()
{
char c;
int shmid,childpid;
key_t key;
char *shm, *s;
key = 5679;
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
perror("shmget");
exit(1);}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);}
s = shm;
// error occured
if((childpid = fork()) < 0) {
perror("Fork Failed");
exit(1);}
// child process
else if(childpid == 0) {
for (c = 'a'; c <= 'z'; c++)
*s++ = c;
*s='\0';}
else{
for (s=shm;*s!='\0';s++)
putchar(*s);
putchar('\n');}
exit(0);
}

St. Joseph’s Institute of Technology 34


C8461-Operating systems Laboratory Department of CSE 2018-2019

OUTPUT
[admin@csk Desktop]$ cc 10a.c
[admin@csk Desktop]$ ./a.out
abcdefghijklmnopqrstuvwxyz
[admin@csk Desktop]$ ipcs

RESULT: Thus the C program to implement inter process communication and shared memory to
print alphabets from a to z was executed successfully and the output was verified.
Viva Questions:
1. What is IPC?
2. What the methods to implement IPC?
3. What is shared memory?
4. What is message passing?
5. What is RPC?

ExNo:8 IMPLEMENT BANKERS ALGORITHM FOR DEAD LOCK


AVOIDANCE
Date:
AIM:
To write a program to implement bankers algorithm for deadlock avoidance.

DATA STRUCTURES
 n-Number of process, m-number of resource types.
St. Joseph’s Institute of Technology 35
C8461-Operating systems Laboratory Department of CSE 2018-2019

 Available: Available[j]=k, k – instance of resource type Rj is available.


 Max: If max[i, j]=k, Pi may request at most k instances resource Rj.
 Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj
 Need: If Need[I, j]=k, Pi may need k more instances of resource type Rj,
Need[I, j]=Max[I, j]-Allocation[I, j];
SAFETY ALGORITHM
1. Work and Finish be the vector of length m and n respectively, Work=Available and Finish[i]
=False.
2. Find an i such that both
 Finish[i] =False
 Need<=Work
If no such I exists go to step 4.
3. work=work+Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the values of resources and processes.
Step 3: Get the avail value.
Step 4: After allocation find the need value.
Step 5: Check whether its possible to allocate.
Step 6: If it is possible then the system is in safe state.
Step 7: Else system is not in safety state.
Step 8: If the new request comes then check that the system is in safety or not if we allow the re-
quest.
Step 9: stop the program.

PROGRAM:
#include<stdio.h>
void main()
{
int i, work[5],avl[5],alloc[10][10],l;
int need[10][10],n,m,I,j,avail[10],max[10][10],k,count,fcount=0,pr[10];
char finish[10]={'f','f','f','f','f','f','f','f','f','f'};
printf("enter the no of process");
scanf("%d",&n);
printf("enter the no of resources");
scanf("%d",&m);
printf("enter the total no of resources");
for(i=1;i<=m;i++)
scanf("%d",&avail[i]);
printf("enter the max resources req by each pr alloc matrix");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&max[i][j]);
printf("process allocation matrix");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&alloc[i][j]);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
need[i][j]=max[i][j]-alloc[i][j];
for(i=1;i<=n;i++)
{
k=0;
for(j=1;j<=m;j++)
{
k=k+alloc[i][j];
St. Joseph’s Institute of Technology 36
C8461-Operating systems Laboratory Department of CSE 2018-2019

}
avl[i]=avl[i]-k;
work[i]=avl[i];
}
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
{
count=0;
for(j=1;j<=m;j++)
{
if((finish[i]=='f')&&(need[i][j]<=work[i]))
count++;
}
if(count==m)
{
for(l=1;l<=m;l++)
work[l]=work[l]+alloc[i][l];
finish[i]='t';
pr[k]=i;
break;
}
}
for(i=1;i<=n;i++)
if(finish[i]=='t')
fcount++;
if(fcount==n)
{
printf("the system is in safe state");
for(i=1;i<=n;i++)
printf("%d",pr[i]);
}
else
printf("the system is not in safe state");
}
OUTPUT
roo@sys5:~/Desktop$ cc bankers.c
roo@sys5:~/Desktop$ ./a.out
Enter the number of process: 5
Enter the number of resources: 3
Enter the total number of resourced: 10 5 7
Enter the max resources required by each pr alloc matrix
753
322
902
222
433
Process allocation matrix
010
200
302
211
002
The system is in safe state 1 2 3 4 5
RESULT: Thus the C program for bankers algorithm was successfully executed and the
output was verified.

St. Joseph’s Institute of Technology 37


C8461-Operating systems Laboratory Department of CSE 2018-2019

Viva Questions:
1. Explain Bankers algorithm?
2. What is meant by deadlock?
3. What is dead lock avoidance?
4. What are the dead lock avoidance methods?
5. How can we prevent deadlocks?
6. What is meant by starvation?
7. When a system is said to be in safe state?

Ex IMPLEMENT AN ALGORITHM FOR DEAD LOCK


No:9
DETECTION
Date:
AIM:
To write a program to implement Deadlock detection algorithm.

ALGORITHM:
1. Start the program.
2. Get the values of resources and processes.
3. Get the allocation and request matrix value.
4. Get the available instances for each resources
5. Check whether its possible to allocate using below condition.
6. If Need<=Work update work as work=work +allocation
7. Else proceed with next process.
8. If it is possible to allocate then the system is in safe state.
9. Else system is not in safe state.
10. Stop the program.

PROGRAM:
#include <stdio.h>;
void main()
{
int found,flag,l,p[4][5],tp,tr,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
printf("Enter total no of processes");
scanf("%d",&tp);
printf("Enter total no of resources");
scanf("%d",&tr);
printf("Enter claim (Max. Need) matrix\n");
for(i=1;i<=tp;i++)
{
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&c[i][j]);
}
printf("Enter allocation matrix\n");
for(i=1;i<=tp;i++)
{
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&p[i][j]);
}
printf("Enter resource vector (Total resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&r[i]);
St. Joseph’s Institute of Technology 38
C8461-Operating systems Laboratory Department of CSE 2018-2019

}
printf("Enter availability vector (available resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}

for(i=1;i<=tp;i++)
{
sum=0;
for(j=1;j<=tr;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=1;i<=tp;i++)
{
for(l=1;l<k;l++)
if(i!=m[l])
{
flag=1;
for(j=1;j<=tr;j++)
if(c[i][j]<temp[j])
{
flag=0;
break;
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=1;j<=tr;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are:");
for(j=1;j<=tp;j++)
{
found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0)
printf("%d\t",j);
}
}
OUTPUT
roo@sys5:~/Desktop$ cc dead.c

St. Joseph’s Institute of Technology 39


C8461-Operating systems Laboratory Department of CSE 2018-2019

roo@sys5:~/Desktop$ ./a.out
Enter total no. of processes : 4
Enter total no. of resources : 5
Enter claim (Max. Need) matrix :
01001
00101
00001
10101
Enter allocation matrix :
10110
11000
00010
00000
Enter resource vector (Total resources) :
21121
Enter availability vector (available resources) :
00001
deadlock causing processes are : 2 3
RESULT: Thus the C program for deadlock detection algorithm was implemented, executed and the
output was verified successfully.
Viva Questions:
1. What is deadlock, starvation? Explain their difference.
2. How can we detect deadlocks?
3. What is deadlock prevention? Explain its methods.
4. What is meant by finite state?
5. What is resource allocation graph

Ex No: 10 IMPLEMENT THREADING & SYNCHRONIZATION APPLICATIONS


Date:

AIM:
To write a program to implement the application of threading and synchronization.

ALGORITHM:
1. Start the process
2. Initialize mutex lock ,thread id and required other variables
3. Create POSIX threads using pthread_create
4. Define thread task by creating new function.
5. Synchronize threads using mutex lock and unlock variables
6. Using pthread_join allow threads to wait until parent process completes
7. Destroy the synchronization variable mutex using pthread_mutex_destroy
8. Stop the process
PROGRAM
//Threading Application Program

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
void* ThreadFunction(void *arg)

St. Joseph’s Institute of Technology 40


C8461-Operating systems Laboratory Department of CSE 2018-2019

{
unsigned long i = 0;
pthread_t id = pthread_self();

if(pthread_equal(id,tid[0]))
{
printf("\n First thread processing\n");
}
else
{
printf("\n Second thread processing\n");
}

for(i=0; i<(0xFFFFFFFF);i++);

return NULL;
}

int main(void)
{
int i = 0;
int err;
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &ThreadFunction, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");

i++;
}
sleep(5);
return 0;
}

OUTPUT
[admin@csk Desktop]$ cc 12thread.c -o 12thread -pthread
[admin@csk Desktop]$ ./12thread
Thread created successfully
First thread processing
Thread created successfully
Second thread processing
[admin@csk Desktop]$

//Synchoronization Application Program

#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
St. Joseph’s Institute of Technology 41
C8461-Operating systems Laboratory Department of CSE 2018-2019

void* doSomeThing(void *arg)


{
pthread_mutex_lock(&lock);
unsigned long i = 0;
counter += 1;
printf("\n Job %d started\n", counter);
for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d finished\n", counter);
pthread_mutex_unlock(&lock);
return NULL;
}
int main(void)
{
int i = 0;
int err;
if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init failed\n");
return 1;
}
while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock);
return 0;
}

OUTPUT
[admin@csk Desktop]$ cc 12sync.c -o 12sync -pthread
[admin@csk Desktop]$ ./12sync
Job 1 started
Job 1 finished
Job 2 started
Job 2 finished
[admin@csk Desktop]$

RESULT: Thus the C program to implement the application of threading and


synchronization was executed successfully.

Viva Questions:

1. Define threads?
2. List the types of threads
3. What is multithreading?
4. Define synchronization.
5. How threads can be used for synchronization?

St. Joseph’s Institute of Technology 42


C8461-Operating systems Laboratory Department of CSE 2018-2019

Ex No: 11 IMPLEMENT MEMORY ALLOCATION METHODS FOR


FIXED PARTITION
Date:

AIM:
To write a program to implementation of the following Memory Allocation Methods for fixed
partition a) First Fit b) Worst Fit c) Best Fit

ALGORITHM:
1. Input memory blocks with size and processes with size.
2. Initialize all memory blocks as free.
3. For First fit memory allocation, Start by picking each process and check if it can be assigned to
current block. If size-of-process <= size-of-block if yes then assign and check for next process. If
not then keep checking the further blocks.
4. For Best fit memory allocation, Start by picking each process and find the minimum block size
that can be assigned to current process i.e., find min(bockSize[1], blockSize[2],.....blockSize[n]) >
processSize[current], if found then assign it to the current process.If not then leave that process
and keep checking the further processes.
5. For Best fit memory allocation,Start by picking each process and find the maximum block size
that can be assigned to current process i.e., find max(bockSize[1],
6. blockSize[2],.....blockSize[n]) > processSize[current], if found then assign it to the current
process. If not then leave that process and keep checking the further processes.
PROGRAM
#include<stdio.h>
main()
{
int i,j,n,l,tb[5],f,t,k=0;
printf("\nEnter the Partitions");
scanf("%d",&n);
printf("\nEnter the no of Processes");
scanf("%d",&l);
int a[n],b[l],par[n],bal[n],ps[l];
printf("\nEnter the space of each partition:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the space required for each processes");
for(i=0;i<l;i++)
scanf("%d",&b[i]);
for(i=0;i<n;i++)
par[i]=a[i];
for(i=0;i<n;i++)
ps[i]=b[i];
for(i=0;i<n;i++)
tb[i]=0;
printf("\nFirst Fit Algorithm");
loop1:
for(i=0;i<n;i++)
bal[i]=0;
i=0;
j=0;
f=0;
printf("\npartition\tprocess\n");
while(j<l)
{
St. Joseph’s Institute of Technology 43
C8461-Operating systems Laboratory Department of CSE 2018-2019

while(i<n && f==0)


{
if(par[i]>ps[j])
{
bal[i]=par[i]-ps[j];
f=1;
printf("\n\t%d\t\t%d",par[i],ps[j]);
par[i]=0;
i++;
}
i++;
}
f=0;i=0;
j++;
}
for(i=0;i<n;i++)
tb[k]+=bal[i]+par[i];
printf("\nMemory Unused=%d\n",tb[k]);
k++;
if(k==2)
goto loop2;
else if(k==3)
goto loop3;
printf("\nBest Fit Algorithm:\n");
for(i=0;i<n;i++)
par[i]=a[i];
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(par[i]>par[j])
{
t=par[i];
par[i]=par[j];
par[j]=t;
}
}
}
goto loop1;
loop2:
printf("\nWorst Fit Algorithm:\n");
for(i=0;i<n;i++)
par[i]=a[i];
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
if(par[i]<par[j])
{
t=par[i];
par[i]=par[j];
par[j]=t;
}
goto loop1;
loop3:
if(tb[0]<tb[1]&&tb[0]<tb[2])
printf("\nFirst Fit is Best\n");
else if(tb[1]<tb[2]&&tb[1]<tb[0])
printf("\nBest Fit is Best\n");
else
printf("\nWorst Fit is Best\n");
St. Joseph’s Institute of Technology 44
C8461-Operating systems Laboratory Department of CSE 2018-2019

}
OUTPUT:
[admin@csk Desktop]$ cc memory.c
[admin@csk Desktop]$ ./a.out

Enter the Partitions5

Enter the no of Processes4

Enter the space of each partition:


100
500
200
300
600

Enter the space required for each processes212


417
112
426

First Fit Algorithm


partition process

500 212
600 417
200 112
Memory Unused=959

Best Fit Algorithm:

partition process

300 212
500 417
200 112
600 426
Memory Unused=533

Worst Fit Algorithm:

partition process

600 212
500 417
300 112
Memory Unused=959

Best Fit is Best

RESULT: Thus the C program to implementation of the following Memory Allocation Methods
for fixed partition was implemented successfully and the output was verified.

Viva Questions:
1. What do you mean by best fit?
2. What do you mean by first fit?
3. Define secondary memory.
St. Joseph’s Institute of Technology 45
C8461-Operating systems Laboratory Department of CSE 2018-2019

4. Define swapping.
5. What do you mean by worst fit?

Ex No: 12 PAGING TECHNIQUE OF MEMORY MANAGEMENT


Date:

AIM:
To implement the Memory management using Paging technique.
ALGORITHM:
1. Read all the necessary input from the keyboard.
2. Pages - Logical memory is broken into fixed - sized blocks.
3. Frames – Physical memory is broken into fixed – sized blocks.
4. Calculate the physical address using the following
1. Physical address = ( Frame number * Frame size ) + offset
5. Display the physical address.
6. Stop the process.

PROGRAM
#include<stdio.h>
#define MAX 50
int main()
{
int page[MAX],i,n,f,ps,off,pno;
clrscr();
printf("\nEnter the no of pages 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++)
{
printf("\n\n%d\t\t",i);
scanf("%d",&page[i]);
}
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);
getch();
return 1;

St. Joseph’s Institute of Technology 46


C8461-Operating systems Laboratory Department of CSE 2018-2019

OUTPUT:
[admin@csk Desktop]$ cc 11.c
[admin@csk Desktop]$ ./a.out
Enter the no of pages in memory 4
Enter page size 3
Enter no of frames 4
Enter the page table
(Enter frame no as -1 if that page is not present in any frame)
pageno frameno
------- -------
0 10
1 11
2 12
3 13

Enter the logical address(i.e,page no & offset):2 50


Physical address(i.e,frame no & offset):12,50[admin@csk Desktop]$

RESULT: Thus the C program for paging technique was implemented successfully and the
output was verified.

Viva Questions:
1. Explain paging technique.
2. Define pages, frames, offset in paging technique.
3. What is meant by logical and physical address?
4. What is thrashing?
5. What is meant by page hit, page fault?

St. Joseph’s Institute of Technology 47


C8461-Operating systems Laboratory Department of CSE 2018-2019

Ex No: 12A FIFO PAGE REPLACEMENT ALGORITHM


Date:

AIM:
To implement First in First Out page replacement technique.

ALGORITHM:
1. Start the process
2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Forma queue to hold all pages
6. Insert the page require memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted
9. Display the values
10. Stop the process

PROGRAM:
#include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
return 0;
St. Joseph’s Institute of Technology 48
C8461-Operating systems Laboratory Department of CSE 2018-2019

OUTPUT:
[admin@csk Desktop]$ vi 9a.c
[admin@csk Desktop]$ cc 9a.c
[admin@csk Desktop]$ ./a.out
ENTER THE NUMBER OF PAGES:
20
ENTER THE PAGE NUMBER :
70120304230321201701
ENTER THE NUMBER OF FRAMES :3
ref string page frames
7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
0
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
3
2
1 0 1 3
2 0 1 2
0
1
7 7 1 2
0 7 0 2
1 7 0 1
Page Fault Is 15[admin@csk Desktop]$

RESULT: Thus the C program for FIFO page replacement technique was executed successfully and
the output was verified.

Ex No: 12B LRU PAGE REPLACEMENT ALGORITHM


Date:
AIM:
To implement Least Recently Used page replacement technique.

ALGORITHM:
1. Start the process
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process

PROGRAM:
#include<stdio.h>
St. Joseph’s Institute of Technology 49
C8461-Operating systems Laboratory Department of CSE 2018-2019

main(){
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf("Enter no of pages:");
scanf("%d",&n);
printf("Enter the reference string:");
for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of frames:");
scanf("%d",&f);
q[k]=p[k];
printf("\n\t%d\n",q[k]);
c++;
k++;
for(i=1;i<n;i++){
c1=0;
for(j=0;j<f;j++){
if(p[i]!=q[j])
c1++;}
if(c1==f){
c++;
if(k<f){
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");}
else{
for(r=0;r<f;r++){
c2[r]=0;
for(j=i-1;j<n;j--){
if(q[r]!=p[j])
c2[r]++;
else
break;}}for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++){
for(j=r;j<f;j++){
if(b[r]<b[j]){
t=b[r];
b[r]=b[j];
b[j]=t;}}}
for(r=0;r<f;r++){
if(c2[r]==b[0])
q[r]=p[i];
printf("\t%d",q[r]);}
printf("\n");}}}
printf("\nThe no of page faults is %d",c);}

OUTPUT:

[admin@csk Desktop]$ cc 9b.c


[admin@csk Desktop]$ ./a.out
Enter no of pages:10
Enter the reference string:7 5 9 4 3 7 9 6 2 1
Enter no of frames:3
7
7 5
St. Joseph’s Institute of Technology 50
C8461-Operating systems Laboratory Department of CSE 2018-2019

7 5 9
4 5 9
4 3 9
4 3 7
9 3 7
9 6 7
9 6 2
1 6 2

The no of page faults is 10 [admin@csk Desktop]$


RESULT: Thus the C program for LRU was executed successfully and the output was verified.

Ex No: 13C LFU PAGE REPLACEMENT ALGORITHM


Date:

AIM:
To implement Least Frequently Used page replacement technique.

ALGORITHM:
1. Start the process
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least frequently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process
PROGRAM:
#include<stdio.h>
int main()
{
int f,p;
int pages[50],frame[10],hit=0,count[50],time[50];
int i,j,page,flag,least,minTime,temp;
printf("Enter no of frames : ");
scanf("%d",&f);
printf("Enter no of pages : ");
scanf("%d",&p);
for(i=0;i<f;i++)
{
frame[i]=-1;
}
for(i=0;i<50;i++)
{
count[i]=0;
}
printf("Enter page no : \n");
for(i=0;i<p;i++)
{
scanf("%d",&pages[i]);
}
printf("\n");

St. Joseph’s Institute of Technology 51


C8461-Operating systems Laboratory Department of CSE 2018-2019

for(i=0;i<p;i++)
{
count[pages[i]]++;
time[pages[i]]=i;
flag=1;
least=frame[0];
for(j=0;j<f;j++)
{
if(frame[j]==-1 || frame[j]==pages[i])
{
if(frame[j]!=-1)
{
hit++;
}
flag=0;
frame[j]=pages[i];
break;
}
if(count[least]>count[frame[j]])
{
least=frame[j];
}
}
if(flag)
{
minTime=50;
for(j=0;j<f;j++)
{
if(count[frame[j]]==count[least] && time[frame[j]]<minTime)
{
temp=j;
minTime=time[frame[j]];
}
}
count[frame[temp]]=0;
frame[temp]=pages[i];
}
for(j=0;j<f;j++)
{
printf("%d ",frame[j]);
}
printf("\n");
}
printf("Page hit = %d",hit);
return 0;
}
OUTPUT
roo@sys5:~/Desktop$ lru.c
roo@sys5:~/Desktop$ ./a.out
Enter no of frames: 3
Enter no of pages:10

St. Joseph’s Institute of Technology 52


C8461-Operating systems Laboratory Department of CSE 2018-2019

Enter page no:


2
3
4
2
1
3
7
5
4
3
2 -1 -1
2 3 -1
2 3 4
2 3 4
2 1 4
2 1 3
2 7 3
2 7 5
2 4 5
2 4 3
Page hit=1
RESULT: Thus the C program for LRU was executed successfully and the output was
verified.

Viva Questions:

1. Explain LFU technique?


2. What is meant by page fault?
3. Which is the best page replacement technique?
4. What is page and frame in OS?
5. What is meant by Belady’s Anamoly

Ex No: 14A SINGLE LEVEL DIRECTORY


Date:
AIM:
To write a program to implement Single Level Directory structure.

ALGORITHM:
Step 1: Read the number of directories to be created.
Step 2: Input the number of files for each directory.
Step 3: Give the file names for the files.
Step 4: Display the single level directory containing files in each.

PROGRAM:
#include<stdio.h>
main()
{
int master,s[20];
char f[20][20][20];
char d[20][20];
St. Joseph’s Institute of Technology 53
C8461-Operating systems Laboratory Department of CSE 2018-2019

int i,j;
printf("enter number of directorios:");
scanf("%d",&master);
printf("enter names of directories:");
for(i=0;i<master;i++)
scanf("%s",d[i]);
printf("enter size of directories:");
for(i=0;i<master;i++)
scanf("%d",&s[i]);
printf("enter the file names :");
for(i=0;i<master;i++)
for(j=0;j<s[i];j++)
scanf("%s",f[i][j]);
printf("\n");
printf(" directory\tsize\tfilenames\n");
printf("*************************************************\n");
for(i=0;i<master;i++)
{
printf("%s\t\t%2d\t",d[i],s[i]);
for(j=0;j<s[i];j++)
printf("%s\n\t\t\t",f[i][j]);
printf("\n");
}
printf("\t\n");
}
OUTPUT
[admin@csk Desktop]$ cc 6a.c
[admin@csk Desktop]$ ./a.out
enter number of directorios:2
enter names of directories:Directory1 Directory2
enter size of directories:4 3
enter the file names :
f1
f2
f3
f4
f5
f6
f7
f8
directory size filenames
*************************************************
Directory1 4 f1
f2
f3
f4
Directory2 3 f5
f6
f7
RESULT: Thus the C program for single level directory structure was executed successfully
and the output was verified.

Ex No: 14B TWO LEVEL DIRECTORY


St. Joseph’s Institute of Technology 54
C8461-Operating systems Laboratory Department of CSE 2018-2019

Date:
AIM:
To write a program to implement two level directory structure.

ALGORITHM:
Step 1: Read the number of directories to be created.
Step 2: Input the number of subdirectories and names of the subdirectories for each directory.
Step 3: Give the file names for the files under the subdirectories.
Step 4: Display the two level structure for each directory created.

PROGRAM:
#include<stdio.h>
struct st
{
char dname[10];
char sdname[10][10];
char fname[10][10][10];
int ds,sds[10];
}dir[10];
void main()
{
int i,j,k,n;
clrscr();
printf("enter number of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter directory %d names:",i+1);
scanf("%s",&dir[i].dname);
printf("enter size of directories:");
scanf("%d",&dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("enter subdirectory name and size:");
scanf("%s",&dir[i].sdname[j]);
scanf("%d",&dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
{
printf("enter file name:");
scanf("%s",&dir[i].fname[j][k]);
}
}
}
printf("\ndirname\t\tsize\tsubdirname\tsize\tfiles");
printf("\n******************************************************\n");
for(i=0;i<n;i++)
{
printf("%s\t\t%d",dir[i].dname,dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("\t%s\t\t%d\t",dir[i].sdname[j],dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
printf("%s\t",dir[i].fname[j][k]);
printf("\n\t\t");
}
printf("\n");
}
St. Joseph’s Institute of Technology 55
C8461-Operating systems Laboratory Department of CSE 2018-2019

OUTPUT:

[admin@csk Desktop]$ cc 6b.c


[admin@csk Desktop]$ ./a.out
enter number of directories:2
enter directory 1 names:D1
enter size of directories:2
enter subdirectory name and size:S1 2
enter file name:f1
enter file name:f2
enter subdirectory name and size: 2 1
enter file name:f3
enter directory 2 names:D2
enter size of directories:1
enter subdirectory name and size:S3 1
enter file name:f4
dirname size subdirname size files
******************************************************
D1 2 S1 2 f1 f2
S2 1 f3
D2 1 S3 1 f4
[admin@csk Desktop]$

RESULT: Thus the C program for two level directory structures was executed successfully
and the output was verified.

Ex No: 14C HIERARCHY LEVEL DIRECTORY


Date:
AIM:
To write a program to implement Hierarchy level directory.

ALGORITHM:
Step 1: Read the Directory for which the hierarchy structure to be displayed.
Step 2: Write commands to access through the subdirectories and files in the given directory.
Step 3: If subdirectories found print them as next level of the directory
Step 4: If file found print them as next sub level of the sub directory

PROGRAM:
#define _XOPEN_SOURCE 500
#include<ftw.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
#include<limits.h>
#define TRUE 1
#define FALSE 0
#define MAXDEPTH 20
static int display_info(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf)
{
char blanks[PATH_MAX];
const char *filename=fpath+ftwbuf->base;
St. Joseph’s Institute of Technology 56
C8461-Operating systems Laboratory Department of CSE 2018-2019

int width = 4*ftwbuf->level;


memset(blanks ,' ', width);
blanks[width] = '\0';
printf("%s%s",blanks,filename);
if(tflag==FTW_DNR)
printf("(unreadabledirectory)");
else if(tflag==FTW_SL)
printf("(symboliclink)");
else if(tflag==FTW_SLN)
printf("(brokensymboliclink)");
else if(tflag==FTW_NS)
printf("statfailed");
printf("\n");
return 0;
}
int main(int argc,char *argv[])
{
int flags=0;
int status;
int ch;
char options[]=":cdpm";
opterr=0;
while(TRUE)
{
ch=getopt(argc,argv,options);
///*itreturns−1whenitfindsnomoreoptions */
if(-1 == ch)
break;
switch(ch)
{
case 'c':
flags|=FTW_CHDIR;
break;
case 'd':
flags|=FTW_DEPTH;
break;
case 'p':
flags|=FTW_PHYS;
break;
case 'm':
flags|=FTW_MOUNT;
break;
default:
fprintf(stderr,"Badoptionfound.\n");
return 1;
}
}
if(optind<argc)
{
while(optind<argc)
{
status=nftw(argv[optind],display_info,MAXDEPTH,flags);
if(-1 == status)
{
perror("nftw");
exit(EXIT_FAILURE);
}
else
St. Joseph’s Institute of Technology 57
C8461-Operating systems Laboratory Department of CSE 2018-2019

optind++;
}}
else
{
status=nftw(".",display_info,MAXDEPTH,flags);
if(-1==status)
{
perror("nftw");
exit(EXIT_FAILURE);
}
}
exit(EXIT_SUCCESS);
}
OUTPUT:
[admin@csk Desktop]$ cc 6c.c
[admin@csk Desktop]$ ./a.out Folder1
Folder1
6b.c
5.c
Folder2
Folder4
4.c
3.c
5a.c
5b.c
5c.c
6a.c
6b.c
6c.c
7a.c
7b.c
Folder3
UNIT III Notes.doc
Assignment-1.doc
Unit1.docx
Unit2.docx
Unit3.docx
Unit4.docx
Unit5.docx
Scene.jpg
Data.jpg
[admin@csk Desktop]$
RESULT: Thus the C program for Hierarchy level directory was executed successfully and
output was verified.
Viva Questions:

1. Explain Hierarchical Level Directory (HLD)?


2. What are the various File directory structures?
3. Advantages of HLD over SLD and TLD.
4. Disadvantages of HLD.
5. Explain Single Level Directory (SLD)?

St. Joseph’s Institute of Technology 58


C8461-Operating systems Laboratory Department of CSE 2018-2019

Ex.No:15A IMPLEMENTATION OF SEQUENTIAL FILE


ALLOCATION
Date:

AIM:
To write a program to implement sequential file allocation.

ALGORITHM:
Step 1: Create a disk space using array.
Step 2: Give the file length and starting block number.
Step 3: Allocate each block of the file sequentially in disk.
Step 4: The disk space is checked to ensure the block is allocated or not.

PROGRAM

#include<stdio.h>
main()
{
int f[50],i,st,j,len,c,k;
X:
for(i=0;i<50;i++)
f[i]=0;
printf("\n Enter the starting block & length of file");
scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++)
if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("Block already allocated");
break;
}
if(j==(st+len))
printf("\n the file is allocated to disk");
printf("\n if u want to enter more files?(y-1/n-0)");
scanf("%d",&c);
if(c==1)
goto X;
return 0;
}
OUTPUT:

St. Joseph’s Institute of Technology 59


C8461-Operating systems Laboratory Department of CSE 2018-2019

roo@sys5:~/Desktop$ gcc sfa.c


roo@sys5:~/Desktop$ ./a.out
Enter the starting block & length of file 4 10
4->1
5->1
6->1
7->1
8->1
9->1
10->1
11->1
12->1
13->1
the file is allocated to disk
if u want to enter more files?(y-1/n-0)0
RESULT: Thus the C program for sequential file allocation was executed successfully and
the output was verified.

Ex No: 15B IMPLEMENTATION OF INDEXED FILE ALLOCATION


Date:

AIM:
To write a program to implement indexed file allocation.

ALGORITHM:

Step 1: Enter the number of files along with their file names.
Step 2: Give the file size and block size for each file.
Step 3: Enter the block numbers for each block in file.
Step 4: Display the indexed file allocation of each file.

PROGRAM

#include<stdio.h>
#include<string.h>
int n;
void main()
{
int b[20],b1[20],i,j,blocks[20][20],sz[20];
char F[20][20],S[20],ch;
clrscr();
printf("\n Enter no. of Files ::");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter file %d name ::",i+1);
scanf("%s",F[i]);
printf("\n Enter file%d size(in kb)::",i+1);
scanf("%d",&sz[i]);
printf("\n Enter blocksize of File%d(in bytes)::",i+1);
scanf("%d",&b[i]);
}
for(i=0;i<n;i++)
{
b1[i]=(sz[i]*1024)/b[i];
printf("\n\nEnter blocks for file%d",i+1);
St. Joseph’s Institute of Technology 60
C8461-Operating systems Laboratory Department of CSE 2018-2019

for(j=0;j<b1[i];j++)
{
printf("\n Enter the %dblock ::",j+1);
scanf("%d",&blocks[i][j]);
}
}
do
{
printf("\nEnter the Filename ::");
scanf("%s",S);
for(i=0;i<n;i++)
{
if(strcmp(F[i],S)==0)
{
printf("\nFname\tFsize\tBsize\tNblocks\tBlocks\n");
printf("\n---------------------------------------------\n");
printf("\n%s\t%d\t%d\t%d\t",F[i],sz[i],b[i],b1[i]);
for(j=0;j<b1[i];j++)
printf("%d->",blocks[i][j]);
}
}
printf("\n---------------------------------------------\n");
printf("\nDo U want to continue ::(Y-1:n-0)");
scanf("%c",&ch);
}while(ch!=0);
}

OUTPUT
roo@sys5:~/Desktop$ gcc ifa.c
roo@sys5:~/Desktop$ ./a.out
Enter no. of Files ::2
Enter file 1 name ::fileA
Enter file1 size(in kb)::1
Enter blocksize of File1(in bytes)::543
Enter file 2 name ::fileB
Enter file2 size(in kb)::1
Enter blocksize of File2(in bytes)::489
Enter blocks for file1
Enter the 1block ::1024
Enter blocks for file2
Enter the 1block ::1500
Enter the 2block ::966
Enter the Filename ::fileA
Fname Fsize Bsize Nblocks Blocks
----------------------------------------------------------
fileA 1 543 1 1024->
-----------------------------------------------------------
Do U want to continue ::(Y-1:n-0)

RESULT: Thus the C program for indexed file allocation was executed successfully and the
output was verified.

Ex No: 15C IMPLEMENTATION OF LINKED FILE ALLOCATION


Date:
AIM:
St. Joseph’s Institute of Technology 61
C8461-Operating systems Laboratory Department of CSE 2018-2019

To write a program to implement linked file allocation.

ALGORITHM:
Step 1: Enter the number of files along with their file names.
Step 2: Give the file size and block size for each file.
Step 3: Enter the block numbers for each block in file.
Step 4: Display the linked file allocation of each file using their block delimiters.

PROGRAM
#include<stdio.h>
#include<string.h>
int n;
void main()
{
int b[20],b1[20],i,j,blocks[20][20],sz[20];
char F[20][20],S[20],ch;
int sb[20],eb[20],x;
printf("\n Enter no. of Files ::");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter file %d name ::",i+1);
scanf("%s",&F[i]);
printf("\n Enter file%d size(in kb)::",i+1);
scanf("%d",&sz[i]);
printf("\n Enter blocksize of File%d(in bytes)::",i+1);
scanf("%d",&b[i]);
}
for(i=0;i<n;i++)
{
b1[i]=(sz[i]*1024)/b[i];
printf("\n Enter Starting block of file%d::",i+1);
scanf("%d",&sb[i]);
printf("\n Enter Ending block of file%d::",i+1);
scanf("%d",&eb[i]);
printf("\nEnter blocks for file%d::\n",i+1);
for(j=0;j<b1[i]-2;)
{
printf("\n Enter the %dblock ::",j+1);
scanf("%d",&x);
if(x>sb[i]&&x<eb[i])
{
blocks[i][j]=x;
j++;
}
else
printf("\n Invalid block::");
}
}
do
St. Joseph’s Institute of Technology 62
C8461-Operating systems Laboratory Department of CSE 2018-2019

{
printf("\nEnter the Filename ::");
scanf("%s",&S);
for(i=0;i<n;i++)
{
if(strcmp(F[i],S)==0)
{
printf("\nFname\tFsize\tBsize\tNblocks\tBlocks\n");
printf("\n---------------------------------------------\n");
printf("\n%s\t%d\t%d\t%d\t",F[i],sz[i],b[i],b1[i]);
printf("%d->",sb[i]);
for(j=0;j<b1[i]-2;j++)
printf("%d->",blocks[i][j]);
printf("%d->",eb[i]);
}
}
printf("\n---------------------------------------------\n");
printf("\nDo U want to continue (Y:n)::");
scanf("%d",&ch);
}
while(ch!=0);
}

OUTPUT
roo@sys5:~/Desktop$ gcc lfa.c
roo@sys5:~/Desktop$ ./a.out
Enter no. of Files ::2
Enter file 1 name ::aa
Enter file1 size(in kb)::1
Enter blocksize of File1(in bytes)::512
Enter file 2 name ::bb
Enter file2 size(in kb)::1
Enter blocksize of File2(in bytes)::1024
Enter Starting block of file1::1100
Enter Ending block of file1::1600
Enter blocks for file1::
Enter Starting block of file2::102
Enter Ending block of file2::104
Enter blocks for file2::
Enter the Filename ::aa
Fname Fsize Bsize Nblocks Blocks
-------------------------------------------------------------------
aa 1 512 2 1100->1600->
-------------------------------------------------------------------
Do U want to continue (Y:n)::y
Enter the Filename ::bb
Fname Fsize Bsize Nblocks Blocks
-------------------------------------------------------------------
bb 1 1024 1 102->104->
-------------------------------------------------------------------
Do U want to continue (Y:n)::0

RESULT: Thus the C program for linked file allocation was executed successfully and the
output was verified.
St. Joseph’s Institute of Technology 63
C8461-Operating systems Laboratory Department of CSE 2018-2019

Viva Questions:
1. Explain Linked File allocation?
2. Explain Sequential File allocation?
3. Explain Indexed File allocation?
4. What is the need for efficient file allocation strategies?
5. Advantages of indexed file allocation.

ADDITIONAL EXPERIMENTS
READER WRITER PROBLEM

PROGRAM
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
sem_t readCountAccess;
sem_t databaseAccess;
int readCount=0;
void *Reader(void *arg);
void *Writer(void *arg);
int main()
{
int i=0,NumberofReaderThread=0,NumberofWriterThread;
sem_init(&readCountAccess,0,1);
sem_init(&databaseAccess,0,1);

pthread_t Readers_thr[100],Writer_thr[100];
printf(“\nEnter number of Readers thread(MAX 10)”);
scanf(“%d”,&NumberofReaderThread);
printf(“\nEnter number of Writers thread(MAX 10)”);
scanf(“%d”,&NumberofWriterThread);

for(i=0;i<numberofreaderthread;i++)
{
pthread_create(&Readers_thr[i],NULL,Reader,(void *)i);
}
for(i=0;i<numberofwriterthread;i++)
{
pthread_create(&Writer_thr[i],NULL,Writer,(void *)i);
}
for(i=0;i<NumberofWriterThread;i++)
{
pthread_join(Writer_thr[i],NULL);
}

for(i=0;i<NumberofReaderThread;i++)
{
pthread_join(Readers_thr[i],NULL);
}
sem_destroy(&databaseAccess);
St. Joseph’s Institute of Technology 64
C8461-Operating systems Laboratory Department of CSE 2018-2019

sem_destroy(&readCountAccess);
return 0;
}
void * Writer(void *arg)
{

sleep(1);
int temp=(int)arg;
printf(“\nWriter %d is trying to enter into database for modifying the data”,temp);
sem_wait(&databaseAccess);
printf(“\nWriter %d is writting into the database”,temp);
printf(“\nWriter %d is leaving the database”);
sem_post(&databaseAccess);
}
void *Reader(void *arg)
{
sleep(1);
int temp=(int)arg;
printf(“\nReader %d is trying to enter into the Database for reading the data”,temp);
sem_wait(&readCountAccess);
readCount++;
if(readCount==1)
{
sem_wait(&databaseAccess);
printf(“\nReader %d is reading the database”,temp);
}
sem_post(&readCountAccess);
sem_wait(&readCountAccess);
readCount–;
if(readCount==0)
{
printf(“\nReader %d is leaving the database”,temp);
sem_post(&databaseAccess);
}
sem_post(&readCountAccess);
}

OUTPUT
Enter number of Readers thread(MAX 10)2
Enter number of Writers thread(MAX 10)1
Reader 0 is trying to enter into the Database for reading the data
Reader 0 is reading the database
Reader 0 is leaving the database
Reader 1 is trying to enter into the Database for reading the data
Reader 1 is reading the database
Reader 1 is leaving the database
Writer 0 is trying to enter into database for modifying the data
Writer 0 is writing into the database
Writer 0 is leaving the dat

St. Joseph’s Institute of Technology 65

You might also like