0% found this document useful (0 votes)
24 views61 pages

Os Rec

This document describes various file and directory commands in Unix like mkdir, cd, rmdir, cat, cp and mv. It provides the syntax and explanation of each command and also shows sample outputs of executing the commands on files and directories.

Uploaded by

shrihari.9919an
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views61 pages

Os Rec

This document describes various file and directory commands in Unix like mkdir, cd, rmdir, cat, cp and mv. It provides the syntax and explanation of each command and also shows sample outputs of executing the commands on files and directories.

Uploaded by

shrihari.9919an
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

CS22411-OPERATING SYSTEMS LABORATORY

DATE:
EX.NO: 1
BASIC UNIX COMMANDS
AIM:
To execute basic commands in Unix.

1. Command: logname
Syntax: logname
Explanation: This command is used to display the name of the user who has logged into
the computer.
Output:
[cs22141@co508:~/student/oslab~]$ logname
cs22141

2. Command: who
Syntax: who
Explanation: This command is used to display the username along with the time and
date of the login.
Output:
[cs22141@co508:~/student/oslab~]$ who
cs22141 tty7 2024-01-29 13:41 (:0)
cs22141 pts/0 2024-01-29 13:41 (:0.0)

3. Command: whoami
Syntax: whoami
Explanation: This command is used to display the name of the user who has logged in.
Output:
[cs22141@co508:~/student/oslab~]$ whoami
cs22141

4. Command: ls
Syntax: ls
Explanation: This command is used to display all the files in the directory.
Output:
[cs22141@co508:~/student/oslab~]$ ls
10a.c 2b.cpp 3-d.c 5b.c 6.cpp 8a.c complex.cpp out.txt
11a.c 2.c 3d.c 5.c 6d.c 8b.c

ROLL NO:2127220501141 Page | 1


5. Command: ls -a
Syntax: ls -a
Explanation: The command is used to display all the files in the directory including
hidden files.
Output:
[cs22141@co508:~/student/oslab~]$ ls -a
. 3.txt 8d.c Music
.. 4a.c 8e.c .mysql_history
10a.c 4b.c 8f.c .nautilus
11a.c 4c.c 9a.c new file
11b.c 4-d.c 9b.c new file (copy)
11c.c 4-e.c 9.c new_student.txt
11d.c 4-f.c 9c.c .nfs00000000032a4e240000002e

6. Command: ls -l
Syntax: ls -l
Explanation: This command is used to display long listing format displaying additional
file information.
Output:
[cs22164@CS-01-112-CO277 ~]$ ls -l
total 560
-rw-r--r-- 1 cs22141 cs22 1228 Nov 14 11:59 10a.c
-rwxr-xr-x 1 cs22141 cs22 699 Feb 24 2023 11a.c
-rwxr-xr-x 1 cs22141 cs22 132 Dec 31 2004 11b.c
-rwxr-xr-x 1 cs22141 cs22 483 Feb 24 2023 11c.c
-rwxr-xr-x 1 cs22141 cs22 483 Feb 24 2023 11d.c
-rwxr-xr-x 1 cs22141 cs22 765 Feb 24 2023 11e.c

7. Command: man
Syntax: man <keyword>
Explanation: This command is used to display the manual for the specified keyword.
Output:
break [n]
Exit from within a for, while, until, or select loop. If n is specified, break n
levels. n must be ≥ 1. If n is greater than the number of enclosing loops, all
enclosing loops are exited. The return value is 0 unless n is not greater than
or equal to 1.

8. Command: date
Syntax: date
Explanation: This command is used to display the current date and time on the screen.
Output:
[cs22141@co508:~/student/oslab~]$ date
Mon Jan 29 13:59:10 IST 2024

9. Command: echo
Syntax: echo <string>
ROLL NO:2127220501141 Page | 2
Explanation: The command is used to display the given string.
Output:
[cs22141@co508:~/student/oslab~]$ echo Hi
Hi

10. Command: clear


Syntax: clear
Explanation: This command is used to clear the screen.
Output:
[cs22141@co508:~/student/oslab~]$ clear

11. Command: cal


Syntax: cal
Explanation: This command is used to display the calendar of current month.
Output:
[cs22141@co508:~/student/oslab~]$ cal
January 2024
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

12. Command: cal


Syntax: cal <year>
Explanation: This command is used to display the calendar of the specified year.
Output:
[cs22141@co508:~/student/oslab~]$ cal 2024
2024

January February March


Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 1 2 3 1 2
7 8 9 10 11 12 13 4 5 6 7 8 9 10 3 4 5 6 7 8 9
14 15 16 17 18 19 20 11 12 13 14 15 16 17 10 11 12 13 14 15 16
21 22 23 24 25 26 27 18 19 20 21 22 23 24 17 18 19 20 21 22 23
28 29 30 31 25 26 27 28 29 24 25 26 27 28 29 30
31

April May June


Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 1 2 3 4 1
7 8 9 10 11 12 13 5 6 7 8 9 10 11 2 3 4 5 6 7 8
14 15 16 17 18 19 20 12 13 14 15 16 17 18 9 10 11 12 13 14 15
ROLL NO:2127220501141 Page | 3
21 22 23 24 25 26 27 19 20 21 22 23 24 25
16 17 18 19 20 21 22
28 29 30 26 27 28 29 30 31 23 24 25 26 27 28 29
30
July August September
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 1 2 3 1 2 3 4 5 6 7
7 8 9 10 11 12 13 4 5 6 7 8 9 10 8 9 10 11 12 13 14
14 15 16 17 18 19 20 11 12 13 14 15 16 17 15 16 17 18 19 20 21
21 22 23 24 25 26 27 18 19 20 21 22 23 24 22 23 24 25 26 27 28
28 29 30 31 25 26 27 28 29 30 31 29 30

October November December


Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 1 2 1 2 3 4 5 6 7
6 7 8 9 10 11 12 3 4 5 6 7 8 9 8 9 10 11 12 13 14
13 14 15 16 17 18 19 10 11 12 13 14 15 16 15 16 17 18 19 20 21
20 21 22 23 24 25 26 17 18 19 20 21 22 23 22 23 24 25 26 27 28
27 28 29 30 31 24 25 26 27 28 29 30 29 30 31

13. Command: cal month year


Syntax: cal <month-in-number> <year>
Explanation: This command is used to display the calendar of the specified month and
Year.
Output:
[cs22141@co508:~/student/oslab~]$ cal 8 2023

August 2023
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

14. Command: help


Syntax: <command> --help
Explanation: This command is used to display the explanation of the specified
command.
Example: [cs22141@co508:~/student/oslab~]$ scanf --help
Output:
The information regarding the “scanf” is displayed in detail.

ROLL NO:2127220501141 Page | 4


RESULT:
The basic Unix commands were executed successful

ROLL NO:2127220501141 Page | 5


CS22411-OPERATING SYSTEMS LABORATORY
DATE:
EX.NO: 1.2
FILE AND DIRECTORY COMMANDS IN UNIX
AIM:
To execute file and directory commands in Unix
1. Command: mkdir
Syntax: mkdir <directory name>
Explanation: This command is used to create directory with specified directory name.
Output:
[cs22141@co508:~/student/oslab~]$ mkdir Vignesh
Directory created

2. Command: cd
Syntax: cd <directory name>
Explanation: This command is used to change from current directory to the specified
directory.
Output:
[cs22141@co508:~/student/oslab~]$ cd Desktop
[cs22141@co508:~/student/oslab~Desktop]$

