0% found this document useful (0 votes)
12 views85 pages

Cs23422 Operating Systems Lab Manual

The document is a laboratory manual for CS23422, focusing on the basics of Linux commands. It covers file and directory commands, process information commands, text-related commands, file permission commands, and useful commands with examples and explanations. Each command is presented with its syntax, purpose, and sample output to aid students in practicing Linux operations.

Uploaded by

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

Cs23422 Operating Systems Lab Manual

The document is a laboratory manual for CS23422, focusing on the basics of Linux commands. It covers file and directory commands, process information commands, text-related commands, file permission commands, and useful commands with examples and explanations. Each command is presented with its syntax, purpose, and sample output to aid students in practicing Linux operations.

Uploaded by

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

CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex No :1 BASICS OF LINUX COMMANDS

AIM:
To execute and practice basics of Linux commands.

I File and Directory Related commands


1) pwd
This command prints the current working directory
[user@sys108 ~]$ pwd
/home/user

2) ls
This command displays the list of files in the current working directory.
$ls –l Lists the files in the long format
$ls –t Lists in the order of last modification time
$ls –d Lists directory instead of contents
$ls -u Lists in order of last access time
[user@sys108 ~]$ ls
hello.txt first.c perl1 sample hai.c

3) cd
This command is used to change from the working directory to any other directory specified.
$cd directoryname
[user@sys108 ~]$ cd jean
[user@sys108 jean]$

4) cd ..
This command is used to come out of the current working directory.
$cd ..
[user@sys108 jean]$ cd ..
[user@sys108 ~]$

5) mkdir
This command helps us to make a directory.
$mkdir directoryname
[user@sys108 ~]$ mkdir jean
[user@sys108 ~]$ ls
hello.txt first.c perl1 sample hai.c jean

6) rmdir
This command is used to remove a directory specified in the command line. It requires the
specified directory to be empty before removing it.
$rmdir directoryname
[user@sys108 ~]$ rmdir jean
hello.txt first.c perl1 sample hai.c

7) cat
This command helps us to list the contents of a file we specify.
$cat [option][file]
cat > filename – This is used to create a new file.
cat >>filename – This is used to append the contents of the file
[user@sys108 ~]$ cat > jean1
Have a Good Day
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
[user@sys108 ~]$ cat >> jean1
Welcome
[user@sys108 ~]$ cat jean1
Have a Good Day
Welcome

8) cp
This command helps us to create duplicate copies of ordinary files.
$cp source destination
[user@sys108 ~]$ cp jean1 jean2
[user@sys108 ~]$ cat jean2
Have a Good Day
Welcome

9) mv
This command is used to move or rename files.
$mv source destination
[user@sys108 ~]$ mv jean1 jean3
[user@sys108 ~]$ cat jean3
Have a Good Day
Welcome

10) ln
This command is to establish an additional filename for the same ordinary file.
$ln firstname secondname
user@sys108 ~]$ ln jean2 cse1

11) rm
This command is used to delete one or more files from the directory.
$rm [option] filename
$rm –i Asks the user if he wants to delete the file mentioned.
$rm –r Recursively delete the entire contents of the directory as well as the
directory itself.
[user@sys108 ~]$ rm jean2

II) Process and status information commands


1) who
This command gives the details of who all have logged in to the UNIX system currently.
$ who
[user@sys108 ~]$ who
user tty1 2014-11-11 19:16 (:0)
user pts/0 2014-11-11 19:19 (:0.0)
user pts/1 2014-11-11 19:19 (:0.0)

2) who am i
This command tells us as to when we had logged in and the system’s name for the
connection being used. $who am i
[user@sys108 ~]$ who am i
user pts/0 2014-11-11 19:19 (:0.0)

3) date
This command displays the current date in different formats.
+%D mm/dd/yy +%w Day of the week
+%H Hr-00 to 23 +%a Abbr.Weekday
+%M Min-00 to 59 +%h Abbr.Month
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
+%S Sec-00 to 59 +%r Time in AM/PM
+%T HH:MM:SS +%y Last two digits of the year
[user@sys108 ~]$ date
Tue Nov 11 19:39:14 IST 2014

4) echo
This command will display the text typed from the keyboard.
$echo
[user@sys108 ~]$ echo welcome to 2015
welcome to 2015

III Text related commands


1. head
This command displays the initial part of the file. By default it displays first ten lines of the
file.
$head [-count] [filename]
[user@sys108 ~]$ head -1 jean3
Have a Good Day

2. tail
This command displays the later part of the file. By default it displays last ten lines of the
file.
$tail [-count] [filename]
[user@sys108 ~]$ tail -1 jean3
Welcome

3. wc
This command is used to count the number of lines, words or characters in a file.
$wc [-lwc] filename
[user@sys108 ~]$ wc -lwc jean3
2 4 24 jean3

4. find
The find command is used to locate files in a directory and in a subdirectory.
The –name option
This lists out the specific files in all directories beginning from the named
directory. Wild cards can be used.
The –type option
This option is used to identify whether the name of files specified are
ordinary files or directory files. If the name is a directory then use “-type d
“and if it is a file then use “-type f”.
The –mtime option
This option will allow us to find that file which has been modified before
or after a specified time. The various options available are –mtime n(on a
particular day),-mtime +n(before a particular day),-mtime –n(after a particular
day)
The –exec option
This option is used to execute some commands on the files that are found
by the find command.
[user@sys108 ~]$ find fc.c
fc.c

IV File Permission commands


1) chmod
Changes the file/directory permission mode: $ chmod 777 file1
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Gives full permission to owner, group and others
$ chmod o-w file1
Removes write permission for others.
[user@sys108 ~]$ chmod 777 welcome.txt

V Useful Commands:
1) exit - Ends your work on the UNIX system.
[user@sys108 ~]$ exit
exit
There are stopped jobs.

2) Ctrl-l or clear
Clears the screen.
[user@sys108 ~]$ clear
[user@sys108 ~]$

3) Ctrl-c
Stops the program currently running.

4) Ctrl-z
Pauses the currently running program.

5) man COMMAND
Looks up the UNIX command COMMAND in the online manual pages.
[user@sys108 ~]$ man
What manual page do you want?
[user@sys108 ~]$ man ls

6) history
List all commands typed so far.
[user@sys108 ~]$ history
109 man
110 man help
111 man ls
112 history

7) more FILE
Display the contents of FILE, pausing after each screenful.
There are several keys which control the output once a screenful has been printed.
<enter> Will advance the output one line at a time.
<space bar> Will advance the output by another full screenful.
"q" Will quit and return you to the UNIX prompt.
[user@sys108 ~]$ more jean3
Have a Good Day
Welcome

8) less FILE
"less" is a program similar to "more", but which allows backward movement
in the file as well as forward movement.
[user@sys108 ~]$ less jean3
Have a Good Day
Welcome
jean3 (END)

9) lpr FILE
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
To print a UNIX text or PostScript file, type the following command at the system
prompt:
[user@sys108 ~]$ lpr jean3
lpr: Error - no default destination available.

Explanation of the above commands:

1. TASK : To display the system date and time


COMMAND : date
SYNTAX : date
EXPLANATION: This command displays the current system date and time on the screen.
OUTPUT :
[exam1@local host ~]$date Thu Nov 27 10:37:05 IST 2013

i. TASK : To display the current month.


COMMAND : date
SYNTAX : date +%m
EXPLANATION: This command displays the current month on the screen.
OUTPUT :
[exam1@local host ~]$date +%m 11

ii. TASK : To display the name of the current month.


COMMAND : date
SYNTAX : date +%h
EXPLANATION: This command displays the name of the current month on the screen
OUTPUT :
[exam1@local host ~]$date +%h Nov

iii. TASK : To display the current system date.


COMMAND : date
SYNTAX : date +%d
EXPLANATION: This command displays the current system date on the screen.
OUTPUT :
[exam1@local host ~]$date +%d 27

iv.TASK : To display the current system (year)


COMMAND : date
SYNTAX : date +%y & date +%Y
EXPLANATION: This command displays the current system year on the screen.
OUTPUT :
[exam1@local host ~]$date +%y 13
[exam1@local host ~]$date +%Y 2013

v.TASK : To display the current system time.


COMMAND : date
SYNTAX : date +%H
EXPLANATION: This command displays the current system time (in hour) on the
screen.
OUTPUT :
[exam1@local host ~]$date +%H 10

vi. TASK : To display the current system time.


COMMAND : date
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
SYNTAX : date +%M
EXPLANATION: This command displays system time (in min) on the screen.
OUTPUT :
[exam1@local host ~]$date +%M 49

vii.TASK : To display the current system time.


COMMAND : date
SYNTAX : date +%S
EXPLANATION: This command displays the current system time (in sec) on the
screen.
OUTPUT :
[exam1@local host ~]$date +%S 50

2. TASK : To display the calendar of the current month.


COMMAND : calendar
SYNTAX : cal (or)cal -1
EXPLANATION: This command displays the calendar of the current month on
the screen.
-1 Display single month output. (This is the default.)

-3 Display prev/current/next month output.

-s Display Sunday as the first day of the week. (This is the default.)

-m Display Monday as the first day of the week.

-j Display Julian dates (days one-based, numbered from January 1).

-y Display a calendar for the current year.


OUTPUT :
[exam1@local host ~] $ cal November 2013
Su Mo Tu We Th Fr Sa
12
34 5 6 789
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

[exam1@localhost ~]$ cal -3 9 2013

August 2013 September 2013 October 2013


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

i. TASK : To display the calendar of a year.


COMMAND : cal
SYNTAX : cal year EXAMPLE : cal 2007
EXPLANATION: This command displays the calendar of the specified year. OUTPUT
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
:
[exam88@local host ~] $ cal 2012
It displays all the month of the year 2012

3.TASK : To display the user defined message


COMMAND : echo
SYNTAX : echo “message”
EXPLANATION: This command display on the screen the argument of the echo
command.
OUTPUT :
[exam1@local host ~] $ echo “Hello” Hello

4. TASK : To display the detail of all users.


