You are on page 1of 102

2023-2024 SEM: 4 Operating Systems

VELAMMAL ENGINEERING COLLEGE

DEPARTMENT OF INFORMATION TECHNOLOGY

II YEAR / IV SEMESTER

21CS206L – OPERATING SYSTEM LABORATORY

Submitted by

REG NO: _____________________________________

Name of the Student: ______________________________________

II YEAR – VEC
Page 1
2023-2024 SEM: 4 Operating Systems

LIST OF EXPERIMENTS

1. Basics of UNIX commands and shell programs


2. Implement few UNIX commands using system calls
3. CPU Scheduling Algorithms for stack and queue Application.
4. Semaphores and IPC.
5. Bankers Algorithm for Deadlock Avoidance
6. Threading & Synchronization Application for Reader Writer Problem
7. Memory Allocation Methods for fixed partition a)First Fit b) Worst Fit c) Best Fit
8. Paging Technique of Memory Management
9. Page Replacement Algorithms a) FIFO b) LRU c) LFU
10. Disk Scheduling algorithms
11. File Organization Techniques
12. File Allocation Strategies a) Sequential b) Indexed c) Linked
13. Mobile Application for Health care system

II YEAR – VEC
Page 2
2023-2024 SEM: 4 Operating Systems

EX.NO: 1 STUDY OF UNIX COMMANDS

COMMANDS:
GENERAL COMMANDS:
NAME SYNTAX DESCRIPTION OUTPUT
Who $who Displays users who are currently elcot@boss:~$ who
logged on elcot tty1 2021-02-11 16:59 (:0)
Who am i $who am i Displays our own login terminal and elcot@boss:~$ whoami
other details elcot
finger $ finger it3 Displays system biography on user
[user] `[user]'.

Date $date Displays the date which is stored in elcot@boss:~$ date


particular format Thu Feb 11 17:06:34 IST 2021

Calendar $cal<month><year> Displays calendar of specified month elcot@boss:~$ cal 2 2002


and year February 2002
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

Clear $clear Clears the screen and displays theelcot@boss:~$ clear


new screen elcot@boss:~$
Uname $uname Displays the OS which is used. elcot@boss:~$ uname
Linux
$uname –a Displays all machine details elcot@boss:~$ uname -a
Linux boss 4.18.0-0.bpo.1-amd64 #1 SMP
Debian 4.18.6-1~bpo9+1 (2018-09-13)
x86_64 GNU/Linux
$uname –s Displays the OS name elcot@boss:~$ uname -s
Linux
$uname –v Displays the version of OS elcot@boss:~$ uname -v
#1 SMP Debian 4.18.6-1~bpo9+1 (2018-09-
13)
$uname –r Displays the release of OS elcot@boss:~$ uname -r
4.18.0-0.bpo.1-amd64
$uname –n Displays the name of network mode elcot@boss:~$ uname -n
boss
$uname –m Displays the type of OS elcot@boss:~$ uname -m
x86_64
Binary $bc Used for calculation elcot@boss:~$ bc
calculator bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000,
2004, 2006 Free Software Foundation, Inc.

II YEAR – VEC
Page 3
2023-2024 SEM: 4 Operating Systems
This is free software with ABSOLUTELY
NO WARRANTY.
For details type `warranty'.
Identifier $id Displays userid and groupid elcot@boss:~$ id
uid=1000(elcot) gid=1000(elcot)
groups=1000(elcot),24(cdrom),25(floppy),27
(sudo),29(audio),30(dip),44(video),46(plugd
ev),108(netdev),113(bluetooth),118(scanner)
,124(lpadmin),127(sambashare)
Present $pwd Displays the currently working elcot@boss:~$ pwd
working directory /home/elcot
Directory
Echo $echo<text> Displays the text given by the user elcot@boss:~$ echo hi Sathya
hi Sathya
Man $man <command> Displays the details of specified elcot@boss:~$ man clear
command clear(1) General Commands
Manual clear(1)

NAME
clear - clear the terminal screen

SYNOPSIS
clear

DESCRIPTION
clear clears your screen if this is
possible, including its scrollback
buffer (if the extended “E3” capability is
defined). clear looks in
the environment for the terminal type
and then in the terminfo database
to determine how to clear the screen.

clear ignores any command-line


parameters that may be present.

HISTORY
A clear command appeared in 2.79BSD
dated February 24, 1979. Later
that was provided in Unix 8th edition
(1985).

AT&T adapted a different BSD


program (tset) to make a new command
(tput), and used this to replace the clear
command with a shell script
which calls tput clear, e.g.,
Touch $touch <filename> Creates a file elcot@boss:~$ touch newfile
Tty $tty Displays the terminal number of elcot@boss:~$ tty
system /dev/pts/0

II YEAR – VEC
Page 4
2023-2024 SEM: 4 Operating Systems

LISTING OPTIONS
SYNTAX DESCRIPTION OUTPUT
$ls Lists all files in the present working elcot@boss:~$ ls
directory Desktop Downloads newfile Public Videos
Documents Music Pictures Templates
$ls –a Displays all hidden files of the user elcot@boss:~$ ls -a
. .cache .gconf Music .ssh
.xscreensaver
.. .config .gnome2 newfile Templates
.anydesk .dbus .gnupg Pictures .tuxtype
.bash_history Desktop .ICEauthority .pki Videos
.bash_logout Documents .local .profile .viminfo
.bashrc Downloads .mozilla Public .wine
$ls –c Lists all subdirectories of the file in elcot@boss:~$ ls -c
columnwise fashion newfile Downloads Desktop Music Templates
Documents Pictures Videos Public
$ls –d Displays the root directory of the elcot@boss:~$ ls -d
present directory .
$ls –r Reverses the order in which files and elcot@boss:~$ ls -r
sundirectories are displayed Videos Public newfile Downloads Desktop
Templates Pictures Music Documents
$ls –R Lists the files and subdirectories in elcot@boss:~$ ls -R
hierarchial order .:
Desktop Downloads newfile Public Videos
Documents Music Pictures Templates

./Desktop:
BOSS-Manual libreoffice-calc.desktop
Camera.desktop libreoffice-impress.desktop
chromium.desktop libreoffice-writer.desktop
Do's and Don'ts Link to Books
English-TamilDictionary.xls TechnicalGlossary-
alphabeticalwise.xls
firefox-esr.desktop thirukural.desktop
Laptop Instruction english.pdf tuxtype.desktop
libreoffice-base.desktop xscreensaver-
properties.desktop

./Documents:
maths physics

./Documents/maths:
28. Pavithra C - 1.Unix commands.odt m.unit-3 part-b
questions.pdf
m.cauchy's intergral formula.pdf m. unit-3 part-c
questions.pdf
m.complex integration.pdf m.unit 4 complex
integration PART C.pdf
m.Laplace Transform Notes.pdf m.unit-4 part-a.pdf
m.unit-3 notes.pdf m.unit -4 part-b.pdf
m.unit-3 part-a.pdf m.z plane w plane.pdf

II YEAR – VEC
Page 5
2023-2024 SEM: 4 Operating Systems
m.unit 3 part- b.pdf unit5 - part-a
m.unit-3 part-b.pdf Unit 5 - Part B (Q&A)
LT(1).pdf

./Downloads:
CamScanner 05-06-2020 22.45.30.pdf
Links- Convolution Theorem problems.docx
LT- Periodic Functions.pdf
MODEL QP-PYTHON.docx
newfile.txt
pavi
python unit 4.pdf
The model exam schedule for I year students.docx
UNIT - 1 QUESTION BANK(1).docx
UNIT - 1 QUESTION BANK.docx
unit4.pdf
UNIT 5 PART A & B QA - FINAL.pdf
Unit 5 - Part B (Q&A) LT(1).pdf
Unit 5 - Part B (Q&A) LT(2).pdf
Unit 5 - Part B (Q&A) LT.pdf
UNIT III_PYTHON.pdf
UNIT III QB-PYTHON.docx
UNIT II QB-PYTHON-1(1).docx
UNIT II QB-PYTHON-1(2).docx
UNIT II QB-PYTHON-1.docx
UNIT II QB-PYTHON.docx
UNIT IV QB.docx
UNIT V QB-PYTHON.docx

./Downloads/pavi:

./Music:

./Pictures:
Background Screen Elcot P-VII.jpg Wallpapers

./Pictures/Wallpapers:
Background Screen Elcot P-VII.jpg

./Public:

./Templates:
New Database.odb New Draw.odg New
Presentation.odp
New Document.odt New Empty File New
Spreadsheet.ods

./Videos:
BOSS-Video Webcam

./Videos/Webcam:
$ls –t Displays the files in the order of elcot@boss:~$ ls -t
modification newfile Downloads Desktop Templates Public
Documents Pictures Videos Music

II YEAR – VEC
Page 6
2023-2024 SEM: 4 Operating Systems
$ls –p Displays files and sundirectories by a elcot@boss:~$ ls -p
slashmark Desktop/ Downloads/ newfile Public/ Videos/
Documents/ Music/ Pictures/ Templates/
$ls –i Displays the node number of each file elcot@boss:~$ ls -i
2486327 Desktop 2486347 Music 2486349 Public
2486345 Documents 2492341 newfile 2486350
Templates
2486346 Downloads 2486348 Pictures 2486357 Videos
$ls –l Lists the permission given to each file elcot@boss:~$ ls -l
total 32
drwxr-xr-x 2 elcot elcot 4096 Jan 26 2019 Desktop
drwxr-xr-x 3 elcot elcot 4096 Feb 11 17:04 Documents
drwxr-xr-x 3 elcot elcot 4096 Jan 30 13:38 Downloads
drwxr-xr-x 2 elcot elcot 4096 Jan 7 2019 Music
-rw-r--r-- 1 elcot elcot 0 Feb 11 19:40 newfile
drwxr-xr-x 3 elcot elcot 4096 Mar 1 2019 Pictures
drwxr-xr-x 2 elcot elcot 4096 Jan 7 2019 Public
drwxr-xr-x 2 elcot elcot 4096 Jan 20 2019 Templates
drwxr-xr-x 3 elcot elcot 4096 Jan 24 2019 Videos

PATTERN SEARCHING COMMAND


NAME SYNTAX DESCRIPTION OUTPUT
Grep $grep<pattern> Displays the line in which the elcot@boss:~$ grep "HI." newfile
<filename> given pattern is seen Thu Feb 11 23:19:42 IST 2021 HI.

FILE MANIPULATION COMMANDS