3. Command: cd ..
Syntax: cd ..
Explanation: This command is used to change from current directory to previous
directory.
Output:
[cs22141@co508:~/student/oslab~Desktop]$ cd ..
[cs22141@co508:~/student/oslab~]$

4. Command: cd /
Syntax: cd /
Explanation: This command is used to change from current working directory to
the root directory.
Output:
[cs22141@co508:~/student/oslab~Desktop]$ cd /
[cs22141@co508:~/student/oslab~/]$

5. Command: rmdir
Syntax: rmdir <directory name>
Explanation: This command is used to remove directory of specified name.
Output:
[cs22141@co508:~/student/oslab~]$ rmdir Vignesh
Directory removed successfully

6. Command: cat>
ROLL NO:2127220501141 Page | 6
Syntax: cat> <file name>
Explanation: This command is used to create new file of specified name.
Output:
[cs22141@co508:~/student/oslab~]$ cat> Vignesh
Hello Uranus

7. Command: cat
Syntax: cat <file name>
Explanation: This command is used to display the contents of specified file
Output:
[cs22141@co508:~/student/oslab~]$ cat Vignesh
Hello Uranus

8. Command: cat>>
Syntax: cat>> <file name>
Explanation: This command leads to the creation of new file if it is not available
otherwise it appends content in the specified file name.
Output:
[cs22141@co508:~/student/oslab~]$ cat>> Vignesh
Mercury

9. Command: cat __>_


Syntax: cat <filename 1> <filename 2> > <filename 3>
Explanation: This command is used to copy content of file 1 and file 2 to file 3.
Output:
[cs22141@co508:~/student/oslab~]$ cat> file1
Vignesh
[cs22141@co508:~/student/oslab~]$ cat> file2
is
[cs22141@co508:~/student/oslab~]$ cat> file3
playing
[cs22141@co508:~/student/oslab~]$ cat file1 file2 > file3
[cs22141@co508:~/student/oslab~]$ cat file3
Vignesh
is

10. Command: cp
Syntax: cp <source filename> <destination filename>
Explanation: This command is used to copy content from source file to destination
file.

Output:
[cs22141@co508:~/student/oslab~]$ cat> destination
[cs22141@co508:~/student/oslab~]$ cat> source
Hello
[cs22141@co508:~/student/oslab~]$ cp source destination
ROLL NO:2127220501141 Page | 7
[cs22141@co508:~/student/oslab~]$ cat destination
Hello
11. Command: mv
Syntax: mv <source file> <destination file>
Explanation: This command is used to move contents from source file to destination
file but the source file is deleted after the content is moved.
Output:
[cs22141@co508:~/student/oslab~]$ mv source destination
[cs22141@co508:~/student/oslab~]$ cat source
cat: source: No such file or directory
[cs22141@co508:~/student/oslab~]$ cat destination
Hello

12. Command: pwd


Syntax: pwd
Explanation: This command is used to display the absolute path of current working
directory.
Output:
[cs22141@co508:~/student/oslab~]$ pwd
/home/cs22/cs22141

13. Command: rm
Syntax: rm <filename>
Explanation: This command is used to remove file of specified name.
Output:
[cs22141@co508:~/student/oslab~]$ rm destination
[cs22141@co508:~/student/oslab~]$ cat destination
cat: destination: No such file or directory

14. Command: rm -r
Syntax: rm -r <filename>
Explanation: This command is used for recursive removal of directory.
Output:
[cs22141@co508:~/student/oslab~]$ mkdir dir1
[cs22141@co508:~/student/oslab~]$ rm -r dir1

15. Command: rm -i
Syntax: rm -i <filename>
Explanation: This command is used for removing directory with permission from user
(interactive).
Output:
[cs22141@co508:~/student/oslab~]$ mkdir dir1
[cs22141@co508:~/student/oslab~]$ rm -r dir1

16. Command: vi
Syntax: vi <filename>.<extension>
Explanation: This command is used for creating file of specified name and extension.
ROLL NO:2127220501141 Page | 8
Output:
[cs22141@co508:~/student/oslab~]$ vi Mul.c
17. Command: touch
Syntax: touch <filename 1> <filename 2> …<filename n>
Explanation: This command is used to create multiple files.
Output:
[cs22141@co508:~/student/oslab~]$ touch f1 f2 f3
[cs22141@co508:~/student/oslab~]$ ls
f1 f2 f3

18. Command: cc
Syntax: cc <filename>.<extension>
Explanation: This command is used to compile the file of specified name and
extension.
Output:
[cs22141@co508:~/student/oslab~]$ cc swap1.c

19. Command: ./a.out


Syntax: ./a.out
Explanation: This command is used to run the specified file and display the output.
Output:
[cs22141@co508:~/student/oslab~]$ ./a.out

Enter the first number: 10


Enter the second number: 20
Before swapping:
a=10
b=20
After swapping:
a=20
b=10

RESULT:
The file and directory commands in Unix were successfully executed

ROLL NO:2127220501141 Page | 9


CS22411 - OPERATING SYSTEMS LABORATORY
DATE:
EX.NO: 2

STUDY OF SHELL PROGRAMMING

AIM:
To study the shell commands and implement several using the shell commands.

I. Sum of two Numbers

ALGORITHM:
1. Start
2. Read the two numbers
3. Add the two numbers
4. Print the results
5. Stop

SOURCE CODE:
echo "enter num:"
read a b
c=$(( $a + $b ))
echo "the sum $a and $b is $c"

OUTPUT:
[cs22141@CS-01-106-CO270 ~]$ vi sum.sh
[cs22141@CS-01-106-CO270 ~]$ sh sum.sh
enter num:
56
the sum 5 and 6 is 11

II. Swapping of two numbers

ROLL NO:2127220501141 Page | 10


ALGORITHM:
1. Start
2. Read the two numbers
3. Swap the numbers using the temp variable
4. Print the results
5. Stop

SOURCE CODE:
echo "enter number:"
read first second
echo "before swap, numbera are:"
echo "first=$first, second=$second"
temp=$first
first=$second
second=$temp
echo "after swap, number are:"
echo "first=$first, second=$second"

OUTPUT:
[cs22141@CS-01-106-CO270 ~]$ vi swap.sh
[cs22141@CS-01-106-CO270 ~]$ sh swap.sh
enter number:
10 66
before swap, numbera are:
first=10, second=66
after swap, number are:
first=66, second=10

III. Greatest of three number

ALGORITHM:
1. Start
2. Read three numbers
3. Compare first with second and the third to find greater one
4. Checkl same for second and third number
ROLL NO:2127220501141 Page | 11
5. Print the result
6. Stop

SOURCE CODE:
echo "enter number:"
read num1 num2 num3
if [ $num1-gt$num2 ] && [ $num1-gt$num3 ]
then
echo "$num1 is greater"
elif [ $num2-gt$num1 ] && [ $num2-gt$num3 ]
then
echo "$num2 is greater"
else
echo "$num3 is greater"
fi

OUTPUT:

[cs22141@CS-01-106-CO270 ~]$ vi greatest.sh


[cs22141@CS-01-106-CO270 ~]$ sh greatest.sh
enter number:
630
6 is greater

IV. Factorial

ALGORITHM:
1. Start
2. Read numbers
3. Calculate factorial using loop concept by multiplying and reducing number
4. Print result
5. Stop

ROLL NO:2127220501141 Page | 12


SOURCE CODE:
echo "enter num:"
read num
fact=1
wihile [ $num -gt 1 ]
do
fact=$(( fact*num ))
num=$(( num-1 ))
done
echo "the fact value:$fact"