COMMAND : who
SYNTAX : who
EXPLANATION : This command lists the information about all the users who have
logged on that system.
OUTPUT :
[exam88@local host ~] $ who
exam80 pts/18 2013-01-23 14.48 <172.17.3.51>
exam18 pts/12 2013-01-23 14.39 <172.17.3.51>

i.TASK : To display the user detail.


COMMAND : who
SYNTAX :whoami
EXPLANATION : This command displays the information about the current user of
the system on the screen.
OUTPUT :
[exam88@local host ~] $ whoami exam88

5.TASK : To create directory.


COMMAND : make directory
SYNTAX :mkdir
EXPLANATION : This command is used to create a new directory with a specified
name. EXAMPLE : mkdir student
OUTPUT :
[exam88@local host ~] $ mkdir sun [exam88@local host ~] $ ls Palindrome.c
palindrome.sh Morn.text good sun

6.TASK : To change directory


COMMAND : change directory
SYNTAX : cd directory name
EXAMPLE : cd sun
EXPLANATION : This command is used to switch from one directory to another.
OUTPUT :
[exam88@local host ~] $ cd sun [exam88@local host sun] $

7.TASK : To come out of sub-directory.


COMMAND : change directory SYNTAX : cd
EXPLANATION : This command help in switching to the main directory.
OUTPUT :
[exam88@local host sun] $ cd [exam88@local host ~] $

8.TASK : To delete a directory.


CS23422 OPERATING SYSTEMS LABORATORY MANUAL
COMMAND : remove directory SYNTAX : rmdir directory name
EXPLANATION : This command is used to delete the specified directory. OUTPUT :
[exam88@local host ~] $ rmdir sun [exam88@local host ~] $ cd sun No such file or
directory.

9.TASK : To list all the files and directories.


COMMAND : list
SYNTAX :ls
EXPLANATION : This command display all the files and directories of the system.
OUTPUT :
[exam88@local host ~] $ ls Palindrome.c palindrome.sh Morn.text good

10.TASK : To create a file.


COMMAND : cat
SYNTAX : cat > file name
EXAMPLE :cat> wind.txt
EXPLANATION : This command leads to the creation of a new file with the specified
filename content.
OUTPUT :
[exam88@local host ~] $ cat> wind.txt Hai good morning
Have a Nice Day
1] + stopped cat > wind.txt [exam88@local host ~] $ cat> moon.txt Hello how
are you.
Take care of ur Health. (Press Ctrl+D to exit)
2] + stopped cat > moon.txt

11.TASK : To view a file


COMMAND : cat
SYNTAX : cat filename
EXAMPLE : cat wind.txt
EXPLANATION: This command displays the content of the specified files. OUTPUT
:
[exam88@local host ~] $ cat wind.txt Hai good morning
Have a Nice Day

12.TASK : To copy a file


COMMAND : copy
SYNTAX : cp source file destination file
EXAMPLE : cp wind.txt moon.txt

EXPLANATION: This command produces a copy of the source file to be stored in the
specified destination file of overwriting its previous content if exist.
OUTPUT :
[exam88@local host ~] $ cp wind.txt moon.txt [exam88@local host ~] $ cat
moon.txt
Hai good morning Have a Nice Day
EXPLANATION: This command produces a copy of the source file to be stored in
the specified destination file(by creating it) .
[exam88@local host ~] $ cp wind.txt star.txt [exam88@local host ~] $ cat star.txt
Hai good morning Have a Nice Day

13.TASK : To move a file.


COMMAND : move
SYNTAX : mv source file destination file
EXAMPLE : mv wind.txt moon.txt
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
EXPLANATION : This command moves the content of the source file to destination
file. The content of the source file is deleted.
OUTPUT :
[exam88@local host ~] $ mv wind.txt moon.txt [exam88@local host ~] $ cat
wind.txt
No such file or directory.

14.TASK : To cut a column from a file.


COMMAND : cut
SYNTAX : cut -c column number filename
EXAMPLE : cut –c 5-10 star.txt
EXPLANATION : This command displays the character of particular column in the
specified field.
OUTPUT :
[exam1@localhost ~]$ cut -c 5-10 star.txt good m
a Nic

15.TASK : To delete a file.


COMMAND : remove
SYNTAX :rm filename
EXAMPLE : rm star.txt
EXPLANATION : This command deletes the specified file from the directory.
OUTPUT :
[exam88@local host ~] $ rm star.txt [exam88@local host ~] $ cat star.txt No such
file or directory.

16. TASK : This command prints the line matching the pattern. grep(globally search a
regular expression and print)
COMMAND : grep
SYNTAX : grep ‘string’ filename
EXAMPLE : grep ‘stat’ stat1.c
OUTPUT :
[exam1@CSELAB1 ~]$ grep 'stat' stat1.c #include<sys/stat.h>
struct stat st; s=stat("fork1.c",&st);
printf("\n use of stat() is unsuccessful ");

17. TASK :To change file access permission.


COMMAND : chmod
EXPLANATION: To change the permission of a file.

18.TASK : To sort the content


COMMAND : sort
SYNTAX : sort file name
EXAMPLE : sort moon.txt
EXPLANATION: This command helps in sorting the content of a file in ascending
order.
OUTPUT :
[exam88@local host ~] $ sort moon.txt Hai good morning
Have a Nice Day

19. TASK : To display no.of characteristics in a file.


COMMAND : word count
SYNTAX : wc file name
EXAMPLE : wc moon.txt
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
EXPLANATION : This command displays the no.of rows, words and character in the
file.

• wc -l <filename> print the line count


• wc -m <filename> print the character count
• wc -L <filename> print the length of longest line
• wc -w <filename> print the word count OUTPUT :
[exam88@local host ~] $ wc –l –w –m moon.txt (or) [exam88@local host ~] $ wc
moon.txt
2 7 33 moon.txt

20. TASK : To display the manual pages.


COMMAND : man
SYNTAX : man command EXAMPLE : man cat
EXPLANATION : This command formats and displays the online manual pages.

21. TASK : To clear the screen.


COMMAND : clear
EXPLANATION : This command is useful for creating or editing programs.
SYNTAX : vi filename
EXAMPLE : vi fork.c

After completing the program in text editor press Esc+Shift+: (colon) wq to exit.

RESULT:

The linux commands has been successfully executed.


CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex. No: 2(a)Implementation of LINUX system calls : fork, exec, getpid, exit, wait, close

AIM
To write a program for implementing process management using the following
system calls of UNIX operating system: fork, exec, getpid, exit, wait, close.

ALGORITHM
1. Read the input from the command line.
2. Use fork() system call to create process, getppid() system call used to get the
parent process ID and getpid() system call used to get the current process ID
3. execvp() system call used to execute that command given on that command line
argument
4. execlp() system call used to execute specified command.
5. Open the directory at specified in command line input.
6. Display the directory contents.

PROGRAM

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char * argv[])
{
char * ls_args[3] = { "ls", "-l", NULL} ;
pid_t c_pid, pid;
int status;
c_pid = fork();
if (c_pid == 0)
{
printf("Child: executing ls\n");
execvp( ls_args[0], ls_args);
perror("execve failed");
}
else if (c_pid > 0)
{
if( (pid = wait(&status)) < 0)
{
perror("wait");
_exit(1);
}
printf("Parent: finished\n");
}else
{
perror("fork failed");
_exit(1);
}
return 0;
}
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

OUTPUT
[user@sys108 ~]$ cc simulate.c
[user@sys108 ~]$ ./a.out
Child: executing
Hello.txt
Sample.txt
Second.txt
Parent: finished

RESULT
Thus the program for implementation of various LINUX system calls was executed
successfully
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex No:2 (b) Implementation of Unix system calls : opendir, readdir.

AIM
To write a program for implementing the following directory system calls of UNIX
operating system: opendir, readdir.

ALGORITHM
1.Open the directory specified in command line input.
2. Display the directory contents.

PROGRAM
#include<sys/types.h>
#include<dirent.h>
#include<stdio.h>
main(int c,char* arg[])
{
DIR *d;
struct dirent *r;
d=opendir(arg[1]);
printf("\n\t Name of the Files \n");
while((r=readdir(d)) != NULL)
printf("\t %s \n",r->d_name);
}

OUTPUT
[user@sys108 ~]$ cc dr.c
[user@sys108 ~]$ ./a.out lab_print
Name of the Files
pri_output.doc
sjf_output.doc
fcfs_output.doc
rr_output.doc
ipc_pipe_output.doc
pro_con_prob_output.doc

RESULT
Thus the program for implementing directory system calls was successfully executed.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex No: 3 SIMULATION OF UNIX COMMANDS

AIM
To write a C program to simulate UNIX commands like ls,cp,grep.

ALGORITHM
1. Create a file using cat command.
2. Simulate ls command to list all the files in current working directory
3. Open the file in read mode and copy the contents of the file.
4. Input the word to be searched in the file.
5. Display the word if searching is successful.

PROGRAM
(i) ls
#include <sys/types.h>
#include <sys/dir.h>
#include <sys/param.h>
#include <stdio.h>
#define FALSE 0
#define TRUE 1
extern int alphasort();
char pathname[MAXPATHLEN];
main() {
int count,i;
struct dirent **files;
int file_select();
if (getwd(pathname) == NULL )
{
printf("Error getting pathn");
}
printf("Current Working Directory = %sn",pathname);
count = scandir(pathname, &files, file_select, alphasort);
if (count <= 0)
{
printf("No files in this directoryn");
}
printf("Number of files = %dn",count);
for (i=1;i<count;++ i)
printf("%s \n",files[i-1]->d_name);
}
int file_select(struct direct *entry)
{
if ((strcmp(entry->d_name, ".") == 0) ||(strcmp(entry->d_name, "..") == 0))
return (FALSE);
else
return (TRUE);
}

OUTPUT
[user@sys108 ~]$ gcc list.c
[user@sys108 ~]$./a.out
Current working directory=/home/student/
Number of files=57
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
(ii) cp
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[] )
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
close(fd1);
close(fd2);
}