NAME SYNTAX DESCRIPTION OUTPUT
Cat>> $cat>><filename> Edit contents of existing file elcot@boss:~$ cat >> test2
elcot@boss:~$ cat test2
Thu Feb 11 23:48:13 IST 2021 this is the
second line.
Cat $cat <filename> View the contents of the file elcot@boss:~$ cat newfile
Thu Feb 11 23:19:42 IST 2021 HI.
Cat $cat –n filename Displays the file with line numbers elcot@boss:~$ cat -n newfile
1 Thu Feb 11 23:48:13 IST 2021
this is the second line.
More $more <filename> Displays the file page by page elcot@boss:~$ more newfile
Thu Feb 11 23:48:13 IST 2021 this is the
second line.
th
More+ $more+10 <filename> Files will be displayed from the 10
page onwards
Wc $wc Counts the number of elcot@boss:~$ wc newfile
words,characters and lines for a 1 11 54 newfile
given file
Wc –l $wc –l Displays the number of lines elcot@boss:~$ wc -l newfile
1 newfile
Wc –w $wc –w Displays the number of words elcot@boss:~$ wc -w newfile
11 newfile

II YEAR – VEC
Page 7
2023-2024 SEM: 4 Operating Systems
Wc –c $wc –c Displays only the number of elcot@boss:~$ wc -c newfile
characters 54 newfile
Cp $cp Copy a file elcot@boss:~$ cp newfile test2
<filename1><filename2> elcot@boss:~$ cat test2
Thu Feb 11 23:48:13 IST 2021 this is the
second line.
Mv $mv<filename1><filena Move a file from a directory to elcot@boss:~$ mv newfile test2
me2> another directory elcot@boss:~$ ls
Desktop geekfile.txt newfile.txt
sometextfile.txt Videos
Documents Music Pictures
Templates
Downloads new Public test2
rm rm <filename> removes a file elcot@boss:~$ rm sometextfile.txt
elcot@boss:~$ ls
Desktop Downloads Music newfile.txt
Public test2
Documents geekfile.txt new Pictures
Templates Videos
rm –i filename ask you for confirmation before elcot@boss:~$ rm -i newfile.txt
actually deleting anything rm: remove regular empty file 'newfile.txt'?
no
diff <filename1> compares files, and shows where elcot@boss:~$ diff test2 test3
diff <filename2 > they differ 1c1
< Thu Feb 11 23:48:13 IST 2021 this is the
second line.
---
> Fri Feb 12 00:07:40 IST 2021 this is third
line.
Ln –s $ln –s <source Creates a soft link between files. elcot@boss:~$ ln -s test3 test4
filename><new Here contents are copied to a new elcot@boss:~$ cat test4
filename> file but the memory addresses of Fri Feb 12 00:07:40 IST 2021 this is third
both files are same.[After creating line.
the link (i.e.,) naming a file with 2
different names,if the original file is
deleted ,the newly created file is
automatically deleted]
Ln $ln <source Creates a hard link between files elcot@boss:~$ ln test3 test5
filename><new .Here contents is copied to a new elcot@boss:~$ cat test5
filename> file which is saved in a new address. Fri Feb 12 00:07:40 IST 2021 this is third
.[After creating the link (i.e.,) line.
naming a file with 2 different names,
if the original file is deleted ,the
newly created file is not deleted]

II YEAR – VEC
Page 8
2023-2024 SEM: 4 Operating Systems

FILTER COMANDS
NAME SYNTAX DESCRIPTION OUTPUT
Head $head <filename Displays the top 10 lines of the file elcot@boss:~$ head test4
Fri Feb 12 00:07:40 IST 2021 this is third
line.
Head -5 $head -5 <filename> Displays the top 5 lines of the file elcot@boss:~$ head test2
Thu Feb 11 23:48:13 IST 2021 this is the
second line.
Tail $tail <filename> Displays the last 10 lines of the file elcot@boss:~$ tail test3
Fri Feb 12 00:07:40 IST 2021 this is third
line.
Tail –t $tail -5 <filename Displays the last 5 lines of the file elcot@boss:~$ tail -5 test2
Thu Feb 11 23:48:13 IST 2021 this is the
second line.
Paste $paste Paste two files in vertical manner elcot@boss:~$ paste test2 test3
<filename1><filenam Thu Feb 11 23:48:13 IST 2021 this is the
e2> second line. Fri Feb 12 00:07:40 IST
2021 this is third line.
Sort $sort <filename> Sorts the contents of the file in elcot@boss:~$ sort test2
alphabetical order Thu Feb 11 23:48:13 IST 2021 this is the
second line.
Sort –r $sort –r<filename> Sorts the contents of the file in elcot@boss:~$ sort -r test2
reversed alphabetical order Thu Feb 11 23:48:13 IST 2021 this is the
second line.

DIRECTORY COMMANDS
NAME SYNTAX DESCRIPTION OUTPUT
Present $pwd Displays the currently working directory elcot@boss:~$ pwd
working /home/elcot
Directory
Make $ mkdir mkdir creates a new subdirectory inside elcot@boss:~$ mkdir subdir
directory subdir of the directory where you are currently elcot@boss:~$ ls
working Desktop Downloads Music
newfile.txt Public Templates test3 test5
Documents geekfile.txt new Pictures
subdir test2 test4 Videos
Change $ cd Misc cd moves you to another directory. elcot@boss:~$ cd subdir
directory elcot@boss:~/subdir
To change back to your home directory:
To change back to your home directory:
Remove $rmdir To remove a directory. elcot@boss:~$ rmdir subdir
directory filename If the directory contains subdirectory or elcot@boss:~$ ls
files, then remove it first and then remove Desktop Downloads Music
the directory. newfile.txt Public test2 test4 Videos
Documents geekfile.txt new Pictures
Templates test3 test5

II YEAR – VEC
Page 9
2023-2024 SEM: 4 Operating Systems

EX.NO: 1

SHELL PROGRAMS

A. FIND IF A YEAR IS LEAP YEAR OR NOT


AIM:
To Find if a year is leap year or not.

ALGORITHM:
STEP 1: Start
STEP 2: Read year
STEP 3: If year%4=0 and year%100!=0 or if year%4=0 and year%400=0 then go to step 4 else goto step 5
STEP 4: Print a leap year
STEP 5: Print not a leap year
STEP 6: Stop

PROGRAM:

echo "Enter Year:"


read y
year=$y
y=`expr $y % 4`
z=0
if [ $y==$z ]
then
echo "$year is leap year"
else
echo "$year is not leap year"
fi

OUTPUT:

II YEAR – VEC
Page 10
2023-2024 SEM: 4 Operating Systems

B. PERFORM ARITHMETIC OPERATION USING SWITCH STATEMENT


AIM:
To write a Shell Program to perform Arithmetic Operations using Switch – Case

ALGORITHM:
STEP 1: Start
STEP2: Read the two Numbers.
STEP 3: Get the operation choice from the User
STEP 4: Give the expressions for each case and solve them.
STEP 5: Print the Result
STEP 6: Stop

PROGRAM:
echo "Enter Two Numbers"
read a b
echo "What do you want to do? (1 to 5)"
echo "1) Sum"
echo "2) Difference"
echo "3) Product"
echo "4) Quotient"
echo "5) Remainder"
echo "Enter your Choice"
read n
case "$n" in
1) echo "The Sum of $a and $b is `expr $a + $b`";;
2) echo "The Difference between $a and $b is `expr $a - $b`";;
3) echo "The Product of the $a and $b is `expr $a \* $b`";;
4) echo "The Quotient of $a by $b is `expr $a / $b`";;
5) echo "The Remainder of $a by $b is `expr $a % $b`";;
Esac
OUTPUT:

II YEAR – VEC
Page 11
2023-2024 SEM: 4 Operating Systems

C. TO PRINT THE FACTORIAL OF THE NUMBER USING FOR LOOP


AIM:
To find the factorial of a number using loop.

ALGORITHM:
STEP 1: Get a number
STEP 2: Use for loop or while loop to compute the factorial by using the below formula
STEP 3: fact(n) = n * n-1 * n-2 * .. 1
STEP 4: Display the result.

PROGRAM:
echo "Enter a number"
read num
fact=1
for((i=2;i<=num;i++))
{
fact=$((fact * i)) #fact = fact * i
}
echo $fact
OUTPUT

II YEAR – VEC
Page 12
2023-2024 SEM: 4 Operating Systems
D. PRINT THE SUM OF DIGITS USING WHILE LOOP

AIM:
To print sum of digits using while loop.

ALGORITHM:
STEP 1: start
STEP 2: get a number
STEP 3: split each digit from the number using modulo operator
STEP 4: calculate the sum
STEP 5: print the result.
STEP 6: stop.

PROGRAM:
echo "Enter a number"
read num

sum=0

while [ $num -gt 0 ]


do
mod=$((num % 10))
sum=$((sum + mod))
num=$((num / 10))
done

echo $sum

OUTPUT:

II YEAR – VEC
Page 13
2023-2024 SEM: 4 Operating Systems

F. SUM OF N NUMBERS USING DO WHILE LOOP

AIM:
To find the sum if n numbers using do…while loop.

ALGORITHM:

STEP 1: Start.
STEP 2: get N total number
STEP 3: get N number using loop
STEP 4:calculate the sum
STEP 5:print result
STEP 6:end

PROGRAM:
echo -n "Enter N : "
read n
i=0
sum=0
while [ $i -lt $n ]
do
echo -n "Enter number : "
read val
sum=`expr $sum + $val`
i=`expr $i + 1`
done
echo "Sum of entered numbers = $sum"

II YEAR – VEC
Page 14
2023-2024 SEM: 4 Operating Systems

OUTPUT:

II YEAR – VEC
Page 15
2023-2024 SEM: 4 Operating Systems

EX.NO:02

A. PROGRAMS USING SYSTEM CALLS FORK SYSTEM CALL

AIM:
To write a UNIX C program to create a child process from parent process using fork() system
call.

ALGORITHM:
Step 1: Start the program.
Step 2: Invoke a fork() system call to create a child process that is a duplicate of parent process.
Step 3: Display a message. Step 4: Stop the program.

PROGRAM:

1.
#include<stdio.h> #include<unistd.h> int main()
{
fork();
fork();
printf("Hello World\n");
}

2.
#include<stdio.h> #include<unistd.h> int main()
{
fork();
fork();
fork();
printf("Hello World\n");
}

OUTPUT:

II YEAR – VEC
Page 16
2023-2024 SEM: 4 Operating Systems

B. SIMULATION OF FORK, GETPID AND WAIT SYSTEM CALLS