OUTPUT:
[cs22141@CS-01-106-CO270 ~]$ vi fact.sh
[cs22141@CS-01-106-CO270 ~]$ sh fact.sh
enter num:
5
the fact value:120

V. Generation of Fibonacci series

ALGORITHM:
1. Start
2. Read number
3. Print 0 and 1 as starting numbers
4. Add the numbers and print the result till the number given is reached
5. Stop

SOURCE CODE:
echo "enter num:"
read n

ROLL NO:2127220501141 Page | 13


a=0
b=1
echo "the fib is:"
echo "$a"
echo "$b"
while [ $n -ne 2 ]
do
c=$(( $a + $b ))
echo "$c"
a=$b
b=$c
n=$(( n - 1))
done

OUTPUT:
[cs22141@CS-01-106-CO270 ~]$ vi fib.sh
[cs22141@CS-01-106-CO270 ~]$ sh fib.sh
enter num:
4
the fib is:
0
1
1
2

VI. Menu driven calculator

ALGORITHM:
1. Start
2. Read numbers
3. Select operation to be done using numbers
4. Do the operation
5. Print result
6. Stop

SOURCE CODE:
ROLL NO:2127220501141 Page | 14
sum=0
i="y"
echo "enter num:"
read n1 n2
echo "1. add"
echo "2. sub"
echo "3. mul"
echo "4. div"
echo "enter choice:"
read ch
case $ch in
1) sum=$(( $n1 + $n2 ))
echo "sum=$sum"
;;
2) sum=$(( $n1 - $n2 ))
echo "sub=$sum"
;;
3) sum=$(( $n1 * $n2 ))
echo "mul=$sum"
;;
4) sum=$(( $n1 / $n2 ))
echo "div=$sum"
;;
esac

OUTPUT:

[cs22141@CS-01-106-CO270 ~]$ vi calc.sh


[cs22141@CS-01-106-CO270 ~]$ sh calc.sh
enter num:
56
1. add
2. sub
3. mul
4. div
enter choice:
1
sum=11
[cs22141@CS-01-106-CO270 ~]$ sh calc.sh
enter num:

ROLL NO:2127220501141 Page | 15


56
1. add
2. sub
3. mul
4. div
enter choice:
2
sub=-1
[cs22141@CS-01-106-CO270 ~]$ vi calc.sh
[cs22141@CS-01-106-CO270 ~]$ sh calc.sh
enter num:
56
1. add
2. sub
3. mul
4. div
enter choice:
3
mul=30
[cs22141@CS-01-106-CO270 ~]$ sh calc.sh
enter num:
56
1. add
2. sub
3. mul
4. div
enter choice:
4
div=0

VII. Verification of Armstrong number

ALGORITHM:
1. Start
2. Read number
3. Separate digit and cal powers
4. Sum of the powers
5. Print results
6. Stop

SOURCE CODE:
echo "enter num:"
ROLL NO:2127220501141 Page | 16
read c
x=$c
sum=0
r=0
n=0
while [ $x -gt 0 ]
do
r=$(( $x % 10 ))
n=$(( $r * $r * $r ))
sum=$(( $sum + $n ))
x=$(( $x / 10 ))
done
if [ $sum -eq $c ]
then
echo "$sum is armstrong num"
else
echo "$sum is not armstrong number"
fi

OUTPUT:
[cs22141@CS-01-106-CO270 ~]$ vi armstrong.sh
[cs22141@CS-01-106-CO270 ~]$ sh armstrong.sh
enter num:
153
153 is armstrong num

VIII. Generation of prime number

ALGORITHM:

1. Start
2. Read numbers
3. Separate digits and cal the powers
4. Sum the powers
5. Print results
6. Stop

SOURCE CODE:
ROLL NO:2127220501141 Page | 17
echo "enter range:"
read n
echo "the prime num are:"
m=2
while [ $m -le $n ]
do
i=2
flag=0
while [ $i -le $(( $m / 2 )) ]
do
if [ $(( $m % $i )) -eq 0 ]
then
flag=1
break
fi
i=$(( $i + 1 ))
done
if [ $flag -eq 0 ]
then
echo $m
fi
m=$(( $m + 1 ))
done

OUTPUT:
[cs22141@CS-01-106-CO270 ~]$ vi prime.sh
[cs22141@CS-01-106-CO270 ~]$ sh prime.sh
enter range:
10
the prime num are:
2
3
5
7

RESULT:
The shell program are successfully studied and implemented.

ROLL NO:2127220501141 Page | 18


CS22411 - OPERATING SYSTEMS LABORATORY
DATE:
EX.NO: 3

PROCESS MANAGEMENT USING SYSTEM CALLS

AIM:
To implement system calls such as fork, exit, getpid, wait and close for process
management.

(i) Program 1:
Code:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main(){
int p;
printf("\nHello from parent process id: %d",getpid());
p=fork();
if(p==-1)
{
printf("\nThe is an error while calling fork()");
}
if(p==0)
{
printf("\nWe are in the child process");
}
else
{
printf("\nWe are in the parent process");
}
printf("Using fork() system cal \n");
return 0;
}
Sample output:
[cs22141@CS-01-112-CO277 ~]$ cc ProcessManagement.c
[cs22141@CS-01-112-CO277 ~]$ ./a.out
Hello from parent process, id=2727
We are in the parent process
Using fork() system call
Hello from parent process, id=2727
We are in processchild id =3649, parentid =3648

ROLL NO:2127220501141 Page | 19


Using fork() system call
(ii) Program 2:
Code:
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
int p;
printf("\nHello from parent process id: %d",getpid());
p=fork();
if(p==-1)
{
printf("\nThere is an error while calling fork ()");
}
if(p==0)
{
printf("\nWe are the child process");
printf("\nChild id: %d, parentid: %d,getpid(),getppid()");
sleep(5);
}
else
{
printf("\nWe are in the parent process");
wait();
}
printf("\nUsing fork() system call \n");
return 0;
}

Sample output:
[cs22141@CS-01-112-CO277 ~]$ cc ProcessManagement2.c
[cs22141@CS-01-112-CO277 ~]$ ./a.out
Hello from parent process, id=3729
We are in the child processchildid=3730, parentid=3729
Using fork() system call
Hello from parent process, id=3729
We are in parent process
Using fork() system call

ROLL NO:2127220501141 Page | 20


(iii) Program 3:
Code:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
int p;
printf("\nHello from parent process id: %d",getpid());
p=fork();
if(p==-1)
{
printf("\nThere is an error while calling fork ()");
}
if(p==0)
{
printf("\nWe are the child process");
printf("\nChild id: %d, parentid: %d,getpid(),getppid()");
sleep(5);
}
else
{
printf("\nWe are in the parent process");
wait();
}
printf("\nUsing fork() system call \n");
return 0;
}

Sample output:
[cs22141@CS-01-112-CO277 ~]$ cc ProcessManagement3.c
[cs22141@CS-01-112-CO277 ~]$ ./a.out
Hello from parent process, id=3905
We are in parent process
[cs22141@CS-01-112-CO277 ~]$ Hello from parent process, id=3905
We are in the child process
Using fork() system call

ROLL NO:2127220501141 Page | 21


(iv) Program 4

#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<errno.h>
int main(int argc, char* argv[]){
DIR* dp;
struct dirent* dirp;
if(argc!=2){
fprintf(stderr,"usage:./programdirectory_name \n");
exit(EXIT_FAILURE);
}
dp=opendir(argv[1]);
while((dirp=readdir(dp))!=NULL)
printf("%s\n",dirp->d_name);
closedir(dp);
exit(EXIT_SUCCESS);
}