OUTPUT
[user@sys108 ~]$ cat > first.txt
hello
hai
[user@sys108 ~]$ gcc copy.c
[user@sys108 ~]$ ./a.out first.txt second.txt
[user@sys108 ~]$ cat second.txt
hello
hai

(iii)grep
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<string.h>
#include <fcntl.h>
void match_pattern(char *argv[])
{
int fd,r,j=0;
char temp,line[100];
if((fd=open(argv[2],O_RDONLY)) != -1)
{
while((r=read(fd,&temp,sizeof(char)))!= 0)
{
if(temp!='\n')
{
line[j]=temp;
j++;
}
else
{
if(strstr(line,argv[1])!=NULL)
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
printf("%s\n",line);
memset(line,0,sizeof(line));
j=0;
}

}
}
}

main(int argc,char *argv[])


{
struct stat stt;
if(argc==3)
{
if(stat(argv[2],&stt)==0)
match_pattern(argv);
else
{
perror("stat()");
exit(1);
}
}
}

OUTPUT
[user@sys108 ~]$ cc grep.c
[user@sys108 ~]$ ./a.out hello first.txt
hello

RESULT
Thus the C program to simulate LINUX commands like ls,cp,grep was executed
successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex.No : 4(a) COMPARISON OF TWO STRINGS

AIM
To write a shell program to compare the two strings.

ALGORITHM
1. Enter into the vi editor and go to the insert mode for entering the code
2. Read the first string.
3. Read the second string
4. Compare the two strings using the if loop
5. If the condition satisfies then print that two strings are equal else print two
strings are not equal.
6. Enter into the escape mode for the execution of the result and verify the output

PROGRAM
echo “enter the first string”
read str1
echo “enter the second string”
read str2
if [ $str1 = $str2 ]
then
echo “strings are equal”
else
echo “strings are unequal”
fi

OUTPUT
[user@sys108 ~]$ vi compare.sh
[user@sys108 ~]$ sh compare.sh
Enter first string: hai
Enter second string: cse
strings are unequal

RESULT
Thus the shell program to compare the two strings is executed and output is verified
successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex.No: 4(b) MAXIMUM OF THREE NUMBERS

AIM
To write a shell program to find greatest of three numbers.

ALGORITHM
1. Declare the three variables.
2. Check if A is greater than B and C.
3. If so print A is greater.
4. Else check if B is greater than C.
5. If so print B is greater.
6. Else print C is greater.

PROGRAM
echo "Enter A"
read a
echo "Enter B"
read b
echo "Enter C"
read c
if [ $a -gt $b -a $a -gt $c ]
then
echo "A is greater"
elif [ $b -gt $a -a $b -gt $c ]
then
echo "B is greater"
else
echo "C is greater"
fi

OUTPUT
[user@sys108 ~]$ vi greater.sh
[user@sys108 ~]$ sh greater.sh
Enter A:23
Enter B:45
Enter C:67
C is greater

RESULT
Thus the shell program to find the maximum of three numbers is executed and output
is verified successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex: No : 5(a) FCFS SCHEDULING

AIM
To write a C program to implement FCFS scheduling algorithm.

ALGORITHM

1. Get the number of processes and their burst time.


2. Initialize the waiting time for process 1 and 0.
3. The waiting time for the other processes are calculated as follows:
for(i=2;i<=n;i++),wt.p[i]=p[i-1]+bt.p[i-1].
4. The waiting time of all the processes is summed then average value time is
calculated.
5. The waiting time of each process and average times are displayed.

PROGRAM
#include<stdio.h>
struct process
{
int pid; int bt; int wt,tt;
}
p[10];
int main(){
int i,n,totwt,tottt,avg1,avg2;
printf("Enter the no of process \n");
scanf("%d",&n);
for(i=1;i<=n;i++){
p[i].pid=i;
printf("Enter the burst time \n");
scanf("%d",&p[i].bt);
}
p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n){
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
i++; }
i=1;
totwt=tottt=0;
printf("\n processid \t bt\t wt\t tt\n");
while(i<=n){
printf("\n\t%d \t%d \t%d \t%d",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt; i++; }
avg1=totwt/n;
avg2=tottt/n;
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
printf("\navg1=%d \t avg2=%d \t",avg1,avg2);
return 0;
}

OUTPUT
[user@sys108 ~]$ vi first.c
[user@sys108 ~]$ cc first.c
[user@sys108 ~]$ ./a.out
Enter the no of process
3
Enter the burst time
2
Enter the burst time
4
Enter the burst time
6
processid bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12
avg1=2 avg2=6

RESULT
Thus the FCFS program for scheduling was executed and verified successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex: No : 5(b) SJF SCHEDULING

AIM
To write a C program to implement Shortest Job First scheduling algorithm.

ALGORITHM

1. Initialize the waiting time for process 1 as 0.


2. The processes are stored according to their burst time.
3. The waiting time for the processes are calculated as follows:
for(i=2;i<=n;i++).wt.p[i]=p[i=1]+bt.p[i-1].
4. The waiting time of all the processes summed and then the average time is
calculated.
5. The waiting time of each processes and average time are displayed.

PROGRAM

#include<stdio.h>
struct process{
int pid; int bt; int wt; int tt;
}p[10],temp;
int main(){
int i,j,n,totwt,tottt;
float avg1,avg2;
printf("\nEnter the number of process:\t");
scanf("%d",&n);
for(i=1;i<=n;i++){
p[i].pid=i;
printf("\nEnter the burst time:\t");
scanf("%d",&p[i].bt); }
for(i=1;i<n;i++){
for(j=i+1;j<=n;j++){
if(p[i].bt>p[j].bt){
temp.pid=p[i].pid;
p[i].pid=p[j].pid;
p[j].pid=temp.pid;
temp.bt=p[i].bt;
p[i].bt=p[j].bt;
p[j].bt=temp.bt;
}}}
p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n){
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
i++; }
i=1;
totwt=tottt=0;
printf("\nProcess id \tbt \twt \ttt");
while(i<=n){
printf("\n\t%d \t%d \t%d \t%d\n",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt; i++; }
avg1=totwt/n;
avg2=tottt/n;
printf("\nAVG1=%f\t AVG2=%f",avg1,avg2);
return 0;
}

OUTPUT
[user@sys108 ~]$ vi shortest.c
[user@sys108 ~]$ cc shortest.c
[user@sys108 ~]$ ./a.out
Enter the number of process: 3
Enter the burst time: 2
Enter the burst time: 4
Enter the burst time: 6
Process id bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12
AVG1=2.000000 AVG2=6.000000

RESULT
Thus the SJF program was executed and verified successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex. No : 5(c) PRIORITY SCHEDULING

AIM
To write a C program to implement priority scheduling algorithm.

ALGORITHM

1. Read burst time, waiting time, turnaround time and priority.


2. Initialize the waiting time for process 1 and 0
3. Based up on the priority process are arranged.
4. The waiting time for other processes are calculated based on priority.
5. The waiting time of all the processes is summed and then the average waiting time is
calculated.
6. The waiting time of each process and average waiting time are displayed based on the
priority.

PROGRAM