AIM:
To write a UNIX C program simulate fork(),getpid() and wait() system call.

ALGORITHM:
Step 1: Invoke a fork() system call to create a child process that is a duplicate of parent process.
Step 2: Retrieve the process id of parent and child process.
Step 3: If return value of the fork system call=0(i.e.,child process),generate the fibonacii series.
Step 4: If return value of the fork system call>0(i.e.,parent process),wait until the child completes.

PROGRAM:

#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<conio.h> int main()


{
int a=-1,b=1,I,c=a+b,n,pid,cpid; printf("\n enter the number of terms"); scanf("%d",&n);
pid=getpid();
printf("\n parent access id is %d",pid); pid=fork();
cpid=getpid();
printf ("\n child process:%d",cpid); if(pid==0)
{
printf ("\n child is producing Fibonacci series");
for(i=0;i<n;i++)
{
c=a+b;
printf("\n %d", c); a=b;
b=c;
}
printf("\n child ends");
}
else
{
printf("\n parent is waiting for the child to complete"); wait(NULL);
printf ("\n parent ends");
}
}

II YEAR – VEC
Page 17
2023-2024 SEM: 4 Operating Systems

OUTPUT:

C. EXECUTION OF EXECLP SYSTEM CALL

AIM:
To write a UNIX C program to implement execlp() system call.

ALGORITHM:
Step 1:Use fork() system call to create a child process and assigns its id to pid variable.
Step 2: If the pid<0,an error message is displayed.

Step 3:If the pid is equal to zero,execlp() system call is invoked and the child process is
overwritten by the files in the directory.
Step 4:If the pid is greater than zero,display a message.

PROGRAM:

#include<stdio.h> #include<unistd.h> #include<sys/wait.h> int main()


{
int pid; pid=fork(); if(pid<0)
{
fprintf(stderr,"fork failed\n");
}
else if(pid==0)
{
execlp("/bin/ls","ls",NULL);
}
else
II YEAR – VEC
Page 18
2023-2024 SEM: 4 Operating Systems
{
wait(NULL);
printf(" child completes");
}
}

OUTPUT:

II YEAR – VEC
Page 19
2023-2024 SEM: 4 Operating Systems
D. SIMULATION OF SLEEP SYSTEM CALL/ZOOMBIE PROCESS
AIM:
To write a UNIX C program to simulate sleep system call.

ALGORITHM:

Step 1: Invoke fork() system call and assign its return value to the variable p. Step 2:It the value is
equal to zero,display the processid of child process.
Step 3:Invoke sleep() system call,which allows the process to sleep for the specified seconds.
Step 4:If the return value is greater than zero,display the process id of parent process.

PROGRAM:

#include<stdio.h> #include<stdlib.h> int main()


{
int pid; pid=getpid();
printf("\n the current process id is %d",pid); pid=fork();
if(pid==0)
{
printf("\nchild starts"); printf("\nchild completes");
}
else
{
sleep(10);
printf("\n parent process is running"); printf("\n I am in zombie state");
}
}

OUTPUT:

II YEAR – VEC
Page 20
2023-2024 SEM: 4 Operating Systems
E. SIMULATION OF OPENDIR, READDIR SYSTEM CALLS

AIM:
To write a UNIX C program to simulate opendir and readdir system calls.

ALGORITHM
Step 1: Invoke opendir() system call to open a directory by passing command line argument as
parameter.
Step 2: Invoke readdir() system call to read the opened directory.
Step 3:Until the end of directory is encountered, read all the files in directory and display its
directory name,inode number and length of the record.

PROGRAM:

#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<dirent.h>


void main(int argc,char *argv[])
{
DIR *dirname; struct dirent*dir;
dirname=opendir("."); dir=readdir(dirname); while(dir!=NULL)
{
printf("Entry found :%s\n",dir->d_name); printf("Inode number of entry:%d\n",dir->d_ino);
printf("Length of this record:%d\n",dir->d_reclen); getchar();
}
}

OUTPUT:

II YEAR – VEC
Page 21
2023-2024 SEM: 4 Operating Systems
F. SIMULATION OF LS SYSTEM CALLS

AIM:
To write a UNIX C program to simulate ls system call.

ALGORITHM:
Step 1: Invoke opendir() system call to open a directory by passing command line argument as
parameter.
Step 2: Invoke readdir() system call to read the opened directory.
Step 3:Until the end of directory is encountered, read all the files in directory and display its
directory name.

PROGRAM:

#include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<stdio.h>


#include<string.h> #include<dirent.h>
void main(int argc,char *argv[])
{
DIR *dp;struct dirent *link; dp=opendir(".");
printf("contents of directory %s are \n",argv[1]); while((link=readdir(dp))!=0)
printf("%s",link->d_name); closedir(dp);
}

OUTPUT:

II YEAR – VEC
Page 22
2023-2024 SEM: 4 Operating Systems
G. SIMULATION OF GREP SYSTEM CALLS
AIM:
To write a UNIX C program to simulate grep system call.

ALGORITHM:
Step 1: Read the file and pattern to be searched.
Step 2:Open the file in read mode,search the pattern in the file using strstr function. Step 3: If
match of the pattern is found in the file ,display the entire line.

PROGRAM:

#include<stdio.h> #include<string.h> void main()


{
char fn[10],pat[10],temp[200]; FILE *fp;
printf("Enter file name:"); scanf("%s",fn);
printf("\n Enter the pattern::"); scanf("%s",pat);
fp=fopen(fn,"r");
while(!feof(fp))
{
fgets(temp,1000,fp); if(strstr(temp,pat))
{
printf("%s",temp);
}
}
fclose(fp);
}

OUTPUT:

II YEAR – VEC
Page 23
2023-2024 SEM: 4 Operating Systems
H. SIMULATION OF I/O SYSTEM CALLS

AIM:
To write a UNIX C program to simulate I/O system calls such as open, read and write.

ALGORITHM:
Step 1: Start the program.
Step 2: Enter the filename to be opened.
Step 3: Using open () system call, open the file in read only mode.
Step 4: Using read () system call, read the content through the file descriptors and put it in a
buffer.
Step 5: Display the content of the buffer. Step 6: Stop the program.

PROGRAM:

#include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<stdlib.h>


#include<studio.h>
int main()
{
int fd;
char buf1[100],fname[30]; printf("Enter the filename:"); scanf("%s",fname);
fd=open(fname,O_RDONLY); read(fd,buf1,30);
printf("\n The content is%s:",buf1); close(fd);
}

OUTPUT:

II YEAR – VEC
Page 24
2023-2024 SEM: 4 Operating Systems

EX.NO: 3
FCFS , SJF Scheduling

A. FCFS SCHEDULING:
Program:
#include<iostream>
using namespace std;

void findWaitingTime(int processes[], int n, int bt[],


int wt[], int at[])
{
int service_time[n];
service_time[0] = at[0];
wt[0] = 0;

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


{
service_time[i] = service_time[i-1] + bt[i-1];

wt[i] = service_time[i] - at[i];

if (wt[i] < 0)
wt[i] = 0;
}
}

void findTurnAroundTime(int processes[], int n, int bt[],


int wt[], int tat[])
{

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


tat[i] = bt[i] + wt[i];
}

void findavgTime(int processes[], int n, int bt[], int at[])