OUTPUT:

[cs22141@CS-01-112-CO277 ~]$ vi sleep.c


[cs22141@CS-01-112-CO277 ~]$ cc sleep.c
[cs22141@CS-01-112-CO277 ~]$ ./a.out
usage:./programdirectory_name

ROLL NO:2127220501141 Page | 22


(v) Program 5

#include<stdio.h>
#include<stdlib.h>
#include<dirent.h>
#include<errno.h>
int main(int argc, char* argv[]){
DIR* dp;
struct dirent* dirp;
if(argc!=2){
fprintf(stderr,"usage:./programdirectory_name \n");
exit(EXIT_FAILURE);
}
errno=0;
if((dp=opendir(argv[1]))!=NULL){
switch(errno){
case EACCES:printf("permissiondenined\n");
break;
case ENOENT:printf("DIRECTORYDOSENTEXIST\n");
break;
case ENOTDIR:printf("%s is not directory\n",argv[1]);
break;}
exit(EXIT_FAILURE);}
while((dirp=readdir(dp))!=NULL)
printf("%s\n",dirp->d_name);
if(closedir(dp)==-1)
perror("closedir");
}

OUTPUT:

[cs22141@CS-01-112-CO277 ~]$ vi exit.c


[cs22141@CS-01-112-CO277 ~]$ cc exit.c
[cs22141@CS-01-112-CO277 ~]$ ./a.out
usage:./programdirectory_name

RESULT:
Thus the various system call operations has been executed successfully.

ROLL NO:2127220501141 Page | 23


CS22411 - OPERATING SYSTEMS LABORATORY
DATE:
EX.NO: 4

IMPLEMENTATION OF CPU SCHEDULING ALGORITHMS

1. FIRST COME FIRST SERVE (FCFS) ALGORITHM

AIM:
To implement the First Come First Serve CPU Scheduling Algorithm for Process
Scheduling in C.

ALGORITHM:
1. Start.
2. Get the number of processes, the process ID and the burst time.
3. Sort all the arrays on the basis of the given priority.
4. As the FCFS technique, finish the first process and proceed to another.
5. Add the burst time to the FT and increment it completely.
6. Calculate TAT and WT as FT and FT-BT respectively.
7. Print the specifications.
8. Stop.

CODE:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n;
printf("\nFirst come first serve");
printf("\nEnter the number of processes: ");
scanf("%d",&n);
int pid[n],bt[n],tat[n],wt[n],ft[n];
int tot_tat=0,tot_wt=0;
double avg_tat,avg_wt;
printf("\nEnter process id: ");
for(int i=0;i<n;i++){
scanf("%d",&pid[i]);
}
printf("Enter the burst time: ");
for(int i=0;i<n;i++)
ROLL NO:2127220501141 Page | 24
{
scanf("%d",&bt[i]);
}
for(int i=0;i<n;i++)
{
if(pid[i]==0)
{
ft[i]=bt[i];
wt[i]=0;
tat[i]=ft[i];
}
else
{
ft[i]=bt[i]+ft[i-1];
wt[i]=ft[i-1];
tat[i]=ft[i];
}
tot_tat=tot_tat+tat[i];
tot_wt=tot_wt+wt[i];
}
printf("\nThe process specifications: ");
printf("\nPID\tBT\tFT\tWT\tTAT");
for(int i=0;i<n;i++)
{
printf("\n%d\t%d\t%d\t%d\t%d",pid[i],bt[i],ft[i],wt[i],tat[i]);
}
printf("\nTotal waiting time: %d",tot_wt);
printf("\nTotal turn around time: %d",tot_tat);
avg_tat=(float)tot_tat/n;
avg_wt=(float)tot_wt/n;
printf("\nAverage waiting time: %f",avg_wt);
printf("\nAverage turn around time: %f",avg_tat);
return 0;
}
Sample Output:
[cs22141@CO277 ~]$ vi FCFS.c
[cs22141@CO277 ~]$ cc -std=c99 FCFS.c
[cs22141@CO277 ~]$ ./a.out
First come first serve
Enter the number of processes: 5
Enter process id: 1 2 3 4 5
Enter the burst time: 8 3 4 2 6

ROLL NO:2127220501141 Page | 25


The process specifications:
PID BT FT WT TAT
1 8 8 0 8
2 3 11 8 11
3 4 15 11 15
4 2 17 15 17
5 6 23 17 23
Total waiting time: 51
Total turn around time: 74
Average waiting time: 10.200000
Average turn around time: 14.800000

RESULT:
The FCFS CPU Scheduling Algorithm has been implemented successfully.

ROLL NO:2127220501141 Page | 26


2. SHORTEST JOB FIRST (SJF) ALGORITHM

AIM:
To implement SJF CPU Scheduling algorithm for Process Scheduling using C.

ALGORITHM:

1. Start.
2. Get the number of processes, the process ID and the burst time.
3. Copy the burst time in a temp array.
4. Sort all the arrays into a temp array.
5. Calculate the finishing time for each process using respective technique.
6. Print the specifications.
7. Stop.

CODE:
#include<stdio.h>
#include<stdlib.h>
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}
int main()
{
int n;
printf("\nShortest Job First");
printf("\nEnter the number of processes: ");
scanf("%d",&n);
int pid[n],bt[n],tat[n],wt[n],ft[n];
int tot_tat=0,tot_wt=0;
double avg_tat,avg_wt;
printf("\nEnter process id: ");
for(int i=0;i<n;i++){
scanf("%d",&pid[i]);
}
printf("Enter the burst time: ");
for(int i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
for(int i=0;i<n;i++)
ROLL NO:2127220501141 Page | 27
{
for(int j=i+1;j<n;j++)
{
if(bt[i]>bt[j])
{
swap(&bt[i],&bt[j]);
swap(&pid[i],&pid[j]);
}
}
}
int x=pid[0];
for(int i=0;i<n;i++)
{
if(pid[i]==x)
{
ft[i]=bt[i];
wt[i]=0;
tat[i]=ft[i];
}
else
{
ft[i]=bt[i]+ft[i-1];
wt[i]=ft[i-1];
tat[i]=ft[i];
}
tot_tat=tot_tat+tat[i];
tot_wt=tot_wt+wt[i];
}
printf("\n");
printf("\nThe process specification:\n");
printf("\nPID\tBT\tFT\tWT\tTAT");
for(int i=0;i<n;i++)
{
printf("\n%d\t%d\t%d\t%d\t%d",pid[i],bt[i],ft[i],wt[i],tat[i]);
}
printf("\nTotal waiting time: %d",tot_wt);
printf("\nTotal turn around time: %d",tot_tat);
avg_tat=(float)tot_tat/n;
avg_wt=(float)tot_wt/n;
printf("\nAverage waiting time: %f",avg_wt);
printf("\nAverage turn around time: %f",avg_tat);
return 0;
}

ROLL NO:2127220501141 Page | 28


Sample Output:
[cs22141@CO277 ~]$ vi SJF.c
[cs22141@CO277 ~]$ cc -std=c99 SJF.c
[cs22141@CO277 ~]$ ./a.out
Shortest Job First
Enter the number of processes: 4
Enter process id: 3 4 1 2
Enter the burst time: 3 5 8 12

The process specification:


PID BT FT WT TAT
3 3 3 0 3
4 5 8 3 8
1 8 16 8 16
2 12 28 16 28
Total waiting time: 27
Total turn around time: 55
Average waiting time: 6.750000
Average turn around time: 13.750000

RESULT:
The Shortest Job First CPU Scheduling Algorithm has been implemented successfully.

ROLL NO:2127220501141 Page | 29


3. PRIORITY BASED ALGORITHM:

AIM:
To implement Priority CPU Scheduling algorithm for Process Scheduling using C.

ALGORITHM:
1. Start.
2. Get the number of processes, the process ID and the burst time.
3. Copy the burst time in a temp array.
4. Sort all the arrays on the basis of priority.
5. Calculate the finishing time for each process using respective technique.
6. Print the specifications.
7. Stop.

CODE:
#include<stdio.h>
#include<stdlib.h>
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}
int main()
{
int n;
printf("\nPriority");
printf("\nEnter the number of processes: ");
scanf("%d",&n);
int pid[n],prio[n],bt[n],tat[n],wt[n],ft[n];
int tot_tat=0,tot_wt=0;
double avg_tat,avg_wt;
printf("\nEnter process id: ");
for(int i=0;i<n;i++){
scanf("%d",&pid[i]);
}
printf("Enter the burst time: ");
for(int i=0;i<n;i++)
{
scanf("%d",&bt[i]);
ROLL NO:2127220501141 Page | 30
}
printf("\nEnter priority: ");
for(int i=0;i<n;i++)
{
scanf("%d",&prio[i]);
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(prio[i]>prio[j])
{
swap(&prio[i],&prio[j]);
swap(&bt[i],&bt[j]);
swap(&pid[i],&pid[j]);
}
}
}
int x=pid[0];
for(int i=0;i<n;i++)
{
if(pid[i]==x)
{
ft[i]=bt[i];
wt[i]=0;
tat[i]=ft[i];
}
else
{
ft[i]=bt[i]+ft[i-1];
wt[i]=ft[i-1];
tat[i]=ft[i];
}
tot_tat=tot_tat+tat[i];
tot_wt=tot_wt+wt[i];
}
printf("\n");
printf("\nThe process specification:\n");
printf("\nPID\tBT\tFT\tWT\tTAT");
for(int i=0;i<n;i++)
{
printf("\n%d\t%d\t%d\t%d\t%d",pid[i],bt[i],ft[i],wt[i],tat[i]);
}
printf("\nTotal waiting time: %d",tot_wt);
printf("\nTotal turn around time: %d",tot_tat);
avg_tat=(float)tot_tat/n;
avg_wt=(float)tot_wt/n;
ROLL NO:2127220501141 Page | 31
printf("\nAverage waiting time: %f",avg_wt);
printf("\nAverage turn around time: %f",avg_tat);
return 0;
}