#include<stdio.h>
struct process{
int pid; int bt; int wt; int tt; int prior;
} p[10],temp;
int main(){
int i,j,n,totwt,tottt,arg1,arg2;
printf("Enter the number of process");
scanf("%d",&n);
for(i=1;i<=n;i++){
p[i].pid=i;
printf("Enter the burst time");
scanf("%d",&p[i].bt);
printf("\n Enter the priority");
scanf("%d",&p[i].prior);
}
for(i=1;i<n;i++){
for(j=i+1;j<=n;j++){
if(p[i].prior>p[j].prior){
temp.pid=p[i].pid;
p[i].pid=p[j].pid;
p[j].pid=temp.pid;
temp.bt=p[i].bt;
p[i].bt=p[j].bt;
p[j].bt=temp.bt;
temp.prior=p[i].prior;
p[i].prior=p[j].prior;
p[j].prior=temp.prior;
}}}
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
p[i].wt=0;
p[1].tt=p[1].bt+p[1].wt; i=2;
while(i<=n)
{
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
i++;
} i=1;
totwt=tottt=0;
printf("\n process \t bt \t wt \t tt");
while(i<=n){
printf("\n%d\t %d\t %d\t %d\t",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++; }
arg1=totwt/n;
arg2=tottt/n;
printf("\n arg1=%d \t arg2=%d\t",arg1,arg2);
return 0;
}

OUTPUT
[user@sys108 ~]$ vi priority.c
[user@sys108 ~]$ cc priority.c
[user@sys108 ~]$ ./a.out
Enter the number of process 3
Enter the burst time 2
Enter the priority 3
Enter the burst time 4
Enter the priority 1
Enter the burst time 6
Enter the priority 2
process bt wt tt
2 4 0 4
3 6 4 10
1 2 10 12

avg1=4 avg2=8

RESULT
Thus the priority scheduling program was executed and verified successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex: No : 5(d) ROUND ROBIN SCHEDULING

AIM
To write a C program to implement Round Robin Scheduling algorithm.

ALGORITHM

1. Initialize the array for Round Robin circular queue as ‘0’.

2. The burst time of each process is divided and the quotients are stored on the round
robin array.

3. According to the array value the waiting time for each process and the average time
are calculated as line the other scheduling.

4. The waiting time for each process and average times are displayed.

PROGRAM
#include<stdio.h>
struct process{
int pid,bt,tt,wt;
};
int main()
{
struct process x[10],p[30];
int i,j,k,tot=0,m,n;
float wttime=0.0,tottime=0.0,a1,a2;
printf("\nEnter the number of process:\t");
scanf("%d",&n);
for(i=1;i<=n;i++){
x[i].pid=i;
printf("\nEnter the Burst Time:\t");
scanf("%d",&x[i].bt);
tot=tot+x[i].bt;
}
printf("\nTotal Burst Time:\t%d",tot);
p[0].tt=0; k=1;
printf("\nEnter the Time Slice:\t");
scanf("%d",&m);
for(j=1;j<=tot;j++){
for(i=1;i<=n;i++){
if(x[i].bt!=0){ p[k].pid=i;
if(x[i].bt-m<0){
p[k].wt=p[k-1].tt;
p[k].bt=x[i].bt;
p[k].tt=p[k].wt+x[i].bt;
x[i].bt=0;
k++; }
else{
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
p[k].wt=p[k-1].tt;
p[k].tt=p[k].wt+m; x[i].bt=x[i].bt-m; k++;
}
}
}
}
printf("\nProcess id \twt \ttt");
for(i=1;i<k;i++){
printf("\n\t%d \t%d \t%d",p[i].pid,p[i].wt,p[i].tt);
wttime=wttime+p[i].wt;
tottime=tottime+p[i].tt;
a1=wttime/n;
a2=tottime/n; }
printf("\n\nAverage Waiting Time:\t%f",a1);
printf("\n\nAverage TurnAround Time:\t%f",a2);
return 0; }

OUTPUT
[user@sys108 ~]$ vi roundrobin.c
[user@sys108 ~]$ cc roundrobin.c
[user@sys108 ~]$ ./a.out
Enter the number of process: 3
Enter the Burst Time: 3
Enter the Burst Time: 5
Enter the Burst Time: 7
Total Burst Time: 15
Enter the Time Slice: 2
process id wt tt
1 0 2
2 2 4
3 4 6
1 6 7
2 7 9
3 9 11
2 11 12
3 12 14
3 14 15
Average Waiting Time: 21.666666
Average TurnAround Time: 26.666666

RESULT
Thus the Round Robin scheduling program was executed and verified successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex.No : 6 IMPLEMENTATION OF SEMAPHORE

AIM
To implement Producer Consumer problem using Semaphore.

ALGORITHM
1. Union a variable “mysemun” as integer type to implement semaphore.
2. A buffer “sembuf” variable for producer consumer is written
3. In producer, buffer “sembuf” full condition is checked and if it is full then it is
displayed.
4. In consumer, buffer “sembuf” empty condition is checked and a message displayed.
5. Producer produces an element sequentially from main().and a message displayed.
6. Consumer consumes an element sequentially from main().and a message displayed.
7. The producer consumer produces messages are displayed till the user defines in the
program.

PROGRAM
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>
#define num 10
#define se 10
#define sf 0
int main()
{
int rc,pid,semid;
int shmid,status,i;
char elem;
union semun
{
int val;
}mysemun;
struct sembuf waitempty={se,-1,SEM_UNDO};
struct sembuf signalempty={se,1,IPC_NOWAIT};
struct sembuf waitfull={sf,-1,SEM_UNDO};
struct sembuf signalfull={sf,1,IPC_NOWAIT};
struct shmid_ds myshmid_ds;
void *shmptr;
semid=semget(IPC_PRIVATE,2,0666 | IPC_CREAT);
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
mysemun.val=num;
semctl(semid,se,SETVAL,mysemun);
mysemun.val=0;
semctl(semid,sf,SETVAL,mysemun);
shmid=shmget(IPC_PRIVATE,num,0666 | IPC_CREAT);
pid=fork();
if(pid==0)
{
shmptr=shmat(shmid,0,SHM_R);
for(i=0;i<10;i++)
{
semop(semid,&waitfull,1);
elem=*((char *)shmptr+(i%num));
printf("consumed element %c\n",elem);
semop(semid,&signalempty,1);
sleep(1);
}
exit(0);
}
else
{
shmptr=shmat(shmid,0,SHM_W);
for(i=0;i<10;i++)
{
semop(semid,&waitempty,1);
elem='i'+i;
printf("produced element %c\n",elem);
*((char *)shmptr+(i%num))=elem;
semop(semid,&signalfull,1);
sleep(2);
}
}
wait(&status);
shmctl(shmid,IPC_RMID,&myshmid_ds);
semctl(semid,se,IPC_RMID,mysemun);
exit(0);
}

OUTPUT
[user@sys108 ~]$ vi producer.c
[user@sys108 ~]$ cc producer.c
[user@sys108 ~]$ ./a.out
produced element r
consumed element r
produced element c
consumed element c
produced element d
consumed element d
produced element f
consumed element f
produced element h
consumed element h
produced element i
consumed element i
produced element j
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
consumed element j
produced element k
consumed element k
produced element l
consumed element l
produced element m
consumed element m

RESULT
Thus the Producer Consumer problem using Semaphore is written and executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex.No: 7 IMPLEMENTATION OF SHARED MEMORY AND IPC
AIM
To write a C program to illustrate interprocess communication using Shared Memory system calls.
ALGORITHM
1. Create shared memory using shmget( ) system call
2. If successfull it returns positive value
3. Attach the created shared memory using shmat( ) systemcall.
4. Write to shared memory using shmsnd( ) system call
5. Read the contents from shared memory using shmrcv( ) systemcall
PROGRAM
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main () {
int segment_id;
char* shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
segment_id = shmget (IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
shmctl (segment_id, IPC_STAT, &shmbuffer);
segment_size = shmbuffer.shm_segsz;
printf ("segment size: %d\n", segment_size);
sprintf (shared_memory, "Hello, World");
shmdt (shared_memory);
shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0);
printf ("shared memory reattached at address %p\n", shared_memory);
printf ("%s\n", shared_memory);
shmdt (shared_memory);
shmctl (segment_id, IPC_RMID, 0);
return 0; }

OUTPUT
user@sys108 ~]$ ./a.out
shared memory attached at address 0xb774d000
segment size: 25600
shared memory reattached at address 0x5000000
Hello , World.

RESULT
Thus the program for Interprocess communication using Shared Memory system calls was executed
successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex.No : 8 BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE

AIM
To implement Deadlock Avoidance by using Banker’s Algorithm in C.

ALGORITHM

 Start the program.


 Get the values of resources and processes.
 Get the avail value.
 After allocation find the need value.
 Check whether it’s possible to allocate.
 If it is possible then the system is in safe state.
 Else system is not in safety state.
 If the new request comes then check that the system is in safety or not if we allow the request.
 Stop the program.

PROGRAM
#include<stdio.h>
#include<process.h>
int main()
{
int allocation[10][5], max[10][5], need[10][5], available[3], flag[10], sq[10];
int n, r, i, j, k, count, count1 = 0;
printf("\n Input the number of processes running ( <10 )..");
scanf("%d", &n);
for (i = 0; i<10; i++)
flag[i] = 0;
printf("\n Input the number of resources ( <5 )..");
scanf("%d", &r);
printf("\n Input the allocation matrix for the processes in row major order..\n");
for (i = 0; i<n; i++)
{
printf("\n Process %d\n", i);
for (j = 0; j<r; j++)
{
printf("\n Resource %d\n", j);
scanf("%d", &allocation[i][j]);
}
}
printf("\n Input the no. of resources that a process can maximum have..\n");
for (i = 0; i<n; i++)
{
printf("\n Process %d\n", i);
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
for (j = 0; j<r; j++)
{
printf("\n Resource %d\n", j);
scanf("%d", &max[i][j]);
}
}
printf("\n Input the no. of available instances of each resource..\n");
for (i = 0; i<r; i++)
{
printf("\n Resource %d : ", i);
scanf("%d", &available[i]);
}
printf("\n The need matrix is as follows : \n");
for (i = 0; i<n; i++)
{
for (j = 0; j<r; j++)
{
need[i][j] = max[i][j] - allocation[i][j];
printf("\t %d", need[i][j]);
}
printf("\n");
}
do{
for (k = 0; k<n; k++)
{
for (i = 0; i<n; i++)
{
if (flag[i] == 0)
{
count = 0;
for (j = 0; j<r; j++)
{
if (available[j] >= need[i][j])
count++;
}
if (count == r)
{
count1++;
flag[i] = 1;
sq[count1 - 1] = i;
for (j = 0; j<r; j++)
{
available[j] = available[j] + allocation[i][j];
}
break;
}
}
}
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
}
if (count1 != n)
{
printf("\n---------------IT IS UNSAFE STATE---------------");
break;
}
} while (count1 != n);
if (count1 == n)
{
printf("\n *******************IT IS SAFE STATE*******************");
printf("\n The safe sequence is....\n");
for (i = 0; i<n; i++)
printf("\t P%d", sq[i]);
printf("\n");
printf("\n The available matrix is now : ");
for (i = 0; i<r; i++)
printf("\t %d", available[i]);
}
return 0;
}

OUTPUT

[user@sys108 ~]$ vi avoidance.c


[user@sys108 ~]$ cc avoidance.c
[user@sys108 ~]$ ./a.out
Input the number of processes running ( <10 )..2
Input the number of resources ( <5 )..2
Input the allocation matrix for the processes in row major order..
Process 0
Resource 0
1
Resource 1
0
Process 1
Resource 0
2
Resource 1
1
Input the no. of resources that a process can maximum have.
Process 0
Resource 0
2
Resource 1
1
Process 1
Resource 0
3
Resource 1
2
Input the no. of available instances of each resource..
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Resource 0 : 8
Resource 1 : 4
The need matrix is as follows :
1 1
1 1

*******************IT'S A SAFE STATE*******************


The safe sequence is....
P0 P1
The available matrix is now : 11 5

RESULT
Thus deadlock avoidance by using Banker’s Algorithm in C was executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex. No: 9 DEADLOCK DETECTION ALGORITHM

AIM
To write a C program to implement DeadLock Detection using Banker’s Algorithm.

ALGORITHM
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety or not if we allow the request.