{
int wt[n], tat[n];

findWaitingTime(processes, n, bt, wt, at);

findTurnAroundTime(processes, n, bt, wt, tat);

cout << "Processes " << " Burst Time " << " Arrival Time "
<< " Waiting Time " << " Turn-Around Time "

II YEAR – VEC
Page 25
2023-2024 SEM: 4 Operating Systems
<< " Completion Time \n";
int total_wt = 0, total_tat = 0;
for (int i = 0 ; i < n ; i++)
{
total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
int compl_time = tat[i] + at[i];
cout << " " << i+1 << "\t\t" << bt[i] << "\t\t"
<< at[i] << "\t\t" << wt[i] << "\t\t "
<< tat[i] << "\t\t " << compl_time << endl;
}

cout << "Average waiting time = "


<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

int main()
{

int processes[] = {1, 2, 3};


int n = sizeof processes / sizeof processes[0];

int burst_time[] = {5, 9, 6};

int arrival_time[] = {0, 3, 6};

findavgTime(processes, n, burst_time, arrival_time);

return 0;
}

II YEAR – VEC
Page 26
2023-2024 SEM: 4 Operating Systems
OUTPUT:

B. SJF SCHEDULING (NON PREEMPTIVE)

PROGRAM:
#include<iostream>
using namespace std;
int mat[10][6];

void swap(int *a, int *b)


{
int temp = *a;
*a = *b;
*b = temp;
}

void arrangeArrival(int num, int mat[][6])


{
for(int i=0; i<num; i++)
{
for(int j=0; j<num-i-1; j++)
{
if(mat[j][1] > mat[j+1][1])
{
for(int k=0; k<5; k++)
{
swap(mat[j][k], mat[j+1][k]);

II YEAR – VEC
Page 27
2023-2024 SEM: 4 Operating Systems
}
}
}
}
}

void completionTime(int num, int mat[][6])


{
int temp, val;
mat[0][3] = mat[0][1] + mat[0][2];
mat[0][5] = mat[0][3] - mat[0][1];
mat[0][4] = mat[0][5] - mat[0][2];

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


{
temp = mat[i-1][3];
int low = mat[i][2];
for(int j=i; j<num; j++)
{
if(temp >= mat[j][1] && low >= mat[j][2])
{
low = mat[j][2];
val = j;
}
}
mat[val][3] = temp + mat[val][2];
mat[val][5] = mat[val][3] - mat[val][1];
mat[val][4] = mat[val][5] - mat[val][2];
for(int k=0; k<6; k++)
{
swap(mat[val][k], mat[i][k]);
}
}
}

int main()
{
int num, temp;

cout<<"Enter number of Process: ";


cin>>num;

cout<<"...Enter the process ID...\n";


for(int i=0; i<num; i++)
{
cout<<"...Process "<<i+1<<"...\n";

II YEAR – VEC
Page 28
2023-2024 SEM: 4 Operating Systems
cout<<"Enter Process Id: ";
cin>>mat[i][0];
cout<<"Enter Arrival Time: ";
cin>>mat[i][1];
cout<<"Enter Burst Time: ";
cin>>mat[i][2];
}

cout<<"Before Arrange...\n";
cout<<"Process ID\tArrival Time\tBurst Time\n";
for(int i=0; i<num; i++)
{
cout<<mat[i][0]<<"\t\t"<<mat[i][1]<<"\t\t"<<mat[i][2]<<"\n";
}

arrangeArrival(num, mat);
completionTime(num, mat);
cout<<"Final Result...\n";
cout<<"Process ID\tArrival Time\tBurst Time\tWaiting Time\tTurnaround Time\n";
for(int i=0; i<num; i++)
{

cout<<mat[i][0]<<"\t\t"<<mat[i][1]<<"\t\t"<<mat[i][2]<<"\t\t"<<mat[i][4]<<"\t\t"<<mat[i
][5]<<"\n";
}
}

II YEAR – VEC
Page 29
2023-2024 SEM: 4 Operating Systems
OUTPUT:

II YEAR – VEC
Page 30
2023-2024 SEM: 4 Operating Systems
C. SJF SCHEDULING (PREEMPTIVE):
PROGRAM:
#include<iostream>
using namespace std;

struct Process {
int pid;
int bt;
int art;
};

void findWaitingTime(Process proc[], int n,


int wt[])
{
int rt[n];

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


rt[i] = proc[i].bt;
int INT_MAX;
int complete = 0, t = 0, minm = INT_MAX;
int shortest = 0, finish_time;
bool check = false;

while (complete != n) {

for (int j = 0; j < n; j++) {


if ((proc[j].art <= t) &&
(rt[j] < minm) && rt[j] > 0) {
minm = rt[j];
shortest = j;
check = true;
}
}

if (check == false) {
t++;
continue;
}

rt[shortest]--;

minm = rt[shortest];
if (minm == 0)
minm = INT_MAX;

if (rt[shortest] == 0) {
II YEAR – VEC
Page 31
2023-2024 SEM: 4 Operating Systems

complete++;
check = false;

finish_time = t + 1;

wt[shortest] = finish_time -
proc[shortest].bt -
proc[shortest].art;

if (wt[shortest] < 0)
wt[shortest] = 0;
}
t++;
}
}

void findTurnAroundTime(Process proc[], int n,


int wt[], int tat[])
{
for (int i = 0; i < n; i++)
tat[i] = proc[i].bt + wt[i];
}

void findavgTime(Process proc[], int n)


{
int wt[n], tat[n], total_wt = 0,
total_tat = 0;

findWaitingTime(proc, n, wt);

findTurnAroundTime(proc, n, wt, tat);

cout << "Processes ";


cout << " Burst time ";
cout << " Waiting time ";
cout << " Turn around time\n";

for (int i = 0; i < n; i++) {


total_wt = total_wt + wt[i];
total_tat = total_tat + tat[i];
cout << " " << proc[i].pid << "\t\t"
<< proc[i].bt << "\t\t " << wt[i]
<< "\t\t " << tat[i] << endl;
}

II YEAR – VEC
Page 32
2023-2024 SEM: 4 Operating Systems
cout << "\nAverage waiting time = "
<< (float)total_wt / (float)n;
cout << "\nAverage turn around time = "
<< (float)total_tat / (float)n;
}

int main()
{
Process proc[] = { { 1, 6, 1 }, { 2, 8, 1 },
{ 3, 7, 2 }, { 4, 3, 3 } };
int n = sizeof(proc) / sizeof(proc[0]);

findavgTime(proc, n);
return 0;
}

OUTPUT:

II YEAR – VEC
Page 33
2023-2024 SEM: 4 Operating Systems

D. Priority scheduling (Non-preemptive)

PROGRAM:

#include <bits/stdc++.h>
using namespace std;
#define totalprocess 5
struct process
{
int at,bt,pr,pno;
};

process proc[50];
bool comp(process a,process b)
{
if(a.at == b.at)
{
return a.pr<b.pr;
}
else
{
return a.at<b.at;
}
}

void get_wt_time(int wt[])


{

int service[50];
service[0] = proc[0].at;
wt[0]=0;

for(int i=1;i<totalprocess;i++)
{
service[i]=proc[i-1].bt+service[i-1];

wt[i]=service[i]-proc[i].at;
if(wt[i]<0)
{
wt[i]=0;
}
}
II YEAR – VEC
Page 34
2023-2024 SEM: 4 Operating Systems

}
void get_tat_time(int tat[],int wt[])
{

for(int i=0;i<totalprocess;i++)
{
tat[i]=proc[i].bt+wt[i];
}

void findgc()
{
int wt[50],tat[50];
double wavg=0,tavg=0;
get_wt_time(wt);
get_tat_time(tat,wt);
int stime[50],ctime[50];
stime[0] = proc[0].at;
ctime[0]=stime[0]+tat[0];

for(int i=1;i<totalprocess;i++)
{
stime[i]=ctime[i-1];
ctime[i]=stime[i]+tat[i]-wt[i];
}

cout<<"Process_no\tStart_time\tComplete_time\tTurn_Around_Time\tWaiting_Time"<<endl;

for(int i=0;i<totalprocess;i++)
{
wavg += wt[i];
tavg += tat[i];

cout<<proc[i].pno<<"\t\t"<<
stime[i]<<"\t\t"<<ctime[i]<<"\t\t"<<
tat[i]<<"\t\t\t"<<wt[i]<<endl;
}

cout<<"Average waiting time is : ";


cout<<wavg/(float)totalprocess<<endl;
cout<<"average turnaround time : ";
cout<<tavg/(float)totalprocess<<endl;
II YEAR – VEC
Page 35
2023-2024 SEM: 4 Operating Systems
}
int main()
{
int arrivaltime[] = { 1, 2, 3, 4, 5 };
int bursttime[] = { 3, 5, 1, 7, 4 };
int priority[] = { 3, 4, 1, 7, 8 };

for(int i=0;i<totalprocess;i++)
{
proc[i].at=arrivaltime[i];
proc[i].bt=bursttime[i];
proc[i].pr=priority[i];
proc[i].pno=i+1;
}
sort(proc,proc+totalprocess,comp);
findgc();
return 0;
}

OUTPUT:

E. Priority scheduling (Preemtive)

PROGRAM:

#include <iostream>
#include <algorithm>
#include <iomanip>
#include <string.h>
using namespace std;

struct process {
int pid;
int arrival_time;
int burst_time;

II YEAR – VEC
Page 36
2023-2024 SEM: 4 Operating Systems
int priority;
int start_time;
int completion_time;
int turnaround_time;
int waiting_time;
int response_time;
};

int main() {

int n;
struct process p[100];
float avg_turnaround_time;
float avg_waiting_time;
float avg_response_time;
float cpu_utilisation;
int total_turnaround_time = 0;
int total_waiting_time = 0;
int total_response_time = 0;
int total_idle_time = 0;
float throughput;
int burst_remaining[100];
int is_completed[100];
memset(is_completed,0,sizeof(is_completed));

cout << setprecision(2) << fixed;

cout<<"Enter the number of processes: ";


cin>>n;

for(int i = 0; i < n; i++) {


cout<<"Enter arrival time of process "<<i+1<<": ";
cin>>p[i].arrival_time;
cout<<"Enter burst time of process "<<i+1<<": ";
cin>>p[i].burst_time;
cout<<"Enter priority of the process "<<i+1<<": ";
cin>>p[i].priority;
p[i].pid = i+1;
burst_remaining[i] = p[i].burst_time;
cout<<endl;
}

int current_time = 0;
int completed = 0;
int prev = 0;

II YEAR – VEC
Page 37
2023-2024 SEM: 4 Operating Systems
while(completed != n) {
int idx = -1;
int mx = -1;
for(int i = 0; i < n; i++) {
if(p[i].arrival_time <= current_time && is_completed[i] == 0) {
if(p[i].priority > mx) {
mx = p[i].priority;
idx = i;
}
if(p[i].priority == mx) {
if(p[i].arrival_time < p[idx].arrival_time) {
mx = p[i].priority;
idx = i;
}
}
}
}

if(idx != -1) {
if(burst_remaining[idx] == p[idx].burst_time) {
p[idx].start_time = current_time;
total_idle_time += p[idx].start_time - prev;
}
burst_remaining[idx] -= 1;
current_time++;
prev = current_time;

if(burst_remaining[idx] == 0) {
p[idx].completion_time = current_time;
p[idx].turnaround_time = p[idx].completion_time - p[idx].arrival_time;
p[idx].waiting_time = p[idx].turnaround_time - p[idx].burst_time;
p[idx].response_time = p[idx].start_time - p[idx].arrival_time;

total_turnaround_time += p[idx].turnaround_time;
total_waiting_time += p[idx].waiting_time;
total_response_time += p[idx].response_time;

is_completed[idx] = 1;
completed++;
}
}
else {
current_time++;
}
}

II YEAR – VEC
Page 38
2023-2024 SEM: 4 Operating Systems
int min_arrival_time = 10000000;
int max_completion_time = -1;
for(int i = 0; i < n; i++) {
min_arrival_time = min(min_arrival_time,p[i].arrival_time);
max_completion_time = max(max_completion_time,p[i].completion_time);
}

avg_turnaround_time = (float) total_turnaround_time / n;


avg_waiting_time = (float) total_waiting_time / n;
avg_response_time = (float) total_response_time / n;
cpu_utilisation = ((max_completion_time - total_idle_time) / (float) max_completion_time )*100;
throughput = float(n) / (max_completion_time - min_arrival_time);

cout<<endl<<endl;

cout<<"#P\t"<<"AT\t"<<"BT\t"<<"PRI\t"<<"ST\t"<<"CT\t"<<"TAT\t"<<"WT\t"<<"RT\t"<<"\n"<<endl;

for(int i = 0; i < n; i++) {

cout<<p[i].pid<<"\t"<<p[i].arrival_time<<"\t"<<p[i].burst_time<<"\t"<<p[i].priority<<"\t"<<p[i].start_tim
e<<"\t"<<p[i].completion_time<<"\t"<<p[i].turnaround_time<<"\t"<<p[i].waiting_time<<"\t"<<p[i].respo
nse_time<<"\t"<<"\n"<<endl;
}
cout<<"Average Turnaround Time = "<<avg_turnaround_time<<endl;
cout<<"Average Waiting Time = "<<avg_waiting_time<<endl;
cout<<"Average Response Time = "<<avg_response_time<<endl;
cout<<"CPU Utilization = "<<cpu_utilisation<<"%"<<endl;
cout<<"Throughput = "<<throughput<<" process/unit time"<<endl;

II YEAR – VEC
Page 39
2023-2024 SEM: 4 Operating Systems
OUTPUT:

II YEAR – VEC
Page 40
2023-2024 SEM: 4 Operating Systems
F. ROUND ROBIN SCHEDULING

PROGRAM:

#include<stdio.h>
#include<conio.h>

void main()
{

int i, NOP, sum=0,count=0, y, quant, wt=0, tat=0, at[10], bt[10], temp[10];


float avg_wt, avg_tat;
printf(" Total number of process in the system: ");
scanf("%d", &NOP);
y = NOP;

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


{
printf("\n Enter the Arrival and Burst time of the Process[%d]\n", i+1);
printf(" Arrival time is: \t");
scanf("%d", &at[i]);
printf(" \nBurst time is: \t");
scanf("%d", &bt[i]);
temp[i] = bt[i];
}

printf("Enter the Time Quantum for the process: \t");


scanf("%d", &quant);

printf("\n Process No \t\t Burst Time \t\t TAT \t\t Waiting Time ");
for(sum=0, i = 0; y!=0; )
{
if(temp[i] <= quant && temp[i] > 0)
{
sum = sum + temp[i];
temp[i] = 0;
count=1;
}
else if(temp[i] > 0)
{
temp[i] = temp[i] - quant;
sum = sum + quant;
}
if(temp[i]==0 && count==1)
{
II YEAR – VEC
Page 41
2023-2024 SEM: 4 Operating Systems
y--;
printf("\nProcess No[%d] \t\t %d\t\t\t\t %d\t\t\t %d", i+1, bt[i], sum-at[i], sum-at[i]-bt[i]);
wt = wt+sum-at[i]-bt[i];
tat = tat+sum-at[i];
count =0;
}
if(i==NOP-1)
{
i=0;
}
else if(at[i+1]<=sum)
{
i++;
}
else
{
i=0;
}
}

avg_wt = wt * 1.0/NOP;
avg_tat = tat * 1.0/NOP;
printf("\n Average Turn Around Time: \t%f", avg_wt);
printf("\n Average Waiting Time: \t%f", avg_tat);
getch();
}

II YEAR – VEC
Page 42
2023-2024 SEM: 4 Operating Systems
OUTPUT:

II YEAR – VEC
Page 43
2023-2024 SEM: 4 Operating Systems

To write a UNIX C program to implement producer consumer problem using semaphores

Step1: Start the program.


Step2: Initialize mutex to1, full to 0and empty ton.
Step3: If mutex =1and empty is greater than zero,invoke producer function.Otherwise display the message
buffer is full.
Step4: If mutex =1and full is greater than zero, invoke consumer function.Otherwise display the message
buffer is empty.
Step5: In producer function,produce an item wait for empty buffer and mutex .If any buffer is empty add
the produced item to the buffer and signal mutex and full buffer.
Step6: In consumer function,wait for full buffer and mutex.If any buffer is full,remove the item from the
buffer to the consumer. Signal mutex and empty buffer.
Step7: Stop the program.

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#define buffSize 1000

struct
{
pthread_mutex_t mutex;
int buff[buffSize];
int producedCount;
int consumedCount;
}shared={PTHREAD_MUTEX_INITIALIZER};
void *produce(void *arg);
void *consume(void *arg);
void main()
{
int prodThreads,consThreads,i;
printf(“\nEnter the no of Producers: “);
scanf(“%d”,&prodThreads);
II YEAR – VEC
Page 44
2023-2024 SEM: 4 Operating Systems
printf(“\nEnter the no of Consumers: “);
scanf(“%d”,&consThreads);
int producerArr[prodThreads],consumerArr[consThreads];
pthread_t producer[prodThreads],consumer[consThreads];
pthread_setconcurrency(prodThreads+consThreads);

for(i=0;i<prodThreads;i++)
{
producerArr[i]=0;
pthread_create(&producer[i],NULL,produce,&producerArr[i]);
}

for(i=0;i<consThreads;i++)
{
consumerArr[i]=0;
pthread_create(&consumer[i],NULL,consume,&consumerArr[i]);
}

for(i=0;i<prodThreads;i++)
{
pthread_join(producer[i],NULL);
printf(“\nThe Producer (%d) produced: [%d] Items”,i,producerArr[i]);
sleep(1);
}
printf(“\n”);

for(i=0;i<consThreads;i++)
{
pthread_join(consumer[i],NULL);
printf(“\nThe Consumer (%d) Consumed: [%d] Items”,i,consumerArr[i]);
sleep(1);
}
}

void *produce(void *arg)


{
while(1)
{
pthread_mutex_lock(&shared.mutex);
if(shared.producedCount<buffSize)
{
shared.producedCount++;
*((int *)arg) += 1;
pthread_mutex_unlock(&shared.mutex);
II YEAR – VEC
Page 45
2023-2024 SEM: 4 Operating Systems
}
else
{
pthread_mutex_unlock(&shared.mutex);
return NULL;
}
}
}
void *consume(void *arg)
{
while(1)
{
pthread_mutex_lock(&shared.mutex);
if(shared.consumedCount<shared.producedCount)
{
shared.consumedCount++;
*((int *)arg) += 1;
pthread_mutex_unlock(&shared.mutex);
}
else
{
pthread_mutex_unlock(&shared.mutex);
if (shared.consumedCount>=buffSize)
return NULL;
}

}
}

OUTPUT
Test Case
gcc -lpthread producerconsumer.c
./a.out
Enter the no of Producers: 4
Enter the no of Consumers: 3

OUTPUT
The Producer (0) produced: [252] Items
The Producer (1) produced: [415] Items
The Producer (2) produced: [136] Items
The Producer (3) produced: [197] Items

The Consumer (0) Consumed: [703] Items


The Consumer (1) Consumed: [260] Items

II YEAR – VEC
Page 46
2023-2024 SEM: 4 Operating Systems
The Consumer (2) Consumed: [37] Items

B. Inter-process communication

To write a UNIX C program to implement inter-process communication using pipes.

Step1: Create a pipe structure using pipe() system call. Pipe() system call returns 2
File descriptors fd[0] and fd[1].fd[0] is opened for reading and fd[1] is opened for writing.
Step2: Create a child process using fork() system call.
Step3: Close the read end of the parent process using close().
Step4: Write the data in the pipe using write().
Step5: Close the write end of the child process using close().
Step6: Read the data in the pipe using read()..

// C program to illustrate
// pipe system call in C #include <stdio.h> #include <unistd.h> #define MSGSIZE 16
char* msg1 = "hello, world #1"; char* msg2 = "hello, world #2"; char* msg3 = "hello, world #3";

int main()
{
char inbuf[MSGSIZE]; int p[2], i;

if (pipe(p) < 0)
exit(1);

/* continued */
/* write pipe */

write(p[1], msg1, MSGSIZE); write(p[1], msg2, MSGSIZE); write(p[1], msg3, MSGSIZE);

for (i = 0; i < 3; i++) {


/* read pipe */ read(p[0], inbuf,
MSGSIZE);
printf("% s\n", inbuf);
}
return 0;
}

II YEAR – VEC
Page 47
2023-2024 SEM: 4 Operating Systems

Output:

II YEAR – VEC
Page 48
2023-2024 SEM: 4 Operating Systems

TowriteaUNIXCprogramtoimplementinterprocesscommunicationusingshared
memory.

Step1: Start the program.


Step2: Create the shared memory for parent process using shm get() system call.
Step3: Attach the shared memory to the child process.
Step4: Create child process using fork ().
Step5: Parent process writes the content in the shared memory.
Step6: The child process reads the content from the shared memory.
Step7: Detach and release the shared memory.
Step8: Stop the program.

II YEAR – VEC
Page 49
2023-2024 SEM: 4 Operating Systems

OUTPUT
shared memory is 0
Process attached at 0x7fca3c925000
Enter some data to write to shared memory HELLO WORLD
You wrote : HELLO WORLD

Thus, a UNIX C program to implement interprocess communication using shared memory is


executed successfully.

II YEAR – VEC
Page 50
2023-2024 SEM: 4 Operating Systems
EX.NO:5

Implementation of Bankers algorithm

PROGRAM:

#include <stdio.h>
int main()
{

int n, m, i, j, k;
n = 5;
m = 3;
int alloc[5][3] = { { 0, 1, 0 },
{ 2, 0, 0 },
{ 3, 0, 2 },
{ 2, 1, 1 },
{ 0, 0, 2 } };

int max[5][3] = { { 7, 5, 3 },
{ 3, 2, 2 },
{ 9, 0, 2 },
{ 2, 2, 2 },
{ 4, 3, 3 } };

int avail[3] = { 3, 3, 2 };

int f[n], ans[n], ind = 0;


for (k = 0; k < n; k++) {
f[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (f[i] == 0) {

int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
II YEAR – VEC
Page 51
2023-2024 SEM: 4 Operating Systems
break;
}
}

if (flag == 0) {
ans[ind++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
f[i] = 1;
}
}
}
}

printf("Following is the SAFE Sequence\n");


for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);

return (0);

OUTPUT:

II YEAR – VEC
Page 52
2023-2024 SEM: 4 Operating Systems

To write a UNIX C program to create the thread.

Step1:Start the program Step2:Include the header file pthread.h


Step3:Create the threadID by using the pthread_create() function to createtwo threads
Step4: The starting function for both the threads is kept same.
Step 5: Inside the function ‘createthread()’, the thread uses pthread_self() and
pthread_equal()functions to identify whether the executing thread is the first one or the second one
as created.Step 6: Also, Inside the same function ‘createthread ()’ a for loop is run so as to
simulate sometime consuming work.
Step 7: Compile the program with the–lpthread.Step8: Stop the program.

#include <pthread.h>
#include <stdio.h> #include
<stdlib.h> int MAX = 10;
int count = 1; pthread_mutex_t
thr; pthread_cond_t cond; void
*even(void *arg){
while(count < MAX) {
pthread_mutex_lock(&thr);
while(count % 2 != 0) {
pthread_cond_wait(&cond, &thr);
}
printf("%d ", count++);

}
pthread_exit(0);
}
void *odd(void *arg){
while(count < MAX) {
pthread_mutex_lock(&thr);
while(count % 2 != 1) {
pthread_cond_wait(&cond, &thr);
}

printf("%d ", count++);

II YEAR – VEC
Page 53
2023-2024 SEM: 4 Operating Systems

pthread_mutex_unlock(&thr);
pthread_cond_signal(&cond);
\
}
pthread_exit(0);
}
int main(){

pthread_create(&thread1, 0, &even, NULL);


pthread_create(&thread2, 0, &odd, NULL);

return 0;

RESULT

Thus a UNIX C program to create the thread was executed successfully.

II YEAR – VEC
Page 54
2023-2024 SEM: 4 Operating Systems

To write a C Program to implement best fit memory allocation method

Step1: Input memory blocks and processes with sizes.


Step2: Initialize all memory blocks as free.
Step 3: Start by picking each process and find the minimum block size that can be assigned to
current process i.e., find min(blockSize[1], blockSize[2],…..blockSize[n]) > processSize[current], if
found then assign it to the current process.
Step 4: If not then leave that process and keep checking the further processes.

#include<stdio.h>
#include<process.h> void
main()
{
int a[20],p[20],i,j,n,m; printf("Enter no of
Blocks.\n"); scanf("%d",&n); for(i=0;i<n;i++)
{
printf("Enter the %dst Block size:",i); scanf("%d",&a[i]);
}
printf("Enter no of Process.\n");
scanf("%d",&m); for(i=0;i<m;i++)
{
printf("Enter the size of %dst Process:",i); scanf("%d",&p[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{ if(p[j]<=a[i])
{
printf("The Process %d allocated to %d\n",j,a[i]);

II YEAR – VEC
Page 55
2023-2024 SEM: 4 Operating Systems
{ if(p[j]!=10000)
{
} p[j]=10000;
} break;
}
for(j=0;j<m;j++)
printf("The Process %d is not allocated\n",j);
}
}
}

Enter no of Blocks. 1
Enter the 0st Block size:2 Enter
no of Process.
5
Enter the size of 0st Process:1 Enter
the size of 1st Process:5 Enter the size
of 2st Process:2 Enter the size of 3st
Process:4 Enter the size of 4st
Process:3 The Process 0 allocated to 2
The Process 1 is not allocated The
Process 2 is not allocated The Process
3 is not allocated The Process 4 is not
allocated

Thus a C program to implement best fit memory allocation method was executedsuccessfully

II YEAR – VEC
Page 56
2023-2024 SEM: 4 Operating Systems

To write a UNIX C program to implement paging memory management scheme.

Step1: Start the program


Step2: Enter the number of pages and page size.
Step3: Calculate the limit of logical address.
Step4: Enter the logical address within the limit.
Step5: Enter the page table entries (i.e.) the page number and the relevant frame
number.
Step6: For the logical address, calculate the page number and frame number.
Step7: Calculate the physical address.
Step8: Stop the program.

II YEAR – VEC
Page 57
2023-2024 SEM: 4 Operating Systems

Memory is Full
Enter Logical Address to find Physical Address Enter process no. and page number and offset -- 2
3
60
RESULTS
Thus C program to implement paging memory management scheme has been executed succefully

II YEAR – VEC
Page 58
2023-2024 SEM: 4 Operating Systems

To write a C Program to implement first fit memory allocation method

Step1:Input memory blocks with size and processes with size.


Step 2: Initialize all memory blocks as free.
Step 3: Start by picking each process and check if it can be assigned to current block. Step 4:
If size-of-process <= size-of-block if yes then assign and check for next process. Step 5: If
not then keep checking the further blocks.
PROGRAM:

II YEAR – VEC
Page 59
2023-2024 SEM: 4 Operating Systems

Enter no. of blocks: 1 Enter size of


each block: 1

Enter no. of processes: 1 Enter size of

each process: 1

Block no. size process no. size


1 1 1 1

Thus a C program to implement first fit memory allocation method was executed successfully

II YEAR – VEC
Page 60
2023-2024 SEM: 4 Operating Systems

To write a C Program to implement worst fit memory allocation method

Step1: Input memory blocks with size and processes with size.
Step2: Initialize all memory blocks as free.
Step3: Start by picking each process and check if it can be assigned to current block.
Step4: If size-of-process <= size-of-block if yes then assign and check for next process.
Step5: If not then keep checking the further blocks.

II YEAR – VEC
Page 61
2023-2024 SEM: 4 Operating Systems

Enter the Total Number of Blocks: 2


Enter the Total Number of Files: 1

Enter the Size of the Blocks:


Block No.[1]: 5
Block No.[2]: 3
Enter the Size of the Files:
File No.[1]: File 2
Number File Size Block Number Block Size Fragment
0 2 1 3 1

Thus a C program to implement worst fit memory allocation method was executed successfully.

II YEAR – VEC
Page 62
2023-2024 SEM: 4 Operating Systems
EX.NO:9a IMPLMENTATION OF FIFO PAGE REPLACEMENT
ALGORITHM.

To write a UNIX C program to implement FIFO page replacement algorithm.

Step1: Start the process


Step2: Declare the size with respect to page length
Step3: Check the need of replacement from the page to memory
Step4: Check the need of replacement from old page to new page in memory
Step5: Format queue to hold all pages
Step6: Insert the page require memory into the queue
Step7: Check for bad replacement and page fault
Step8: Get the number of processes to be inserted
Step9: Display the values
Step10: Stop the process

#include<stdio.h>
intmain()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;printf("\nE
NTERTHENUMBEROFPAGES:\n");
scanf("%d",&n);
printf("\nENTERTHEPAGENUMBER:\n");
for(i=1;i<=n;i++)s
canf("%d",&a[i]);
printf("\nENTERTHE NUMBEROFFRAMES:");
scanf("%d",&no)
;for(i=0;i<no;i++
)frame[i]=-1; j=0;
printf("\trefstring\tpageframes\n");f
or(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;

II YEAR – VEC
Page 63
2023-2024 SEM: 4 Operating Systems

if(avail==0)
{
frame[j]=a[i];j=(j+
1)%no;count++;fo
r(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("PageFaultIs%d",count);r
eturn0;
}

1 1 -1
2 1 2
3 3 2
4 3 4
5 5 4
Page Fault Is
5

Thus a UNIX C program to implement FIFO page replacement is executed successfully.

II YEAR – VEC
Page 64
2023-2024 SEM: 4 Operating Systems

To write UNIX C program a program to implement LRU page replacement algorithm

Step1: Start the process


Step2: Declare the size
Step3: Get the number of Pages to be inserted
Step4: Get the value
Step5: Declare counter and stack
Step6: Select the least recently used page by counter value
Step7: Stack them according to the selection.
Step8: Display the values
Step9: Stop the process

#include<stdio.h>
main()
{
intq[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20]; printf("Enterno
of pages:");
scanf("%d",&n);
printf("Enterthereferencestring:");f
or(i=0;i<n;i++)scanf("%d",&p[i]);
printf("Enternoofframes:");s
canf("%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++;

II YEAR – VEC
Page 65
2023-2024 SEM: 4 Operating Systems

}
if(c1==f)
{c+
+;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)pri
ntf("\t%d",q[j]);pri
ntf("\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]++;
elsebr eak;
}
}
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");
}
}

II YEAR – VEC
Page 66
2023-2024 SEM: 4 Operating Systems

}
printf("\nThenoofpage faultsis%d",c);

}
}

2
2 1
2 1 3
2 1 3 4

Thus a UNIX C program to implement LRU page replacement is executed successfully

II YEAR – VEC
Page 67
2023-2024 SEM: 4 Operating Systems

To write a UNIX C program to implement LFU page replacement algorithm.

Step1: Start the program


Step2: Declare the size
Step3: Get the number of frames to be inserted
Step4: Get the number of pages to be inserted and get the value.
Step5: Get the page sequence
Step6: Select the least frequently used page by counter value
Step7: Stack them according to the selection.
Step8: Display the values
Step9: Stop the process

PROGRAM:
#include<stdio.h> #include<conio.h> main()
{
int rs[50], i, j, k, m, f, cntr[20], a[20], min, pf=0; clrscr();
printf("\nEnter number of page references -- "); scanf("%d",&m);
printf("\nEnter the reference string -- "); for(i=0;i<m;i++)
scanf("%d",&rs[i]);
printf("\nEnter the available no. of frames -- "); scanf("%d",&f);
for(i=0;i<f;i++)
{
cntr[i]=0; a[i]=-1;
}
printf(“\nThe Page Replacement Process is – \n“); for(i=0;i<m;i++)
{
for(j=0;j<f;j++) if(rs[i]==a[j])
{
cntr[j]++;

break;

if(j==f)
{ min = 0; for(k=1;k<f;k++)
if(cntr[k]<cntr[min]) min=k;
II YEAR – VEC
Page 68
2023-2024 SEM: 4 Operating Systems

a[min]=rs[i]; cntr[min]=1; pf++;


}
printf("\n"); for(j=0;j<f;j++) printf("\t%d",a[j]); if(j==f)

}
printf(“\tPF No. %d”,pf);}
printf("\n\n Total number of page faults -- %d",pf); getch();
}

OUTPUT:
The Page Replacement Process is –

1 -1 -1 PF No. 1
1 2 -1 PF No. 2
1 2 3 PF No. 3
2 3 PF No. 4
2 3 PF No. 5
523
523
5 2 1 PF No. 6
5 2 4 PF No. 7
5 2 3 PF No. 8

Total number of page faults --8

Thus a UNIX C program to implement LFU page replacement is


executed successfully.

II YEAR – VEC
Page 69
2023-2024 SEM: 4 Operating Systems

To write a C Program to simulate FCFS disk scheduling algorithm

#include<conio.h>
#include<stdio.h>
int main()
{
int i,j,sum=0,n;
int ar[20],tm[20];
int disk

clrscr();
printf("enter number of location\t");
scanf("%d",&n);
printf("enter position of head\t");
scanf("%d",&disk);
printf("enter elements of disk queue\n");
for(i=0;i<n;i++)
{
scanf("%d",&ar[i]);
tm[i]=disk-ar[i];
if(tm[i]<0)
{
tm[i]=ar[i]-disk;
}

II YEAR – VEC
Page 70
2023-2024 SEM: 4 Operating Systems

disk=ar[i];
sum=sum+tm[i];
}

/*for(i=0;i<n;i++)
{
printf("\n%d",tm[i]);
} */

printf("\nmovement of total cylinders %d",sum);


getch();
return 0;
}

Output:
enter number of location 8
enter position of head 53
enter elements of disk queue

98

183

37

122

14

124

65

67

movement of total cylinders 640

Thus a C program to simulate FCFS disk scheduling algorithm is executed successfully

II YEAR – VEC
Page 71
2023-2024 SEM: 4 Operating Systems

To write a C Program to simulate SCAN disk scheduling algorithm

DESCRIPTION

In the SCAN algorithm, the disk arm starts at one end, and moves towards the other end, servicing
requests as it reaches each cylinder, until it gets to the other end of the disk. At the other end, the
direction of head movement is reversed, and servicing continues. The head continuously scans back
and forth across the disk.

PROGRAM

#include<conio.h
>
#include<stdio.h
>
int main()
{
int
i,j,sum=0,n;
int d[20];
int disk; //loc of
head int temp,max;
int dloc; //loc of disk in array printf("enter
number of location\t"); scanf("%d",&n);
printf("enter position of head\t");
scanf("%d",&disk);
printf("enter elements of disk queue\n");
for(i=0;i<n;i++)
{
scanf("%d",&d[i]);
}

II YEAR – VEC
Page 72
2023-2024 SEM: 4 Operating Systems

d[n]=di
sk;
n=n+1;
for(i=0;i<n;i++) // sorting disk locations
{
for(j=i;j<n;j++)
{
if(d[i]>d[j])
{
temp=d[i]; d[i]=d[j];
d[j]=temp;
}
}

}
max=d[n];
for(i=0;i<n;i++) // to find loc of disc in array
{
if(disk==d[i]) { dloc=i; break; }
}
for(i=dloc;i>=0;i--)
{
printf("%d -->",d[i]);
}
printf("0 -->");
for(i=dloc+1;i<n
;i++)
{
printf("%d-->",d[i]);
}
sum=disk+max;
printf("\nmovement of total cylinders %d",sum);
getch();
return 0;
}

II YEAR – VEC
Page 73
2023-2024 SEM: 4 Operating Systems

OUTPUT
enter number of location 5
enter position of head 2
enter elements of disk
queue 1
2
3
4
5
2 -->1 -->0 -->2-->3-->4-->5-->

movement of total cylinders -604770503

RESULT

II YEAR – VEC
Page 74
2023-2024 SEM: 4 Operating Systems

AIM
To write a C Program to simulate C-SCAN disk scheduling algorithm

C-SCAN is a variant of SCAN designed to provide a more uniform wait time. Like SCAN, C-SCAN moves
the head from one end of the disk to the other, servicing requests along the way. When the head reaches the
other end, however, it immediately returns to the beginning of the disk without servicing any requests on the
return trip.

PROGRAM

II YEAR – VEC
Page 75
2023-2024 SEM: 4 Operating Systems

{
queue1[temp1] = temp; temp1++;
}
else
{
queue2[temp2] = temp; temp2++;
}
}

for (i = 0; i < temp1 - 1; i++)


{
for (j = i + 1; j < temp1; j++)
{
if (queue1[i] > queue1[j])
{
temp = queue1[i]; queue1[i] = queue1[j];
queue1[j] = temp;
}
}
}

for (i = 0; i < temp2 - 1; i++)


{
for (j = i + 1; j < temp2; j++)
{
if (queue2[i] > queue2[j])
{
temp = queue2[i]; queue2[i] = queue2[j];
queue2[j] = temp;
}
}

II YEAR – VEC
Page 76
2023-2024 SEM: 4 Operating Systems

for (i = 1, j = 0; j < temp1; i++, j++)


{
queue[i] = queue1[j];
}

queue[i] = maxrange; queue[i + 1] =

0;

for (i = temp1 + 3, j = 0; j < temp2; i++, j++)


{
queue[i] = queue2[j];
}

queue[0] = headposition;

for (j = 0; j <= n + 1; j++)


{
difference = absoluteValue(queue[j + 1] - queue[j]); seek = seek + difference;

printf("Disk head moves from position %d to %d with Seek %d \n", queue[j], queue[j + 1], difference);
}

averageSeekTime = seek / (float)n;

printf("Total Seek Time= %d\n", seek); printf("Average Seek Time= %f\n",


averageSeekTime);
}

int absoluteValue(int x)

II YEAR – VEC
Page 77
2023-2024 SEM: 4 Operating Systems

Thus a C program to simulate C-SCAN disk scheduling algorithm is executed successfully.

II YEAR – VEC
Page 78
2023-2024 SEM: 4 Operating Systems

To write a UNIX C Program to implement single level directory file organization

Step1:Start the process.


Step 2: Get the number of directories.Step 3:
Get the name of the directory.Step4:Display
the size of the directory.
Step5: Display the number and name of the files which are presented in the directory.
Step6: Stop the process.

#include<stdio.h>
#include<conio.h>
#include<string.h> void
main()
{
int nf=0,i=0,j=0,ch;
char mdname[10],fname[10][10],name[10]; clrscr();
printf("Enter the directory name:");
scanf("%s",mdname);
printf("Enter the number of files:");
scanf("%d",&nf);
do
{
printf("Enter file name to be created:");
scanf("%s",name);
for(i=0;i<nf;i++)
{
if(!strcmp(name,fname[i])) break;
}
if(i==nf)

II YEAR – VEC
Page 79
2023-2024 SEM: 4 Operating Systems

{
strcpy(fname[j++],name); nf++;
}
else
printf("There is already %s\n",name);
printf("Do you want to enter another file(yes - 1 or no - 0):"); scanf("%d",&ch);
}
while(ch==1);
printf("Directory name is:%s\n",mdname);
printf("Files names are:");
for(i=0;i<j;i++)
printf("\n%s",fname[i]);
getch();
}

Output:

Enter the directory name:sss Enter the


number of files:3 Enter file name to be
created:aaa
Do you want to enter another file(yes - 1 or no - 0):1 Enter file
name to be created:bbb
Do you want to enter another file(yes - 1 or no - 0):1 Enter file
name to be created:ccc
Do you want to enter another file(yes - 1 or no - 0):0 Directory
name is:sss
Files names are: aaa
bbb
Ccc

Thus a UNIX C Program to implement single level directory file organization was executed successfully.

II YEAR – VEC
Page 80
2023-2024 SEM: 4 Operating Systems

To write a UNIX C Program to implement two level directory file organization

Step1: Start the process.


Step2: Get the number of directories.
Step3: Get the name of the main directory.
Step4: Display the size of the directory.
Step5: Get the name of the sub-directory which is in the main directory.
Step6: Display the size of the sub-directory.
Step7: Display the number and name of the files which are presented in
the directory.
Step8: Stop the process.

#include<stdio.h>struct
{
char
dname[10],fname[10][10]; int
fcnt;
}dir[10];
void main()
{
int i,ch,dcnt,k;
char f[30], d[30];
clrscr();
dcnt=0;
while(1)
{
printf("\n\n 1. Create Directory\t 2. Create File\t 3. Delete File");
printf("\n 4. Search File \t \t 5. Display \t 6. Exit \t Enter your choice --
"); scanf("%d",&ch);
switch(ch)

II YEAR – VEC
Page 81
2023-2024 SEM: 4 Operating Systems

{
case 1: printf("\n Enter name of directory -- ");
scanf("%s", dir[dcnt].dname);
dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created");
break;
case 2: printf("\n Enter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
if(strcmp(d,dir[i].dname)==0
)
{
printf("Enter name of the file -- ");
scanf("%s",dir[i].fname[dir[i].fcnt])
; dir[i].fcnt++;
printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d);
break;
case 3: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{

printf("File %s is deleted ",f);


dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]);
goto jmp;
}
}
II YEAR – VEC
Page 82
2023-2024 SEM: 4 Operating Systems

printf("File %s not found",f);


goto jmp;
}
}
printf("Directory %s not found",d);
jmp : break;
case 4: printf("\nEnter name of the directory -- ");
scanf("%s",d);
for(i=0;i<dcnt;i++)
{

if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file -- ");
scanf("%s",f);
for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is found ",f);
goto jmp1;
}
}
printf("File %s not found",f);
goto jmp1;
}
}
printf("Directory %s not found",d);
jmp1: break;
case 5: if(dcnt==0)
printf("\nNo Directory's ");
else
{
printf("\nDirectory\tFiles");
for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname);
for(k=0;k<dir[i].fcnt;k++)
printf("\t%s",dir[i].fname[k]);
}
}