Sample Output:
[cs22141@CO277 ~]$ cc -std=c99 Priority.c
[cs22141@CO277~]$ ./a.out
Priority
Enter the number of processes: 4
Enter process id: 1 2 3 4
Enter the burst time: 8 12 3 5
Enter priority: 4 2 3 1
The process specification:
PID BT FT WT TAT
4 5 5 0 5
2 12 17 5 17
3 3 20 17 20
1 8 28 20 28
Total waiting time: 42
Total turn around time: 70
Average waiting time: 10.500000
Average turn around time: 17.500000

RESULT:
The Priority Based CPU Scheduling Algorithm has been implemented successfully.

ROLL NO:2127220501141 Page | 32


4. ROUND ROBIN ALGORITHM

AIM:
To implement Round Robin CPU Scheduling algorithm for Process Scheduling using
C.

ALGORITHM:
1. Start.
2. Get the number of processes, the process ID and the burst time.
3. Copy the burst time in a temp array.
4. Check the burst time and the time quantum and decide on the following actions.
5. A) If the burst time is greater than the time quantum:
 For finishing time, add the time quantum.
 For burst time, subtract the time quantum.
B) If the burst time is 0, reduce the number of processes.
C) If the burst time is lesser than the time quantum:
 For finishing time, add the time quantum.
 For burst time, make it 0.
 Reduce the number of processes.
6. Print the calculated values, the total and average times.
7. Stop.
CODE:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int n,i,j,x,t;
printf("\n RR CPU SCHEDULING ALGO");
printf("\n \n enter no of processess:");
scanf("%d",&n);
x=n;
int final=0;
int pid[n],bt[n],temp[n],ft[n];
int tot_tat=0,tot_wt=0;
double avg_tat,avg_wt;
printf("\n enter pid:");
ROLL NO:2127220501141 Page | 33
for(i=0;i<n;i++)
scanf("%d",&pid[i]);
printf("\nenter bt:");
for(i=0;i<n;i++)
{scanf("%d",&bt[i]);
temp[i]=bt[i];
ft[i]=0;
}
printf("\n enter TQ:");
scanf("%d",&t);
while(n>0)
{
for(i=0;i<x;i++)
{
if(bt[i]>=t){
ft[i]=final+t;
final=final+t;
bt[i]=bt[i]-t;
if(bt[i]==0)
n--;
}
else if(bt[i]>0){
ft[i]=final+bt[i];
final=final+bt[i];
bt[i]=0;
n--;
}}}
printf("\n the process spec:");
printf("\n PID \tBT \tFT\tWT\tTAT");
for(i=0;i<x;i++){
printf("\n %d \t%d \t%d \t%d \t%d",pid[i],temp[i],ft[i],ft[i]-temp[i],ft[i]);
tot_tat+=ft[i];
tot_wt+=ft[i]-temp[i];
}
printf("\n\n totat WT:%d",tot_wt);
printf("\n total TAT:%d",tot_tat);
avg_tat=(float)tot_tat/x;
avg_wt=(float)tot_wt/x;
printf("\n\n avg tat:%.2f",avg_tat);
printf("\n avg wt:%.2f",avg_wt);
return 0;}

OUTPUT:
[cs22141@CO277 ~]$ vi rr.c
[cs22141@CO277 ~]$ cc rr.c

ROLL NO:2127220501141 Page | 34


[cs22141@CO277 ~]$ ./a.out

RR CPU SCHEDULING ALGO

enter no of processess:4
enter pid:1 2 3 4
enter bt:8 12 3 5
enter TQ:2

the process spec:


PID BT FT WT TAT
1 8 22 14 22
2 12 28 16 28
3 3 13 10 13
4 5 20 15 20

totat WT:55
total TAT:83
avg tat:20.75

RESULT:
ROLL NO:2127220501141 Page | 35
The Round Robin CPU Scheduling Algorithm has been implemented successfully.

CS22411-OPERATING SYSTEMS LABORATORY


DATE:
EX.NO: 5.1

IMPLEMENTATION OF SHARED MEMORY INTER-PROCESS


COMMUNICATION

AIM:
To write a C program to implement the inter-process communication using a shared
memory.

ALGORITHM:
1. Start the program.
2. Declare the necessary variables.
3. shmat() and shmdt() are used attach and detach shared memory segments.
3.1. Prototypes:-
void*shmat(int shmid, const void shmaddr, int shmflag);
shmdt(const void*shmaddr);
4. shmat() returns a pointer, shmaddr, to the head of shared segment associated with a valid
shmid-shmdt() detaches the share memory segment located at the address indicated by
shmaddr.
5. Shared1.c simply creates the string and shared memory portion.
6. Shared2.c attaches itself to be created shared memory portion and uses the string.
7. Stop

ROLL NO:2127220501141 Page | 36


PROGRAM 1:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#define SHMSZ 27
main()
{
char c;
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if((shmid = shmget(key, SHMSZ,IPC_CREAT | 0666)) < 0)
{
printf("Cannot Allocate Shared Memory\n");
exit(1);
}

if((shm = shmat(shmid,NULL,0))==(char *)-1)


{
printf("Cannot Attach Data in Shared Memory\n");
exit(1);
}
s=shm;

for(c = 'a'; c <= 'z'; c++)


{
*s++ = c;
}

*s='\0';

while(*shm != '*')
sleep(1);
exit(0);
}