PROGRAM
#include<stdio.h>
struct da
{
int max[10],a1[10],need[10],before[10],after[10];
}p[10];
void main()
{
int i,j,k,l,r,n,tot[10],av[10],cn=0,cz=0,temp=0,c=0;
printf("\n ENTER THE NO. OF PROCESSES:");
scanf("%d",&n);
printf("\n ENTER THE NO. OF RESOURCES:");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("PROCESS %d \n",i+1);
for(j=0;j<r;j++)
{
printf("MAXIMUM VALUE FOR RESOURCE %d:",j+1);
scanf("%d",&p[i].max[j]);
}
for(j=0;j<r;j++)
{
printf("ALLOCATED FROM RESOURCE %d:",j+1);
scanf("%d",&p[i].a1[j]);
p[i].need[j]=p[i].max[j]-p[i].a1[j];
}
}
for(i=0;i<r;i++)
{
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
printf("ENTER TOTAL VALUE OF RESOURCE %d:",i+1);
scanf("%d",&tot[i]);
}
for(i=0;i<r;i++)
{
for(j=0;j<n;j++)
temp=temp+p[j].a1[i];
av[i]=tot[i]-temp;
temp=0;
}
printf("\n\t RESOURCES ALLOCATED NEEDED TOTAL AVAIL");
for(i=0;i<n;i++)
{
printf("\n P%d \t",i+1);
for(j=0;j<r;j++)
printf("%d",p[i].max[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].a1[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].need[j]);
printf("\t");
for(j=0;j<r;j++)
{
if(i==0)
printf("%d",tot[j]);
}
printf(" ");
for(j=0;j<r;j++)
{
if(i==0)
printf("%d",av[j]);
}
}
printf("\n\n\t AVAIL BEFORE\T AVAIL AFTER ");
for(l=0;l<n;l++)
{
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
if(p[i].need[j] >av[j])
cn++;
if(p[i].max[j]==0)
cz++;
}
if(cn==0 && cz!=r)
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
{
for(j=0;j<r;j++)
{
p[i].before[j]=av[j]-p[i].need[j];
p[i].after[j]=p[i].before[j]+p[i].max[j];
av[j]=p[i].after[j];
p[i].max[j]=0;
}
printf("\n P %d \t",i+1);
for(j=0;j<r;j++)
printf("%d",p[i].before[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].after[j]);
cn=0;
cz=0;
c++;
break;
}
else
{
cn=0;cz=0;
}
}
}
if(c==n)
printf("\n THE ABOVE SEQUENCE IS A SAFE SEQUENCE");
else
printf("\n DEADLOCK OCCURED");
}

OUTPUT
[user@sys108 ~]$ vi deadlock1.c
[user@sys108 ~]$ cc deadlock1.c
[user@sys108 ~]$ ./a.out
ENTER THE NO. OF PROCESSES:4
ENTER THE NO. OF RESOURCES:3
PROCESS 1
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:1
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:0
PROCESS 2
MAXIMUM VALUE FOR RESOURCE 1:6
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:3
ALLOCATED FROM RESOURCE 1:5
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
PROCESS 3
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:4
ALLOCATED FROM RESOURCE 1:2
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 4
MAXIMUM VALUE FOR RESOURCE 1:4
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:0
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:2

ENTER TOTAL VALUE OF RESOURCE 1:9


ENTER TOTAL VALUE OF RESOURCE 2:3
ENTER TOTAL VALUE OF RESOURCE 3:6

RESOURCES ALLOCATED NEEDED TOTAL AVAIL


P1 322 100 222 936 112
P2 613 511 102
P3 314 211 103
P4 422 002 420

AVAIL BEFORE AVAIL AFTER


P2 010 623
P1 401 723
P3 620 934
P4 514 936
THE ABOVE SEQUENCE IS A SAFE SEQUENCE

RESULT
Thus the C program for Dead Lock Detection was executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex. No : 10 (a) FIRST FIT MEMORY ALLOCATION

AIM
To write a C program to implement First fit Memory allocation technique

ALGORITHM
1. Enter the number of blocks and number of files.
2. Enter the size of the blocks.
3. Enter the size of the files.
4. First fit chooses the first available block that is large enough.
5. Display File number, File size, Occupied block number and size.

PROGRAM
#include<stdio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
printf("\n\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
}

OUTPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:- Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:- File 1: 1
File 2: 4

File No File Size Block No Block Size Fragment


1 1 1 5 4
2 4 3 7 3

RESULT
Thus First fit Memory allocation technique was executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex. No : 10(b) WORST FIT MEMORY ALLOCATION

AIM
To write a C program to implement Worst fit Memory allocation technique

ALGORITHM
1. Enter the number of blocks and number of files.
2. Enter the size of the blocks.
3. Enter the size of the files.
4. Worst fit occupies the largest available block.
5. Display File number, File size, occupied block number and size.

PROGRAM
#include<stdio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];
printf("\n\tMemory Management Scheme - Worst Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i]; if(temp>=0)
if(highest<temp)
{
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

ff[i]=j; highest=temp;
}
}
}
frag[i]=highest;
bf[ff[i]]=1;
highest=0;
}
printf("\nFile_no:\tFile_size:\tBlock_no:\tBlock_size:\tFragement"); for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
}
OUTPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:- Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:- File 1: 1
File 2: 4
File No File Size Block No Block Size Fragment
1 1 3 7 6
2 4 1 5 1

RESULT
Thus Worst fit Memory allocation technique was executed and verified successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex. No : 10(c) BEST FIT MEMORY ALLOCATION

AIM
To write a C program to implement Best fit Memory allocation technique

ALGORITHM
1. Enter the number of blocks and number of files.
2. Enter the size of the blocks.
3. Enter the size of the files.
4. Best fit chooses the block that is closest in size to the request.
5. Display File number, File size, occupied block number and size.

PROGRAM
#include<stdio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
if(lowest>temp)
{
ff[i]=j;
lowest=temp;
}
}
}
frag[i]=lowest;
bf[ff[i]]=1;
lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock Size\tFragment");
for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
}

OUTPUT
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:- Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:- File 1: 1
File 2: 4

File No File Size Block No Block Size Fragment


1 1 2 2 1
2 4 1 5 1

RESULT
Thus Best fit Memory allocation technique was executed and verified successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

Ex.No: 11 PAGING TECHNIQUE OF MEMORY MANAGEMENT

AIM
To implement the Memory management policy- Paging using C.

ALGORITHM
Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks.
Step 3: Frames – Physical memory is broken into fixed – sized blocks.
Step 4: Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
Step 5: Display the physical address.

PROGRAM
#include <stdio.h>
struct pstruct
{
int fno;
int pbit;
}ptable[10];

int pmsize,lmsize,psize,frame,page,ftable[20],frameno;

void info()
{
printf("\n\nMEMORY MANAGEMENT USING PAGING\n\n");
printf("\n\nEnter the Size of Physical memory: ");
scanf("%d",&pmsize);
printf("\n\nEnter the size of Logical memory: ");
scanf("%d",&lmsize);
printf("\n\nEnter the partition size: ");
scanf("%d",&psize);
frame = (int) pmsize/psize;
page = (int) lmsize/psize;
printf("\nThe physical memory is divided into %d no.of frames\n",frame);
printf("\nThe Logical memory is divided into %d no.of pages",page);
}

void assign()
{
int i;
for (i=0;i<page;i++)
{
ptable[i].fno = -1;
ptable[i].pbit= -1;
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
}
for(i=0; i<frame;i++)
ftable[i] = 32555;
for (i=0;i<page;i++)
{
printf("\n\nEnter the Frame number where page %d must be placed: ",i);
scanf("%d",&frameno);
ftable[frameno] = i;
if(ptable[i].pbit == -1)
{
ptable[i].fno = frameno;
ptable[i].pbit = 1;
}
}
printf("\n\nPAGE TABLE\n\n");
printf("PageAddress FrameNo. PresenceBit\n\n");
for (i=0;i<page;i++)
printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit);
printf("\n\n\n\tFRAME TABLE\n\n");
printf("FrameAddress PageNo\n\n");
for(i=0;i<frame;i++)
printf("%d\t\t%d\n",i,ftable[i]);
}
void cphyaddr()
{
int laddr,paddr,disp,phyaddr,baddr;
getch();
printf("\n\n\n\tProcess to create the Physical Address\n\n");
printf("\nEnter the Base Address: ");
scanf("%d",&baddr);
printf("\nEnter theLogical Address: ");
scanf("%d",&laddr);
paddr = laddr / psize;
disp = laddr % psize;
if(ptable[paddr].pbit == 1 )
phyaddr = baddr + (ptable[paddr].fno*psize) + disp;
printf("\nThe Physical Address where the instruction present: %d",phyaddr);
}
void main()
{
info();
assign();
cphyaddr();
}
CS23422 OPERATING SYSTEMS LABORATORY MANUAL

OUTPUT
[user@sys108 ~]$ vi memoryman.c
[user@sys108 ~]$ cc memoryman.c
[user@sys108 ~]$ ./a.out

MEMORY MANAGEMENT USING PAGING


Enter the Size of Physical memory: 8
Enter the size of Logical memory: 6
Enter the partition size: 2
The physical memory is divided into 4 no.of frames
The Logical memory is divided into 2 no.of pages
Enter the Frame number where page 0 must be placed: 30
Enter the Frame number where page 1 must be placed: 40

PAGE TABLE
PageAddress FrameNo. PresenceBit
0 30 1
1 40 1

FRAME TABLE
FrameAddress PageNo
0 32555
1 32555
2 32555
3 0

Process to create the Physical Address


Enter the Base Address: 1000
Enter theLogical Address: 6
The Physical Address where the instruction present: 1012

RESULT
Thus the Memory management policy- Paging was executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex. No: 12(a) FIFO PAGE REPLACEMENT ALGORITHM

AIM
To write a C program to implement FIFO page replacement algorithm

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

PROGRAM
#include<stdio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
void main()
{
printf("\n \t\t\t FIFO PAGE REPLACEMENT ALGORITHM");
printf("\n Enter no.of frames....");
scanf("%d",&nof);
printf("Enter number of reference string..\n");
scanf("%d",&nor);
printf("\n Enter the reference string..");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\nThe given reference string:");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=1;i<=nof;i++)
frm[i]=-1;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference np%d->\t",ref[i]);
for(j=0;j<nof;j++)
{
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
if(frm[j]==ref[i])
{
flag=1;
break; }}
if(flag==0)
{
pf++;
victim++;
victim=victim%nof;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
} }
printf("\n\n\t\t No.of pages faults...%d",pf);
}