II YEAR – VEC
Page 83
2023-2024 SEM: 4 Operating Systems

break;
default:exit(0);
}}
getch();
}

OUTPUT:
1. Create Directory 2. Create File 3. Delete File
4. Search File 5. Display 6. Exit Enter your choice -- 1

Enter name of directory -- DIR1


Directory created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice --

1 Enter name of directory -- DIR2

Directory created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 2

Enter name of the directory – DIR1


Enter name of the file -- A1
File created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 2

Enter name of the directory – DIR1


Enter name of the file -- A2
File created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 2

Enter name of the directory – DIR2


Enter name of the file -- B1
File created

1. Create Directory 2. Create File 3. Delete File

II YEAR – VEC
Page 84
2023-2024 SEM: 4 Operating Systems

4. Search File 5. Display 6. Exit Enter your choice --


5 Directory Files
DIR1 A1 A2
DIR2 B1

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 4

Enter name of the directory – DIR


Directory not found

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice --
3 Enter name of the directory – DIR1
Enter name of the file -- A2

File A2 is deleted

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice – 6

Thus a UNIX C Program to implement two level directory file organization was executed successfully.

II YEAR – VEC
Page 85
2023-2024 SEM: 4 Operating Systems

To write a UNIX C program to simulate contiguous file allocation.