PROGRAM 2:
#include<sys/types.h>
#include<sys/ipc.h>

ROLL NO:2127220501141 Page | 37


#include<sys/shm.h>
#include<stdio.h>
#include<stdlib.h>
#define SHMSZ 27
main()
{
int shmid;
key_t key;
char *shm, *s;
key = 5678;
if((shmid = shmget(key, SHMSZ,0666)) < 0)
{
printf("Cannot Allocate Shared Memory\n");
exit(1);
}

if((shm = shmat(shmid,NULL,0))==(char *)-1)


{
printf("Cannot Attach Data in Shared Memory\n");
exit(1);
}
s=shm;

for(s=shm; *s != '\0'; s++)


{
putchar(*s);
putchar(' ');
}
putchar('\n');
*shm='*';
exit(0);
}

SAMPLE OUTPUT:
[cs22141@CO277 ~]$ cc 5a1.c
[cs22141@CO277 ~]$ cc 5a2.c
[cs22141@CO277 ~]$ ./a.out
abcdefghijklmnopqrstuvwxyz

RESULT:

ROLL NO:2127220501141 Page | 38


Thus the C Program for implementing inter-process communication using shared
memory is executed successfully.

CS22411-OPERATING SYSTEMS LABORATORY


DATE:
EX.NO: 5.2

IMPLEMENTATION OF MESSAGE QUEUEING INTER-PROCESS


COMMUNICATION

AIM:
To write a C program to implement the inter-process communication using message
queueing.

ALGORITHM:
1. Start
2. Create message queue using msgget system call.
3. If the message queueing is not created, go to step 1.
4. Copy string ‘Hello’ to mtext.
5. Create a child process.
6. If the child process is successfully created, then send the message, otherwise go to step
8.
7. If parent process got the focus, receive the message sent by the child.
8. Stop
CODE:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define MAX 10
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;

key = ftok("progfile", 65);


msgid = msgget(key, 0666 | IPC_CREAT);
ROLL NO:2127220501141 Page | 39
message.mesg_type = 1;
printf("Write Data : ");
fgets(message.mesg_text,MAX,stdin);
msgsnd(msgid, &message, sizeof(message), 0);
printf("Data send is : %s \n", message.mesg_text);
return 0;
}
Message Queue (Reader Process)
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct mesg_buffer {
long mesg_type;
char mesg_text[100];
} message;
int main()
{
key_t key;
int msgid;
key = ftok("progfile", 65);
msgid = msgget(key, 0666 | IPC_CREAT);
msgrcv(msgid, &message, sizeof(message), 1, 0);
printf("Data Received is : %s \n",
message.mesg_text);
msgctl(msgid, IPC_RMID, NULL);
return 0;
}

SAMPLE OUTPUT:
[cs22141@CO277 ~]$ cc 5b1.c
[cs22141@CO277 ~]$ ./a.out

Write Data:Hello
Data send is:Hello

[cs22141@CO277 ~]$ cc 5b2.c


[cs22141@CO277 ~]$ ./a.out

Data received is:Hello

RESULT:
Thus the C Program for implementing inter-process communication using message

ROLL NO:2127220501141 Page | 40


queue is executed successfully.

CS22411-OPERATING SYSTEMS LABORATORY


DATE:
EX.NO: 5.3
IMPLEMENTATION OF PIPE PROCESSING INTER-PROCESS
COMMUNICATION

AIM:
To write a C program to implement the inter-process communication using pipe
processing.

ALGORITHM:
1. Start
2. Declare necessary variables required for creating pipe.
3. Initialize a character-based buffer with values.
4. Create a pipe ‘p’.
5. Using principles of pipe, write on one side of the pipe.
6. The other end of the pipe reads the content written to mark the ‘flow’.
7. Stop

CODE:
#include <stdio.h>
#include <unistd.h>
int main() {
int pid;
char buff[2][20]={"hi","hello"};
char buff1[20];
int p[2];
pipe(p);
pid=fork();
if(pid>0)
write(p[1],buff[0],20);
else{
read(p[0],buff1,20);
printf("%s",buff1);
}
return 0;
}
ROLL NO:2127220501141 Page | 41
SAMPLE OUTPUT:
[cs22141@CO277 ~]$ cc 5c1.c
[cs22141@CO277 ~]$ ./a.out

hi

RESULT:
Thus the C Program for implementing inter-process communication using pipes is
executed successfully.
ROLL NO:2127220501141 Page | 42
CS22411-OPERATING SYSTEMS LABORATORY
DATE:
EX.NO: 6
IMPLEMENTATION OF PRODUCER CONSUMER PROBLEM USING
SEMAPHORES
AIM :
To synchronize producer and consumer processes using semaphore.

ALGORITHM :
1. Create a shared memory segment BUFSIZE of size 1 and attach it.
2. Obtain semaphore id for variables empty, mutex and full using semget function.
3. Create semaphore for empty, mutex and full as follows:
a. Declare semun, a union of specific commands.
b. The initial values are: 1 for mutex, N for empty and 0 for full
c. Use semctl function with SETVAL command
4. Create a child process using fork system call.
a. Make the parent process to be the producer
b. Make the child process to the consumer
5. The producer produces 5 items as follows:
a. Call wait operation on semaphores empty and mutex using semop function.
b. Gain access to buffer and produce data for consumption
c. Call signal operation on semaphores mutex and full using semop function.
6. The consumer consumes 5 items as follows:
a. Call wait operation on semaphores full and mutex using semop function.
b. Gain access to buffer and consume the available data.
c. Call signal operation on semaphores mutex and empty using semop function.
7. Remove shared memory from the system using shmctl with IPC_RMID argument
8. Stop

PROGRAM :
#include<stdio.h>
int mutex =1,full=0,empty=3,choice,x=0,count=0,n;
void Producer(int c)
ROLL NO:2127220501141 Page | 43
{
mutex=wait(mutex);
printf("Producer produces item-%d",c);
empty=wait(empty);
full=signal(full);
mutex=signal(mutex);
}
void Consumer(int c)
{
mutex=wait(mutex);
printf("Consumer consumes item-%d",c);
full=wait(full);
empty=signal(empty);
mutex=signal(mutex);
}
wait(int s)
{
while(s<=0)
{
s--;
}
}
signal(int s)
{
s++;
}
void main()
{
printf("Enter size of buffer: ");
scanf("%d",&n);
while(x==0)
{
printf("\n1. Producer");
printf("\n2. Consumer");
printf("\n3. Exit the program");
printf("\nEnter your choice(1/2/3): ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
count=count+1;
if(count>n)
{
printf("The buffer is full");
}
else
ROLL NO:2127220501141 Page | 44
{
Producer(count);
}
break;
}
case 2:
{
count=count-1;
if(count==0)
{
printf("\nThe Buffer is empty");
}
else
{
Consumer(count);
}
break;
}
case 3:
{
x=1;
}
}
}
}
SAMPLE OUTPUT:
[cs22141@CO302 ~]$ cc semaphores.c
[cs22141@CO302 ~]$ ./a.out
Enter size of buffer: 3
1. Producer
2. Consumer
3. Exit the program
Enter your choice(1/2/3): 1
Producer produces item-1
1. Producer
2. Consumer
3. Exit the program
Enter your choice(1/2/3): 1
Producer produces item-2
1. Producer
2. Consumer
3. Exit the program
Enter your choice(1/2/3): 1
Producer produces item-3
1. Producer
2. Consumer
3. Exit the program
ROLL NO:2127220501141 Page | 45
Enter your choice(1/2/3): 1
The buffer is full
1. Producer
2. Consumer
3. Exit the program
Enter your choice(1/2/3): 2
Consumer consumes item-3
1. Producer
2. Consumer
3. Exit the program
Enter your choice(1/2/3): 2
Consumer consumes item-2
1. Producer
2. Consumer
3. Exit the program
Enter your choice(1/2/3): 2
Consumer consumes item-1
1. Producer
2. Consumer
3. Exit the program
Enter your choice(1/2/3): 2