OUTPUT
[user@sys108 ~]$ vi fifo.c
[user@sys108 ~]$ cc fifo.c
[user@sys108 ~]$ ./a.out
FIFO PAGE REPLACEMENT ALGORITHM
Enter no.of frames....4
Enter number of reference string.. 6
Enter the reference string..
564123
The given reference string:
...................................... 5 6 4 1 2 3
Reference np5-> 5 -1 -1 -1
Reference np6-> 5 6 -1 -1
Reference np4-> 5 6 4 -1
Reference np1-> 5 6 4 1
Reference np2-> 2 6 4 1
Reference np3-> 2 3 4 1
No.of pages faults...6

RESULT
Thus the program for Page Replacement Algorithm using FIFO is written and executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex. No: 12(b) LRU PAGE REPLACEMENT ALGORITHM

AIM
To implement Least Recently Used Page Replacement algorithm in C.

ALGORITHM
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the queue
Step 3: Now the new page is inserted at the tail of the queue
Step 4: Create a stack
Step 5: When the page fault occurs replace page present at the bottom of the stack

PROGRAM
#include<stdio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],lrucal[50],count=0;
int lruvictim();
void main()
{
printf("\n\t\t\t LRU PAGE REPLACEMENT ALGORITHM");
printf("\n Enter no.of Frames....");
scanf("%d",&nof);
printf(" Enter no.of reference string..");
scanf("%d",&nor);
printf("\n Enter reference string..");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\n\n\t\t LRU PAGE REPLACEMENT ALGORITHM ");
printf("\n\t The given reference string:");
printf("\n………………………………..");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=1;i<=nof;i++)
{
frm[i]=-1;
lrucal[i]=0;
}

for(i=0;i<10;i++)
recent[i]=0;
printf("\n");
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference NO %d->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}
}
if(flag==0)
{
count++;
if(count<=nof)
victim++;
else
victim=lruvictim();
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
recent[ref[i]]=i;
}
printf("\n\n\t No.of page faults...%d",pf);
getch();
}
int lruvictim()
{
int i,j,temp1,temp2;
for(i=0;i<nof;i++)
{
temp1=frm[i];
lrucal[i]=recent[temp1];
}
temp2=lrucal[0];
for(j=1;j<nof;j++)
{
if(temp2>lrucal[j])
temp2=lrucal[j];
}
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
for(i=0;i<nof;i++)
if(ref[temp2]==frm[i])
return i;
return 0;
}

OUTPUT
[user@sys108 ~]$ vi least.c
[user@sys108 ~]$ cc least.c
[user@sys108 ~]$ ./a.out
LRU PAGE REPLACEMENT ALGORITHM
Enter no.of Frames....3
Enter no.of reference string..6
Enter reference string..
654231
LRU PAGE REPLACEMENT ALGORITHM
The given reference string:
…………………. 6 5 4 2 3 1
Reference NO 6-> 6 -1 -1
Reference NO 5-> 6 5 -1
Reference NO 4-> 6 5 4
Reference NO 2-> 2 5 4
Reference NO 3-> 2 3 4
Reference NO 1-> 2 3 1
No.of page faults...6

RESULT
Thus the program for LRU Page Replacement Algorithm is written and executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex No: 12 (c) LFU PAGE REPLACEMENT ALGORITHM

AIM
To implement LFU page replacement technique.

ALGORITHM
1. Read Number Of Pages And Frames
2. Read Each Page Value
3. Search For Page In The Frames
4. If Not Available Allocate Free Frame
5. If No Frames Is Free Repalce The Page With The Page That Is Least frequently used.
6. Print Page Number Of Page Faults

PROGRAM
#include<stdio.h>
void main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf(“Enter no of pages:”);
scanf(“%d”,&n);
printf(“Enter the reference string:”);
for(i=0;i<n;i++)
scanf(“%d”,&p[i]);
printf(“Enter no of frames:”);
scanf(“%d”,&f);
q[k]=p[k];
printf(“\n\t%d\n”,q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf(“\t%d”,q[j]);
printf(“\n”);
}
else
{
for(r=0;r<f;r++)
{
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
c2[r]=0;
for(j=i-1;j<n;j–)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf(“\t%d”,q[r]);
}
printf(“\n”);
}
}
}
printf(“\nThe no of page faults is %d”,c);
}

OUTPUT
Enter no of pages:10
Enter the reference string:7 5 9 4 3 7 9 6 2 1
Enter no of frames:3
7
75
759
459
439
437
937
967
962
162

RESULT
Thus the program for LFU was executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex No: 13 (a) SINGLE LEVEL DIRECTORY

AIM
To write a c program to simulate Single level directory structure.

ALGORITHM

Start the program.


Get the number of main directories to be created.
Get the name of the directory and size of the directory.
Simulate the directory level and display the structure.
Stop the program.

PROGRAM
#include<stdio.h>
main()
{
int master,s[20];
char f[20][20][20];
char d[20][20];
int i,j;
printf("Enter number of directorios:");
scanf("%d",&master);
printf("Enter names of directories:");
for(i=0;i<master;i++)
scanf("%s",&d[i]);
printf("Enter size of directories:");
for(i=0;i<master;i++)
scanf("%d",&s[i]);
printf("Enter the file names :");
for(i=0;i<master;i++)
for(j=0;j<s[i];j++)
scanf("%s",&f[i][j]);
printf("\n");
printf(" directory\tsize\tfilenames\n");
printf("*************************************************\n");
for(i=0;i<master;i++)
{
printf("%s\t\t%2d\t",d[i],s[i]);
for(j=0;j<s[i];j++)
printf("%s\n\t\t\t",f[i][j]);
printf("\n"); }
printf("\t\n");
}

OUTPUT
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
[user@sys108 ~]$ vi singlelevel.c
[user@sys108 ~]$ cc singlelevel.c
[user@sys108 ~]$ ./a.out
Enter number of directorios:2
Enter names of directories: hai hello
Enter size of directories:2 2
Enter the file names :sample test fibonacci fact
directory size filenames
*************************************************
hai 2 sample
test
hello 2 fibonacci
fact

RESULT
Thus the program to simulate Single level directory structure is executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex.No: 13(b) TWO LEVEL DIRECTORY

AIM
To write a C program to simulate Two Level directory structures.

ALGORITHM

1. Start the program.


2. Get the number of main directories to be created, name of the directory and size of the
directory.
3. Get the number of sub directories to be created, name of the directory and size of the
directory.
4. Simulate the directory level and display the structure.
5. Stop the program.