Step1: Start the program.


Step2: Read the number of files.
Step3: Input the filename.
Step4: Open the file in read only mode and find start, end and length of
the file.
Step5: Display the name, start, end and length of the file.

#include <stdio.h>
#include <stdlib.h> void
recurse(int files[])
{

int flag = 0, startBlock, len, j, k, ch;

printf("Enter the starting block and the length of the files: ");
scanf("%d%d", &startBlock, &len);
for (j=startBlock; j<(startBlock+len); j++){ if
(files[j] == 0)
flag++;

if(len == flag){

for (int k=startBlock; k<(startBlock+len); k++){ if


(files[k] == 0){
files[k] = 1; printf("%d\t%d\n", k,
files[k]);
}

II YEAR – VEC
Page 86
2023-2024 SEM: 4 Operating Systems

if (k != (startBlock+len-1))
printf("The file is allocated to the disk\n"); }

else

printf("The file is not allocated to the disk\n");

printf("Do you want to enter more files?\n"); printf("Press 1 for


YES, 0 for NO: ");
scanf("%d", &ch); if
(ch == 1)
recurse(files); else
exit(0); return;
}

int main()

int files[50];

for(int i=0;i<50;i++)
files[i]=0;
recurse(files);
return 0;

OUTPUT:

Enter the starting block and the length of the files: 1 5

11
21

31

41

51

The file is allocated to the disk Do


you want to enter more files? Press
1 for YES, 0 for NO: 1
Enter the starting block and the length of the files: 6 5

II YEAR – VEC
Page 87
2023-2024 SEM: 4 Operating Systems

61

71

81

91

10 1

The file is allocated to the disk Do


you want to enter more files? Press
1 for YES, 0 for NO: 0

Thus a UNIX C program to simulate contiguous file allocation scheme is


executed successfully.

II YEAR – VEC
Page 88
2023-2024 SEM: 4 Operating Systems

To write a UNIX C program to simulate linked file allocation.

Step1: Create a queue to hold all pages in memory


Step2: When the page is required to replace the page at the head of the queue
Step3: Now the new page is inserted at thetail ofthequeue
Step4: Create a stack
Step5: When the page fault occurs replace page presentatthebottomofthestack
Step6: Stop the allocation

#include <stdio.h>

#include <conio.h>

#include <stdlib.h>

void recursivePart(int pages[]){


int st, len, k, c, j;

printf("Enter the index of the starting block and its length: "); scanf("%d%d", &st,

&len);

k = len;

if (pages[st] == 0){

for (j = st; j < (st + k); j++){

if (pages[j] == 0){ pages[j]

= 1;

printf("%d >%d\n", j, pages[j]);

II YEAR – VEC
Page 89
2023-2024 SEM: 4 Operating Systems

else {

printf("The block %d is already allocated \n", j); k++;

else

printf("The block %d is already allocated \n", st); printf("Do you want

to enter more files? \n");

printf("Enter 1 for Yes, Enter 0 for No: ");

scanf("%d", &c);

if (c==1)

recursivePart(pages);

else

exit(0); return;

}
int main(){

int pages[50], p, a;

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

pages[i] = 0;

printf("Enter the number of blocks already allocated: "); scanf("%d", &p);

printf("Enter the blocks already allocated: "); for (int i = 0; i < p;

i++){

scanf("%d", &a);
II YEAR – VEC
Page 90
2023-2024 SEM: 4 Operating Systems

pages[a] = 1;

recursivePart(pages);

getch();

return 0;

OUTPUT:

Enter the number of blocks already allocated: 2 Enter the blocks

already allocated: 3

Enter the index of the starting block and its length: 1 5

1>1

2------>1
The block 3 is already allocated

The block 4 is already allocated 5

>1

6------>1

7------>1

Do you want to enter more files?

Enter 1 for Yes, Enter 0 for No: 1

Enter the index of the starting block and its length: 2 3 The

block 2 is already allocated

Do you want to enter more files?

II YEAR – VEC
Page 91
2023-2024 SEM: 4 Operating Systems

Enter 1 for Yes, Enter 0 for No: 1

Enter the index of the starting block and its length: 8 2 8

>1

9- ----->1

Do you want to enter more files?

Enter 1 for Yes, Enter 0 for No: 0

Thus a UNIX C program to simulate linked file allocation scheme is executed successfully.

II YEAR – VEC
Page 92
2023-2024 SEM: 4 Operating Systems

To write a UNIX C program to simulate indexed file allocation.

Step1:Start the program. Step2: Read the number of files.Ste p3:Input the filename.
Step 4: Open the file in read only mode and find start, end and length of the
file.Step5: Display the name, start, end and length of the file.

#include<stdio.h>
#include<stdlib.h>
void main()
{
int f[50], index[50],i, n, st, len, j, c, k, ind,count=0;
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++;
}

II YEAR – VEC
Page 93
2023-2024 SEM: 4 Operating Systems

if(count==n)
{
for(j=0;j<n;j++)
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);
}

OUTPUT:

Enter the index block: 3


Enter no of blocks needed and no of files for the index 3 on the disk : 2 4
5

Allocated

File Indexed 3
>4 : 1

3-------->5 : 1

Do you want to enter more file(Yes - 1/No - 0)6 1


Enter the index block: 4
4 index is already allocated
Enter the index block: 6
Enter no of blocks needed and no of files for the index 6 on the disk : 3 7
8

II YEAR – VEC
Page 94
2023-2024 SEM: 4 Operating Systems

Allocated File
Indexed 6 >7 : 1
6- ------->8 : 1

6-------->9 : 1

Do you want to enter more file(Yes - 1/No - 0)0

Thus a UNIX C program to simulate indexed file allocation scheme is executed successfully.

II YEAR – VEC
Page 95
2023-2024 SEM: 4 Operating Systems

DATE:

AIM

To develop a mobile app for health care system.

The main folder of this application is Mobile App, which consists of the below sub-folders:
.idea
Project Module (app)
Gradle
External Libraries

.idea
The .idea folder contains project settings in the form of configuration files(.xml). Each xml file is
comprised of only a portion of configuration data related to the particular functional area which is
defined by the name of the file such as compiler.xml, modules.xml, etc. These files contain
information about the names and locations of the project component modules, compiler settings, etc.
Almost all files under .idea contain information about the project itself.

Gradle
The Gradle folder consists of a gradle build system’s jar wrapper and this jar is used to communicate
Android studio with gradle installed in the operating system. The windows operating system is used
for this application.

External Libraries
External Libraries is not actually a folder but it contains information about Referenced Libraries and
the targeted platform of SDK in Android studio. In my application Android API 23 is used as the
targeted platform.

Project Module (app)


The app folder is the actual project folder which contains project application code in the form of java
files. The application folder contains build, libs and src sub-folders. build is the directory which
stores the complete output of the make process such as classes.dex, compiled classes and resources,
etc. The libs folder consists of libraries and .jar files. The src folder contains android application code
in the main subfolder and the unit test script in the android Test subfolder. The main folder again
contains two subfolders java and res. The res folder contains sub folders like drawable, layout,
II YEAR – VEC
Page 96
2023-2024 SEM: 4 Operating Systems

mipmap, etc. The layout folder includes xml files which are mainly used to create the user interface.
Each layout will have a corresponding java class. The mipmap folder is used for placing the app
icons which can be seen on the application dashboard. The java folder takes care of all the java codes
including methods developed by the application developer, and these java classes act as backend
code for connecting the user interface layouts present in res, and also obtaining values from the
RESTful web services. The java files in my application are as follows:

MainActivity.java
This class is used to develop the welcome screen of this application. Clicking on the welcome screen
directs the user to the login screen.

Login.java
This class is used to develop functions i.e. clicking on login button results in the metrics screen if
valid credentials are entered and invalid authentication pops up an error message.

Metrics.java
Clicking on a particular metric icon present in the metrics screen directs the user to the corresponding
screen. This function is implemented using this java class.

Admit.java
The Admit metric user interface is comprised of a date picker, and this java class helps the developer
to get the patient admit count after selecting a particular date.

Discharge.java
This java class is used for displaying the number of patients discharged for a given day after selecting
a date in the date picker calendar.

Census.java
The daily census count is displayed using this java class.

Insurance.java
A display of insurance company names and the number of patients in a list view can be implemented
using this java class.

Length.java
The average length of patient stay can be shown on the text view using this java class.

Demographics.java
This class is used to draw a bar graph on the android canvas.

Diagnosis.java
This class is used to display diagnosed disease names on the text view. The common interfaces and
methods present in the above mentioned java classes are described below:

OnClickListener.

II YEAR – VEC
Page 97
2023-2024 SEM: 4 Operating Systems

Onclicklistener is an interface that defines an onclick method in which clicking on the certain text,
button or image implements the defined onclick method.

Intent.
Intent in Android is an abstract description of an operation to be performed. It is used to connect
different activities. In this application intent is used as an onclick method, clicking a button, image or
text implements the intent method of entering into another activity. Java classes such as Admit,
Discharge, Insurance, Census, Metrics, Length, Demographics and Diagnosis contain an
onclicklistener in which clicking on the image view like back, refresh and logout directs to the
corresponding screen.

The Login screen uses the button and the Welcome screen uses the text view. The onclick listener
along with the intent method is described below:
Image View iv1= (Image View) findViewById (R.id.image2); iv1.setOnClickListener (new
View.OnClickListener () { @Override
public void on Click (View a) { Intent b = get Intent ();
finish ();
start Activity (b);
}});

The above code implements an image view and then assigns the onclicklistener to the created view.
When the user clicks, the onclicklistener will call the onclick function (intent method). Asynchronous
Task. It is used to perform operations in the background and publish results in the user interface. In
order to get the values of a JSON array, Android applications need to connect to the RESTful web
services by using HTTP URL connections. Async task helps in fetching the values from RESTful
web services and updating the user interface. Below are the steps involved in Async task.

HTTP URL Connection. Connecting to RESTful web services using HTTPURL connection in Async
task can be achieved by using the code below.

public class Http extends AsyncTask<Void, String, Integer> { @Override


protected Integer doInBackground(String... params) { InputStream input = null;
HttpURLConnection urlCon = null; Integer result = 0;
try {
URL url = new URL(params[1]);
urlCon = (HttpURLConnection) url.openConnection(); urlCon.setRequestMethod("GET");
int statusCode = urlCon.getResponseCode(); if (statusCode == 200) {
Json parsing (output); return result;
}}}}

JSON Parsing. This method is used to parse JSON data for obtaining required record values. The
code below is used to parse the JSON array.

private void json parsing (String Result) { try { JSONObject output = new JSONObject(Result);
JSONArray A = output.optJSONArray("name of the Json array"); for (int j = 0; j < A.length(); j++) {

II YEAR – VEC
Page 98
2023-2024 SEM: 4 Operating Systems

JSONObject O = A.optJSONObject (j); String rec = O.optString(" record name");


}}

Post Execute Method. The Post Execute method is used when the downloading of values from the
web page has been completed and the user interface needs to be updated. Below is the code used for
displaying the JSON value on the text view.
public void onPostExecute (Integer Result) { if (Result == 1) {
Textview.setText(rec);
} else {
system.out.println(“failed to fetch ”);
}

SCREEN SHOTS:

Fig.1: WELCOME SCREEN Fig.2: LOGIN SCREEN

II YEAR – VEC
Page 99
2023-2024 SEM: 4 Operating Systems

Fig. 3: LOGIN ERROR SCREEN

Fig 4: METRICS SCREEN Fig 5: ADMIT SCREEN

II YEAR – VEC
Page 100
2023-2024 SEM: 4 Operating Systems

Fig 6: DISCHARGE SCREEN Fig 7: CENSUS SCREEN

Fig 8: INSURANCE SCREEN Fig 9: DEMOGRAPHICS SCREEN

II YEAR – VEC
Page 101
2023-2024 SEM: 4 Operating Systems

Fig 10: LENGTH OF STAY SCREEN Fig 11: DIAGNOSIS SCREEN

II YEAR – VEC
Page 102

You might also like