The Buffer is empty


1. Producer
2. Consumer
3. Exit the program
Enter your choice(1/2/3): 3

RESULT:
ROLL NO:2127220501141 Page | 46
Thus synchronization between producer and consumer process for access to a
shared

CS22411 - OPERATING SYSTEMS LABORATORY


DATE:
EX.NO: 7

IMPLEMENTATIN OF BANKERS ALGORITHM


FOR DEADLOCK AVOIDANCE

AIM:
To implement Bankers algorithm in C for deadlock avoidance using safety algorithm
and resource request algorithm

ALGORITHM:
1. Start
2. Read the number of processes into n, number of resources into r
3. Set index <- 0
4. Declare arrays allocation[n][r], maximum[n][r], need[n][r], available[r], final_se-
quence[n], flags[n]
5. Read input for allocation matrix, maximum matrix, available array from user through
looping
6. Set i = 0, j = 0
7. Repeat steps 8 to 11 until i is less than n
8. Repeat steps 9 to 10 until j is less than r
9. Set need[i][j] <- maximum[i][j] - allocation[i][j]
10. Increment j
11. Increment i
12. Set all values of flags array to 0
13. Set k = 0, j = 0
14. Repeat steps 15 to 19 until k < n
15. Repeat steps 16 to 18 until j < n
16. Check if flags[i] equals 0 then
17. Check if each value in need[i] is less than each value in available matrix then set
final_sequence[index++]=i and increment each value in available matrix with the corre-
sponding value in allocation[i] and set flags[i] <- 1.
18. Increment j by 1
19. Increment k by 1
20. Check if all the values in flags array equal to 1 then Print final sequence array as the
safe state sequence if so deadlock is not detected.
21. Else Print "Deadlock detected".
22. Call resource function
23. Check if request <= need if true go to next step otherwise print error
24. Check if request <= available go to next step otherwise the process has to wait
25. available = available - request
26. allocation = allocation + request
27. need = need - request
ROLL NO:2127220501141 Page | 47
28. Print Check the safety new with values safety() function. If it's safe accept resource re-
quest else reject it.
29. Stop
PROGRAM:
#include <stdio.h>

int max[10][10];
int alloc[10][10];
int need[10][10];
int avail[10];
int work[10];
int finish[10];
int n, r = 3;

void read() {
int i, j;
printf("\nNumber of Processes: ");
scanf("%d", &n);
printf("\nEnter Allocation Matrix:\n");
for(i = 0; i < n; i++)
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);

printf("\nEnter Maximum Matrix:\n");


for(i = 0; i < n; i++)
for(j = 0; j < r; j++)
scanf("%d", &max[i][j]);

printf("\nEnter Available Matrix:\n");


for(j = 0; j < r; j++)
scanf("%d", &avail[j]);

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


for(j = 0; j < r; j++)
need[i][j] = max[i][j] - alloc[i][j];
}
}
void print() {
int i, j;
printf("\nNeed Matrix:\n");
for(i = 0; i < n; i++) {
for(j = 0; j < r; j++)
printf(" %d ", need[i][j]);
printf("\n");
}
printf("\nAvailable Matrix:\n");
for(j = 0; j < r; j++)
ROLL NO:2127220501141 Page | 48
printf(" %d ", avail[j]);
printf("\n");
}
int safety() {
int i, j, k, count = 0, cl = 0, flag = 0;
int safe_sequence[10];
int work[10];
for(j = 0; j < r; j++)
work[j] = avail[j];

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


finish[i] = 0;

while(count < n) {
flag = 0;
for(i = 0; i < n; i++) {
if(finish[i] == 0 && need[i][0] <= work[0] && need[i][1] <= work[1] &&
need[i][2] <= work[2]) {
for(k = 0; k < r; k++)
work[k] += alloc[i][k];
finish[i] = 1;
safe_sequence[count++] = i;
flag = 1;
}
}
if(flag == 0) break;
}
if(count == n) {
printf("\nSafe Sequence: ");
for(i = 0; i < n; i++)
printf("%d ", safe_sequence[i]);
printf("\nSafe state\n");
return 1;
} else {
printf("\nUnsafe state\n");
return 0;
}
}

void resource() {
int p, i, y, res[10];
printf("\nEnter the process number requesting resources: ");
scanf("%d", &p);

printf("\nEnter resource request: ");


for(i = 0; i < r; i++)
scanf("%d", &res[i]);
ROLL NO:2127220501141 Page | 49
for(i = 0; i < r; i++) {
if(res[i] > need[p][i]) {
printf("\nRequest exceeds Need\n");
return;
}
if(res[i] > avail[i]) {
printf("\nNot enough resources available\n");
return;
}
}

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


avail[i] -= res[i];
alloc[p][i] += res[i];
need[p][i] -= res[i];
}

y = safety();
if(!y) {
for(i = 0; i < r; i++) {
avail[i] += res[i];
alloc[p][i] -= res[i];
need[p][i] += res[i];
}
printf("\nRequest cannot be granted\n");
return;
} else {
printf("\nRequest granted\n");
print();
}
}
int main() {
int x;
read();
print();
x = safety();
if(x)
resource();
else
printf("Request cannot be accepted\n");
return 0;
}

ROLL NO:2127220501141 Page | 50


SAMPLE INPUT AND OUTPUT:

[cs22141@CS-01-103-CO273 ~]$ cc ex7.c


[cs22141@CS-01-103-CO273 ~]$ ./a.out

Number of Processes: 5

Enter Allocation Matrix:


010
200
302
211
002

Enter Maximum Matrix:


753
322
902
222
433

Enter Available Matrix:


332

Need Matrix:
7 4 3
1 2 2
6 0 0
0 1 1
4 3 1

Available Matrix:
3 3 2

Safe Sequence: 1 3 4 0 2
Safe state

Enter the process number requesting resources: 2


Enter resource request: 3 0 0

Safe Sequence: 3 1 2 4 0
Safe state

Request granted
ROLL NO:2127220501141 Page | 51
Need Matrix:
7 4 3
1 2 2
3 0 0
0 1 1
4 3 1

Available Matrix:
0 3 2

ROLL NO:2127220501141 Page | 52


RESULT:
Thus bankers algorithm was implemented with safety and resource request algorithm.

CS22411 - OPERATING SYSTEMS LABORATORY


DATE:
EX.NO: 8

IMPLEMENTATION OF RESOURCE REQUEST ALGORITHM

AIM:
To implement deadlock detection algorithm in C.