PROGRAM
#include<stdio.h>
struct st
{
char dname[10];
char sdname[10][10];
char fname[10][10][10];
int ds,sds[10];
}dir[10];
void main()
{
int i,j,k,n;
printf("Enter number of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter directory %d names:",i+1);
scanf("%s",&dir[i].dname);
printf("Enter size of directories:");
scanf("%d",&dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("Enter subdirectory name and size:");
scanf("%s",&dir[i].sdname[j]);
scanf("%d",&dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
{
printf("Enter file name:");
scanf("%s",&dir[i].fname[j][k]);
}
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
}
}
printf("\ndirname\t\tsize\tsubdirname\tsize\tfiles");
printf("\n******************************************************\n");
for(i=0;i<n;i++)
{
printf("%s\t\t%d",dir[i].dname,dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("\t%s\t\t%d\t",dir[i].sdname[j],dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
printf("%s\t",dir[i].fname[j][k]);
printf("\n\t\t");
}
printf("\n"); }
}

OUTPUT
[user@sys108 ~]$ vi twolevel.c
[user@sys108 ~]$ cc twolevel.c
[user@sys108 ~]$ ./a.out
Enter number of directories:2
Enter directory 1 names:colleges
Enter size of directories:1
Enter subdirectory name and size:deemed 1
Enter file name:stjosephs
Enter directory 2 names:companies
Enter size of directories:1
Enter subdirectory name and size:MNC 1
Enter file name:CTS
dirname size subdirname size files
******************************************************
colleges 1 affiliated 1 stjosephs

companies 1 MNC 1 CTS

RESULT
Thus the program to simulate Two level directory structure is executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex.No:13(c) HIERARCHICAL & DAG

AIM
To write a C program to implement Hierarchical and DAG.

ALGORITHM
1. Start the program.
2. Get the number of main directories to be created, name of the directory and size of the directory.
3. Get the number of sub directories to be created, name of the directory and size of the directory.
4. Get the name of the file to be shared between directories.
5. Simulate the directed acyclic graph and display the structure.
6. Stop the program.

PROGRAM

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN_PER_RANK 1
#define MAX_PER_RANK 5
#define MIN_RANKS 3
#define MAX_RANKS 5
#define PERCENT 30
int main (void)
{
int i, j, k,nodes = 0;
srand (time (NULL));
int ranks = MIN_RANKS
+ (rand () % (MAX_RANKS - MIN_RANKS + 1));
printf ("digraph {\n");
for (i = 0; i < ranks; i++)
{
int new_nodes = MIN_PER_RANK
+ (rand () % (MAX_PER_RANK - MIN_PER_RANK + 1));
for (j = 0; j < nodes; j++)
for (k = 0; k < new_nodes; k++)
if ( (rand () % 100) < PERCENT)
printf (" %d -> %d;\n", j, k + nodes);
nodes += new_nodes;
}
printf ("}\n");
return 0;
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
}

OUTPUT

[user@sys108 ~]$ cc dgraph.c


[user@sys108 ~]$ ./a.out

digraph {

0 -> 5;

1 -> 6;

2 -> 5;

2 -> 8;

3 -> 5;

3 -> 8;

4 -> 6;

4 -> 7;

1 -> 9;

3 -> 9;

6 -> 9;

RESULT
Thus the program to simulate Directed Acyclic Graph and hierarchial structure is executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex.No:14(a) SEQUENTIAL FILE ALLOCATION

AIM
To write a c program to simulate Sequential File Allocation strategy.

ALGORITHM

1. Memory before allocation is displayed.


2. The file Id is entered by the user.
3. The number of blocks memory required and the starting address of the file is given by
the user.
4. If starting address and length of block is greater than 20 print error message.
5. Else the memory address is replaced by the id.
6. Display memory after allocation.

PROGRAM
#include<stdio.h>
#include<conio.h>
int a[20],num=0;
int fid[10],length[10],start[10];
void filedescriptor();
void display();
void filedescriptor()
{
int i;
printf("\n file id \t starting address \t length \n");
for(i=0;i<num;i++)
printf("%d\t\t\t %d\t\t%d\n",fid[i],start[i],length[i]);
}
void display()
{
int i;
for(i=0;i<20;i++)
printf("%2d",i);
printf("\n");
for(i=0;i<20;i++)
printf("%2d", a[i]);
}
void main()
{
int i,n,k,temp,st,l,id,flag=0,cho;
for(i=0;i<20;i++)
a[i]=0;
clrscr();
printf("\n Memory before allocation:\n");
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
display();
while(1) {
printf("\n Enter the file id:");
scanf("%d",&id);
printf("\n Enter the number of blocks the file occupies:");
scanf("%d", &l);
fid[num]=id;
length[num]=l;
printf("\n Enter the starting address:");
scanf("%d", &st);
flag=0;
if((st+l)>20)
{
printf("\n Sorry the given memory goes out of space:");
goto l; }
for(i=st;i<(st+l);i++) {
if(a[i]!=0) {
flag=1;
break;
}}
if(flag==0) {
start[num]=st;
for(i=st;i<(st+l);i++)
a[i]=id; }
else
{
printf("\n Sorry the given blocks are already occupied: Enter new starting address");
goto l; }
flag=0;
num++;
filedescriptor();
printf("\n Memory after allocation \n");
display();
printf("\n Want to continue? \n1.yes \n2.no");
scanf("%d",&cho);
if(cho==2)
exit(0);
}}
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
OUTPUT
[user@sys108 ~]$ vi sequential.c
[user@sys108 ~]$ cc sequential.c
[user@sys108 ~]$ ./a.out
Memory before allocation:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Enter the file id: 7
Enter the number of blocks the file occupies :4
Enter the starting address:2
File id starting address length
7 2 4
Memory after allocation:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 0 7 7 7 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Want to continue?
1.yes
2.no
2

RESULT
Thus a C program to simulate Sequential File allocation strategy is executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex.No: 14(b) INDEXED FILE ALLOCATION

AIM
To write a C program to simulate Indexed File Allocation strategy.

ALGORITHM

1. Get the index block number and number of files in the index block as input from user.
2. Get the file numbers (i.e referred block numbers holding file) as input .
3. Check whether that the input block number is already allocated if so print block allocated.
4. Else increase the count and allocate the file.
5. Continue the loop to enter another index block.

PROGRAM
#include<stdio.h>
void main()
{
int f[50],indblk,i,k,j,index[50],n,c,count=0;
for(i=0;i<50;i++)
f[i]=0;
X:printf("Enter index block");
scanf("%d",&indblk);
if(f[indblk]!=1)
{
f[indblk]=1;
printf("Enter number of files on index");
scanf("%d",&n);
}
y: for(i=0;i<n;i++)
{
scanf("%d",&index[i]);
if(f[index[i]]==0)
{
count++;
}
}
if(count==n)
{
for(j=0;j<n;j++)
f[index[j]]=1;
printf("\n Allocated");
printf("\n File indexed");
for(k=0;k<n;k++)
printf("\n%d->%d:%d",indblk,index[k],f[index[k]]);
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
}
else
{
printf("\n File in the index already allocation");
printf("\n Enter another file indexed");
goto y;
}
printf("\n Index is already allocated");
count=0;
printf("\n If you enter one more block(1/0)");
scanf("%d",&c);
if(c==1)
goto X;
}

OUTPUT
[user@sys108 ~]$ vi index.c
[user@sys108 ~]$ cc index.c
[user@sys108 ~]$ ./a.out
Enter index block 2
Enter no of files on index 4
5678
Allocated
File indexed
2->5:1
2->6:1
2->7:1
2->8:1
Index is already allocated
If you enter one more block(1/0)

RESULT
Thus a C program to simulate Indexed File allocation strategy is executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex.No: 14(c) LINKED FILE ALLOCATION

AIM
To write a C program to simulate Linked File Allocation strategy

ALGORITHM

1. Get the number of blocks already allocated and its block numbers as input from user.
2. Add that block numbers to a list as allocated block number list and mark that block
numbers are allocated.
3. To perform allocation , get the starting block number and length of the input file.
4. From the starting block check whether each block is in allocated block number list.
5. If so print block is already allocated. Else allocate file to the block number.
6. Continue the loop if the processes want to be repeated.

PROGRAM
#include<stdio.h>
main()
{
int f[50],p,i,j,k,a,st,len,n,c;
for(i=0;i<50;i++)
f[i]=0;
printf("Enter how many blocks that are already allocated");
scanf("%d",&p);
printf("\nEnter the blocks no.s that are already allocated");
for(i=0;i<p;i++)
{
scanf("%d",&a);
f[a]=1;
}
X:printf("Enter the starting block & length");
scanf("%d%d",&st,&len);
k=len;
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("\n%d->%d",j,f[j]);
}
else
{
printf("\n %d-> file is already allocated",j);
k++;
}
}
printf("\n If u want to enter one more file? (yes-1/no-0)");
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
scanf("%d",&c);
if(c==1)
goto X;
else
exit(0);
}

OUTPUT
[user@sys108 ~]$ vi linked.c
[user@sys108 ~]$ cc linked.c

[user@sys108 ~]$ ./a.out


Enter how many blocks that are already allocated 3
Enter the blocks no.s that are already allocated 4 7 9
Enter the starting block & length 3 7
3->1
4->file is already allocated
5->1
6->1
7->file is already allocated
8->1
9->file is already allocated
10->1
11->1
12->1
If u want to enter one more file? (yes-1/no-0)

RESULT
Thus a C program to simulate Linked File allocation strategy is executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex.No:15 (a) FCFS (First Come First Serve) DISK SCHEDULING ALGORITHM

AIM
To write a C program for FCFS Disk Scheduling Algorithm

ALGORITHM
1. Input:
o The number of disk I/O requests.
o The sequence of disk I/O requests.
o The initial position of the disk head.
2. Initialization:
o Set the total seek count to 0.
o Set the current head position to the initial head position.
3. Process Each Request:
o For each request in the request queue:
 Calculate the distance (seek time) between the current head position and the request.
 Add this distance to the total seek count.
 Update the head position to the current request.
4. Output:
o Print the order in which the requests are serviced.
o Print the total seek count (total head movement).
Step-by-Step:
1. Start.
2. Input the total number of requests n.
3. Input the request queue (disk positions to be accessed).
4. Input the initial head position.
5. Initialize seek_count = 0 and set current_head to the initial head position.
6. For each request in the request queue:
o Calculate distance = abs(current_head - request).
o Add distance to seek_count.
o Update current_head = request.
7. Print the sequence of requests that were serviced.
8. Print the total seek count.
9. End.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
PROGRAM

#include <stdio.h>
#include <stdlib.h>

void FCFS(int requests[], int n, int head) {


int seek_count = 0;
int distance, cur_track;

printf("Seek Sequence: \n");

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


cur_track = requests[i];

// Calculate absolute distance


distance = abs(cur_track - head);

// Increase the total count


seek_count += distance;

// Update the head position


head = cur_track;

printf("%d ", cur_track);


}

printf("\nTotal number of seek operations = %d\n", seek_count);


}

int main() {
int n, head;

printf("Enter the number of requests: ");


scanf("%d", &n);

int requests[n];
printf("Enter the request sequence: ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}

printf("Enter the initial head position: ");


scanf("%d", &head);
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
FCFS(requests, n, head);

return 0;
}
OUTPUT:
Enter the number of requests: 5
Enter the request sequence: 98 183 37 122 14
Enter the initial head position: 53

Sequence of servicing requests:


98 183 37 122 14
Total seek count: 640

RESULT:

Thus a C program for FCFS using Disk Scheduling Algorithm has been executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex No: 15 (b) SSTF (Shortest Seek Time First) DISK SCHEDULING ALGORITHM

AIM:
To write a C program for SSTF using Disk Scheduling Algorithm.
ALGORITHM:
Input:
o The number of disk I/O requests.
o The sequence of disk I/O requests.
o The initial position of the disk head.
2. Initialization:
o Set the total seek count to 0.
o Set the current head position to the initial head position.
o Mark all requests as unvisited.
3. Repeat until all requests are serviced:
o Find the unvisited request that is closest to the current head position.
o Calculate the distance (seek time) between the current head position and the closest request.
o Add this distance to the total seek count.
o Mark the closest request as visited.
o Move the head to the position of the closest request.
4. Output:
o Print the order in which the requests are serviced.
o Print the total seek count (total head movement).
Step-by-Step:
1. Start.
2. Input the total number of requests n.
3. Input the request queue (disk positions to be accessed).
4. Input the initial head position.
5. Initialize seek_count = 0 and set current_head to the initial head position.
6. Mark all requests as unvisited.
7. Repeat until all requests are serviced:
o Find the unvisited request that is closest to current_head (i.e., minimum absolute difference
between current_head and the request).
o Calculate distance = abs(current_head - closest_request).
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
o Add distance to seek_count.
o Mark the closest request as visited.
o Update current_head = closest_request.
8. Print the sequence of requests that were serviced.
9. Print the total seek count.
10. End.

PROGRAM:

#include <stdio.h>
#include <stdlib.h>

int findClosest(int requests[], int n, int head, int visited[]) {


int min_distance = 1e9;
int closest_track = -1;

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


if (!visited[i] && abs(requests[i] - head) < min_distance) {
min_distance = abs(requests[i] - head);
closest_track = i;
}
}

return closest_track;
}

void SSTF(int requests[], int n, int head) {


int seek_count = 0, cur_track;
int visited[n];

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


visited[i] = 0;
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
printf("Seek Sequence: \n");

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


int idx = findClosest(requests, n, head, visited);
visited[idx] = 1;

cur_track = requests[idx];
seek_count += abs(cur_track - head);
head = cur_track;

printf("%d ", cur_track);


}

printf("\nTotal number of seek operations = %d\n", seek_count);


}

int main() {
int n, head;

printf("Enter the number of requests: ");


scanf("%d", &n);

int requests[n];
printf("Enter the request sequence: ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}

printf("Enter the initial head position: ");


scanf("%d", &head);

SSTF(requests, n, head);
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
return 0;
}

OUTPUT:
Enter the number of requests: 5
Enter the request sequence: 98 183 37 122 14
Enter the initial head position: 53

Sequence of servicing requests:


37 14 98 122 183
Total seek count: 236

RESULT;

Thus a C program for SSTF using Disk Scheduling Algorithm has been executed successfully.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Ex No:15 (c) SCAN (Elevator) DISK SCHEDULING ALGORITHM

AIM:
To write a C program for SCAN using Disk Scheduling Algorithm.
ALGORITHM:
1. Input:
o The number of disk I/O requests.
o The sequence of disk I/O requests.
o The initial position of the disk head.
o The direction of the disk head movement (either "left" or "right").
o The total disk size (maximum disk cylinder value).
2. Initialization:
o Set the total seek count to 0.
o Set the current head position to the initial head position.
o Separate the requests into two lists:
 One for requests less than the current head (on the left).
 One for requests greater than the current head (on the right).
3. Sort the two lists:
o Sort the requests on the left in descending order.
o Sort the requests on the right in ascending order.
4. Servicing Requests:
o If the direction is "left":
 Service the requests on the left first (from the current head towards 0), then service the
requests on the right.
o If the direction is "right":
 Service the requests on the right first (from the current head towards the maximum disk
size), then service the requests on the left.
5. For each serviced request:
o Calculate the distance (seek time) between the current head position and the request.
o Add this distance to the total seek count.
o Move the head to the position of the request.
6. Output:
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
o Print the order in which the requests are serviced.
o Print the total seek count (total head movement).
Step-by-Step:
1. Start.
2. Input the total number of requests n.
3. Input the request queue (disk positions to be accessed).
4. Input the initial head position.
5. Input the total disk size (maximum cylinder value).
6. Input the direction of movement ("left" or "right").
7. Initialize seek_count = 0 and set current_head to the initial head position.
8. Separate the requests into two lists:
o Requests less than current_head (left).
o Requests greater than current_head (right).
9. Sort the left list in descending order and the right list in ascending order.
10. If direction is "left":
o Move the head towards 0 by servicing requests in the left list.
o After reaching 0, reverse the direction and service the requests in the right list.
11. If direction is "right":
o Move the head towards the maximum disk size by servicing requests in the right list.
o After reaching the maximum, reverse the direction and service the requests in the left list.
12. For each serviced request:
o Calculate distance = abs(current_head - request).
o Add distance to seek_count.
o Update current_head = request.
13. Print the sequence of serviced requests.
14. Print the total seek count.
15. End.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
PROGRAM:
#include <stdio.h>
#include <stdlib.h>

void SCAN(int requests[], int n, int head, int disk_size, int direction) {
int seek_count = 0;
int distance, cur_track;
int left[n], right[n];
int l = 0, r = 0;

if (direction == 0)
left[l++] = 0;
if (direction == 1)
right[r++] = disk_size - 1;

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


if (requests[i] < head)
left[l++] = requests[i];
if (requests[i] > head)
right[r++] = requests[i];
}

// Sort left and right lists


qsort(left, l, sizeof(int), (int (*)(const void*, const void*))abs);
qsort(right, r, sizeof(int), (int (*)(const void*, const void*))abs);

printf("Seek Sequence: \n");

if (direction == 1) {
for (int i = 0; i < r; i++) {
cur_track = right[i];
distance = abs(cur_track - head);
seek_count += distance;
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
head = cur_track;
printf("%d ", cur_track);
}
for (int i = l - 1; i >= 0; i--) {
cur_track = left[i];
distance = abs(cur_track - head);
seek_count += distance;
head = cur_track;
printf("%d ", cur_track);
}
} else {
for (int i = l - 1; i >= 0; i--) {
cur_track = left[i];
distance = abs(cur_track - head);
seek_count += distance;
head = cur_track;
printf("%d ", cur_track);
}
for (int i = 0; i < r; i++) {
cur_track = right[i];
distance = abs(cur_track - head);
seek_count += distance;
head = cur_track;
printf("%d ", cur_track);
}
}

printf("\nTotal number of seek operations = %d\n", seek_count);


}

int main() {
int n, head, disk_size, direction;
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
printf("Enter the number of requests: ");
scanf("%d", &n);

int requests[n];
printf("Enter the request sequence: ");
for (int i = 0; i < n; i++) {
scanf("%d", &requests[i]);
}

printf("Enter the initial head position: ");


scanf("%d", &head);

printf("Enter the total disk size: ");


scanf("%d", &disk_size);

printf("Enter the direction (0 for left, 1 for right): ");


scanf("%d", &direction);

SCAN(requests, n, head, disk_size, direction);

return 0;
}

OUTPUT:
Enter the number of requests: 5
Enter the request sequence: 98 183 37 122 14
Enter the initial head position: 53
Enter the disk size: 200
Enter the direction (left or right): left
Sequence of servicing requests:
37 14 0 98 122 183
Total seek count: 389
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
RESULT:

The C program for SCAN using Disk Scheduling Algorithm has been executed successfully.

To install VMware Workstation on a Linux host and add a guest operating system (OS), follow the step-
by-step instructions below:

Part 1: Installing VMware Workstation on a Linux Host

Step 1: Download VMware Workstation

1. Open a web browser and go to the official VMware Workstation Pro download page.

2. Select Linux as the operating system and download the appropriate version (typically a .bundle file).

Step 2: Make the .bundle File Executable

After downloading the .bundle file (e.g., VMware-Workstation-Full-xx.x.x-xxxxxxx.x86_64.bundle), you


need to make it executable.

1. Open the terminal and navigate to the folder where the .bundle file is saved:

cd ~/Downloads

2. Make the file executable:

chmod +x VMware-Workstation-Full-xx.x.x-xxxxxxx.x86_64.bundle

Step 3: Install VMware Workstation

Now, install VMware Workstation using the following command:

sudo ./VMware-Workstation-Full-xx.x.x-xxxxxxx.x86_64.bundle

you may be prompted to accept the license agreement and provide administrative (sudo) privileges.

Step 4: Run VMware Workstation

Once the installation is complete, you can launch VMware Workstation from the terminal or from your
system’s application menu.

Vmware

Part 2: Adding a Guest OS to VMware Workstation

Step 1: Open VMware Workstation

Launch VMware Workstation by typing vmware in the terminal or opening it from the system’s application
menu.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
Step 2: Create a New Virtual Machine

1. In VMware Workstation, click File > New Virtual Machine.

2. The "New Virtual Machine Wizard" will open. Choose either:

o Typical (recommended for most users)

o Custom (advanced users can modify specific settings)

3. Click Next.

Step 3: Select Installation Method

You will be asked how you want to install the guest OS:

 Installer disc image file (ISO): Select this if you have an ISO file for the guest OS.

 Installer disc: Select this if you have a physical CD/DVD with the OS installer.

 I will install the operating system later: Select this if you want to configure the OS later.

Choose the option that suits your setup (usually, the ISO image file) and click Next.

Step 4: Select Guest OS

Select the type of guest operating system you're installing. Options include:

 Linux: If you're installing a Linux distro, select the corresponding version.

 Windows: Select the version of Windows you're installing.

Click Next.

Step 5: Name and Location

Give your virtual machine a name (e.g., "Ubuntu VM") and choose where you want to store it on your disk.
Click Next.

Step 6: Set Disk Size

Specify the size of the virtual disk for the guest OS. VMware recommends at least 20 GB. You can choose:

 Store virtual disk as a single file

 Split virtual disk into multiple files (useful if the host file system has a size limit for single files).

Click Next.

Step 7: Customize Hardware (Optional)

You can customize the hardware settings, such as:


CS23422 OPERATING SYSTEMS LABORATORY MANUAL
 Memory (RAM)

 Processors (CPU cores)

 Network Adapter (bridged, NAT, or host-only)

 Disk size and type

Click Finish after configuring.

Step 8: Install the Guest OS

1. If you selected an ISO image in the previous steps, VMware will boot from the ISO when you power
on the virtual machine.

2. Power on the virtual machine by clicking Power on this virtual machine.

3. Follow the installation instructions for the guest OS (e.g., Linux, Windows) as you would on a physical
machine.

Part 3: Installing VMware Tools (Optional but Recommended)

VMware Tools enhances the performance of the guest OS and enables features like:

 Seamless mouse movement

 Clipboard sharing

 Improved video performance

 Drag-and-drop support between host and guest

Step 1: Install VMware Tools on Linux Guest OS

1. After installing the guest OS, power on the virtual machine.

2. In the VMware menu, click VM > Install VMware Tools. This mounts the VMware Tools ISO to the
guest OS.

3. Open a terminal in the guest OS and mount the VMware Tools CD-ROM:

sudo mkdir /mnt/cdrom

sudo mount /dev/cdrom /mnt/cdrom

4. Extract and install VMware Tools:

tar -xvf /mnt/cdrom/VMwareTools-*.tar.gz -C /tmp

cd /tmp/vmware-tools-distrib

sudo ./vmware-install.pl
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
5. Follow the prompts to complete the installation

Step 2: Install VMware Tools on Windows Guest OS

For Windows, the VMware Tools installation is more straightforward. Once you select Install VMware
Tools from the VMware menu, the installer will automatically run in the Windows guest OS. Follow the on-
screen instructions to complete the setup.

Part 4: Managing the Virtual Machine

After installing the guest OS, you can manage the virtual machine using the VMware Workstation interface:

 Start, stop, or suspend the VM.

 Take snapshots of the VM state.

 Resize the disk or allocate more resources (e.g., memory or CPU) as needed.
CS23422 OPERATING SYSTEMS LABORATORY MANUAL
85

You might also like