ALGORITHM:
1. Start
2. Read the number of processes into n, number of resources into r.
3. Set index <- 0
4. Declare arrays allocation[n][r], req[n][r], need[n][r], available[r], final_sequence[n],
flags[n].
5. Read input for allocation matrix, req matrix, available array from the user through
looping.
6. Set i = 0, j = 0
7. Repeat steps 8 to 11 until i is less than n
8. Repeat steps 9 to 10 until j is less than n
9. Check if flags[i] equals 0 then
10. Check if each value in req[i] is less than each value in available matrix then set
final_sequence[index++]=i and increment each value in available matrix with the
corresponding value in allocation[i] and set flags[i] <- 1.
11. Increment j
12. Increment i
13. Set all values of flags array to 0
14. Set k = 0, i = 0
15. Repeat steps 16 to 19 until k < n
16. Repeat steps 17 to 18 until i < n
17. Check if flags[i] equals 0 then
18. Check if each value in req[i] is less than each value in available matrix then set
final_sequence[index++]=i and increment each value in available matrix with the
corresponding value in allocation[i] and set flags[i] <- 1.
19. Increment i by 1
20. Increment k by 1
21. Check if all the values in flags array equal to 1 then Print final sequence array as the
safe state sequence if so deadlock is not detected.
22. Else print “Deadlock detected”
23. Stop

ROLL NO:2127220501141 Page | 53


PROGRAM:

#include <stdio.h>
int req[10][10];
int alloc[10][10];
int avail[10];
int work[10];
int finish[10];
int n, r = 3;

void read() {
int i, j;
printf("\nNumber of Processes: ");
scanf("%d", &n);
printf("\nEnter Allocation Matrix:\n");
for (i = 0; i < n; i++)
for (j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
printf("\nEnter Request Matrix:\n");
for (i = 0; i < n; i++)
for (j = 0; j < r; j++)
scanf("%d", &req[i][j]);
printf("\nEnter Available Matrix:\n");
for (i = 0; i < r; i++)
scanf("%d", &avail[i]);
}

void print() {
int i, j;
printf("\nAllocation Matrix\n");
for (i = 0; i < n; i++) {
for (j = 0; j < r; j++)
printf(" %d ", alloc[i][j]);
printf("\n");
}
printf("\nRequest Matrix\n");
for (i = 0; i < n; i++) {
for (j = 0; j < r; j++)
printf(" %d ", req[i][j]);
printf("\n");
}
printf("\nAvailable Matrix\n");
for (i = 0; i < r; i++)
printf(" %d ", avail[i]);
ROLL NO:2127220501141 Page | 54
printf("\n");
}

void safety() {
int i, j, k, c = 0, flag, count = 0;
for (i = 0; i < n; i++)
finish[i] = 0;
for (i = 0; i < r; i++)
work[i] = avail[i];
while (count < n) {
flag = 0;
for (i = 0; i < n; i++) {
int c = 0;
if (finish[i] == 0) {
for (j = 0; j < r; j++) {
if (req[i][j] <= work[j])
c++;
}
if (c == r) {
for (k = 0; k < r; k++)
work[k] += alloc[i][k];
finish[i] = 1;
count++;
flag = 1;
}
}
}
if (flag == 0) {
printf("\nUnsafe state, deadlock detected!\n");
return;
}
}
printf("\nSafe state, no deadlock detected.\n");
}

int main() {
read();
print();
safety();
return 0;
}

ROLL NO:2127220501141 Page | 55


SAMPLE INPUT & OUTPUT:

[cs22141@CS-01-103-CO273 ~]$ cc ex8.c


[cs22141@CS-01-103-CO273 ~]$ ./a.out

Number of Processes: 5

Enter Allocation Matrix:


010
200
303
211
002

Enter Request Matrix:


000
202
000
100
002

Enter Available Matrix:


000

Allocation Matrix
0 1 0
2 0 0
3 0 3
2 1 1
0 0 2

Request Matrix
0 0 0
2 0 2
0 0 0
1 0 0
0 0 2

Available Matrix
0 0 0

Safe state, no deadlock detected.

RESULT:
ROLL NO:2127220501141 Page | 56
Thus bankers algorithm was implemented with safety and resource request
algorithm.

CS22411 - OPERATING SYSTEMS LABORATORY


DATE:
EX.NO: 9 a)

IMPLEMENTATION OF MEMORY MANAGEMENT USING PAGING

AIM:
To write a C program to implement paging memory management technique to
convert the given logical address to physical address.

ALGORITHM:

1. Declare a page table structure that contains the page number and the corresponding
frame number for all the pages.
2. Enter the number of the pages and page size for each page.
3. Get the frame number for each page and store it in the structure.
4. Enter the logical address.
5. Calculate and retrieve the page number and pages offset form the logical address.
6. Display the page table and logical address containing page number and offset.
7. Retrieve the corresponding frame number for the calculated page number from the
page table.
8. With the frame number and offset, calculate the physical address.
9. Display the computed physical address.

PROGRAM:
#include<stdio.h>
int main()
{
int pgtable[10];
int psz,nop,i,la,pgno,off,pa;
printf(“Enter the number of pages:”);
scanf(“%d”,&nop);
printf(“Enter the frame number in the page table:”);
for(i=0;i<nop;i++)
{
scanf(“%d”,&pgtable[i]);
}
printf(“Enter the page size:”);
scanf(“%d”,&psz);
printf(“Enter the logical address:”);
scanf(“%d”,&la);
pgno = la/psz;
off = la%psz;
pa = pgtable[pgno]*psz+off;
ROLL NO:2127220501141 Page | 57
printf(“Physical Address:%d”,pa);
}

SAMPLE INPUT AND OUTPUT:

Enter the no of pages : 4


Enter the frame number in the page table : 4567
Enter the page size : 4
Enter the logical address : 13
Physical Address : 29

ROLL NO:2127220501141 Page | 58


RESULT:
Thus the implementation of paging technique has been successfully executed.

CS22411 - OPERATING SYSTEMS LABORATORY


DATE:
EX.NO: 9 b)

IMPLEMENTATION OF MEMORY MANAGEMENT USING SEGMENTATION

AIM:
To write a C program to implement paging using segmentation.

ALGORITHM:
1. Declare a segment table structure that contains the base address and limit of page.
2. Enter the number of segments and for each segment, enter the base and limit.
3. Get the frame number for each page and store it in the structure.
4. Enter the logical address.
5. Calculate and retrieve the corresponding base number and check if the offset is
within the limit.
6. With the segment number and offset, calculate the physical address.
7. Display the computed physical address.

PROGRAM:
#include<stdio.h>
struct segtable
{
int base;
int limit;
}

int main(){
struct segtable s[10]; int nos, i, sno, off, pa;
printf(“Enter the no. of segments:”);
scanf(“%d”,&nos);
printf(“Enter the base and limit of the segment table:”);
for(i=0;i<nos;i++)
{
scanf(“%d”,&s[i].base);
scanf(“%d”,&s[i].limit);
}
printf(“Enter the logical address(Segment No and Offset)”);
scanf(“%d %d”, &sno, &off);
if(s[sno].limit>off)
{
pa = s[sno].base + off;
printf(“Physical Address:%d\n”,pa);
ROLL NO:2127220501141 Page | 59
}
else
printf(“Invalid Address!”);
}
SAMPLE INPUT AND OUTPUT:

Enter the no. of segments : 4


Enter the base and limit in these segment table: 1000 100 2000 200
3000 300
4000 400
Enter the logical address(SegmentNoandOffset): 020
Physical Address: 1020

Enter the no. of segments : 4


Enter the base and limit in these segment table: 1000 100 2000 200
3000 300
4000 400
Enter the logical address(SegmentNoandOffset): 3450
Invalid Address!

RESULT:
ROLL NO:2127220501141 Page | 60
Thus the implementation of segmentation technique has been successfully executed.

ROLL NO:2127220501141 Page | 61

You might also like