You are on page 1of 137

CS8461-OPERATING SYSTEM LABORATORY

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

1
Ex.No : 1(a) UNIX COMMANDS
Date:
AIM :
To study and execute the commands in UNIX.
COMMAND :
1.Date Command :
This command is used to display the current data and time.
Syntax :
$date
$date +%ch
Options : -
a = Abbreviated weekday.
A = Full weekday.
b = Abbreviated month.
B = Full month.
c = Current day and time.
C = Display the century as a decimal number.
d = Day of the month.
D = Day in “mm/dd/yy” format
h = Abbreviated month day.
H = Display the hour.
L = Day of the year.
m = Month of the year.

2
M = Minute.
P = Display AM or PM
S = Seconds
T = HH:MM:SS format
u = Week of the year.
y = Display the year in 2 digit.
Y = Display the full year.
Z = Time zone .
To change the format :
Syntax :
$date “+%H-%M-%S‟
2.Calender Command :
This command is used to display the calendar of the year or the
particular month of calendar year.
Syntax :
a.$cal <year>
b.$cal <month> <year>
Here the first syntax gives the entire calendar for given year & the second
Syntax gives the calendar of reserved month of that year.
3.Echo Command :
This command is used to print the arguments on the screen .
Syntax :
$echo <text>
Multiline echo command :
To have the output in the same line , the following commands can be used.
3
Syntax :
$echo <text\>text
To have the output in different line, the following command can be used.
Syntax :
$echo “text
>line2
>line3”
4.Banner Command :
It is used to display the arguments in “#‟ symbol .
Syntax :
$banner <arguments>
5.’who’ Command :
It is used to display who are the users connected to our computer
currently.
Syntax :
$who – option’s
Options : -
H–Display the output with headers.
b–Display the last booting date or time or when the system was lastly
rebooted.
6.’who am i’ Command :
Display the details of the current working directory.
Syntax :

4
$who am i
7.’tty’ Command :
It will display the terminal name.
Syntax :
$tty
8.’Binary’ Calculator Command :
It will change the “$‟ mode and in the new mode, arithmetic operations
such as +,-,*,/,%,n,sqrt(),length(),=, etc can be performed . This command is used
to go to the binary calculus mode.
Syntax :
$bc operations
^d
$
1 base –inputbase
0 base – outputbase are used for base conversions.
Base :
Decimal = 1 Binary = 2 Octal =8 Hexa = 16
9.’CLEAR’ Command :
It is used to clear the screen.
Syntax : $clear
10.’MAN’ Command :
It help us to know about the particular command and its options &
working. It is like “help‟ command in windows .
Syntax :
$man <command name>

5
11.MANIPULATION Command :
It is used to manipulate the screen.
Syntax :
$tput <argument>
Arguments :
1. Clear – to clear the screen.
2. Longname – Display the complete name of the terminal.
3. SMSO – background become white and foreground become black
color.
4. rmso – background become black and foreground becomes white
color.
5. Cop R C – Move to the cursor position to the specified location.
6. Cols – Display the number of columns in our terminals.
12.LIST Command :
It is used to list all the contents in the current working directory.
Syntax :
$ ls – options <arguments>
If the command does not contain any argument means it is working in
the Current directory.
Options :
a– used to list all the files including the hidden files.
c– list all the files columnwise.
d- list all the directories.

6
m- list the files separated by commas.
p- list files include “/” to all the directories.
r- list the files in reverse alphabetical order.
f- list the files based on the list modification date.
x-list in column wise sorted order.

DIRECTORY RELATED COMMANDS :


1.Present Working Directory Command :
To print the complete path of the current working directory.
Syntax :
$pwd
2.MKDIR Command :
To create or make a new directory in a current directory .
Syntax :
$mkdir <directory name>
3.CD Command :
To change or move the directory to the mentioned directory .
Syntax :
$cd <directory name.
4.RMDIR Command :
To remove a directory in the current directory & not the current
directory itself.
Syntax :
$rmdir <directory name>

7
FILE RELATED COMMANDS :
1. CREATE A FILE :
To create a new file in the current directory we use CAT command.
Syntax :
$cat > <filename.
The > symbol is redirectory we use cat command.
2. DISPLAY A FLE :
To display the content of file mentioned we use CAT command without
“>‟ operator.
Syntax :
$cat <filename.
Options –s = to neglect the warning /error message.
3. COPYING CONTENTS:
To copy the content of one file with another. If file doesnot exist, a new
file is created and if the file exists with some data then it is overwritten.
Syntax :
$ cat <filename source> >> <destination filename>
$ cat <source filename> >> <destination filename> it is avoid
overwriting.
Options
-n content of file with numbers included with blank lines.
Syntax :
$cat –n <filename>
4. SORTING A FILE :

8
To sort the contents in alphabetical order in reverse order.
Syntax :
$sort <filename >
Option :
$ sort –r <filename>
5. COPYING CONTENT FROM ONE FILE TO ANOTHER:
To copy the contents from source to destination file , so that both
contents are same.
Syntax :
$cp <source filename> <destination filename>
$cp <source filename path > <destination filename path>
6. MOVE Command :
To completely move the contents from source file to destination file and
to remove the source file.
Syntax :
$ mv <source filename> <destination filename>
7. REMOVE Command :
To permanently remove the file we use this command .
Syntax :
$rm <filename>
8. WORD Command :
To list the content count of no of lines , words, characters .
Syntax :
$wc<filename>
Options :
9
-c – to display no of characters.
-l – to display only the lines.
-w – to display the no of words.
9. Line printer :
To print the line through the printer, we use lp command.
Syntax :
$lp <filename>
10. PAGE Command :
This command is used to display the contents of the file page wise & next
page can be viewed by pressing the enter key.
Syntax :
$pg <filename>
11. FILTERS AND PIPES HEAD :
It is used to display the top ten lines of file.
Syntax:
$head<filename>
TAIL :
This command is used to display the last ten lines of file.
Syntax:
$tail<filename>
PAGE :
This command shows the page by page a screenfull of information is
displayed after which the page command displays a prompt and passes for the
user to strike the enter key to continue scrolling.
Syntax:

10
$ls –a\p
MORE :
It also displays the file page by page .To continue scrolling with more
command , press the space bar key.
Syntax:
$more<filename>
GREP :
This command is used to search and print the specified patterns from
the file.
Syntax:
$grep [option] pattern <filename>
SORT :
This command is used to sort the datas in some order.
Syntax:
$sort<filename>
PIPE :
It is a mechanism by which the output of one command can be channeled
into the input of another command.
Syntax:
$who | wc-l
TR :
The tr filter is used to translate one set of characters from the standard
inputs to another.
Syntax:
$tr “[a-z]” “[A-Z]”

11
COMMUNICATION THROUGH UNIX COMMANDS
1.Command: MESG
Description: The message command is used to give permission to other
users to send message to your terminal.
Syntax:
$mesg y
2.Command: WRITE
Description: This command is used to communicate with other users,
who are logged in at the same time.
Syntax:
$write <user name>
3.Command: WALL
Description: This command sends message to all users those who are
logged in using the unix server.
Syntax:
$wall <message>
4.Command: MAIL
Description: It refers to textual information, that can be transferred from
one user to another
Syntax:
$mail <user name>
5.Command: REPLY
Description: It is used to send reply to specified user.
Syntax:

12
$reply<user name>

RESULT:
Thus, the basic UNIX commands has been executed successfully and output
was verified.

13
EX.NO :1(b) vi EDITOR COMMANDS
DATE :
AIM :
To study the various commands operated in vi editor in UNIX.
DESCRIPTION :
The Vi editor is a visual editor used to create and edit text, files, documents
and programs. It displays the content of files on the screen and allows a user to
add, delete or change part of text . There are three modes available in the Vi
editor , they are
1.Command mode
2.Input (or) insert mode.
Starting Vi :
The Vi editor is invoked by giving the following commands in UNIX prompt.
Syntax :
$vi <filename> (or)
$vi
This command would open a display screen with 25 lines and with tilt (~)
symbol at the start of each line. The first syntax would save the file in the
filename mentioned and for the next the filename must be mentioned at the end.
Options :
1.vi +n <filename> - this would point at the nth line (cursor pos).
2.vi –n <filename> - This command is to make the file to read only to
change from one mode to another press escape key.

INSERTING AND REPLACING COMMANDS :

14
To move editor from command node to edit mode, you have to press the <ESC>
key. For inserting and replacing the following commands are used.
1.<ESC> a Command :
This command is used to move the edit mode and start to append after
the current character.
Syntax :
<ESC> a
2.<ESC> A COMMAND :
This command is also used to append the file , but this command append
at the end of current line.
Syntax :
<ESC> A
3.<ESC> i Command :
This command is used to insert the text before the current cursor
position.
Syntax :
<ESC> i
4.<ESC> I Command :
This command is used to insert at the beginning of the current line.
Syntax :
<ESC> I
5.<ESC> o Command :
This command is insert a blank line below the current line & allow
insertion of contents.
Syntax : <ESC> o

15
6.<ESC> O Command :
This command is used to insert a blank line above & allow insertion of
contents.
Syntax :
<ESC> O
7.<ESC> r Command :
This command is to replace the particular character with the given
characters.
Syntax :
<ESC> rx Where x is the new character.

8.<ESC> R Command :
This command is used to replace the particular text with a given text.
Syntax :
<ESC> R text

9.<ESC> s Command :
This command replaces a single character with a group of character .
Syntax :
<ESC> s
10.<ESC> S Command :
This command is used to replace a current line with group of characters.
Syntax :
<ESC> S

16
CURSOR MOVEMENT IN vi :
1.<ESC> h Command:
This command is used to move to the previous character typed. It is used
to move to left of the text . It can also used to move character by character (or) a
number of characters.
Syntax :
<ESC> h – to move one character to left.
<ESC> nh – tomove “n‟ character to left.
2.<ESC> l Command:
This command is used to move to the right of the cursor (ie) to the next
character. It can also be used to move the cursor for a number of character.
Syntax :
<ESC> l – single character to right.
<ESC> nl – “n‟ characters to right.
3.<ESC> j Command:
This command is used to move down a single line or a number of lines.
Syntax :
<ESC> j – single down movement.
<ESC> nj – “n‟ times down movement.
4.<ESC> k Command:
This command is used to move up a single line or a number of lines.
Syntax :
<ESC> k – single line above.
<ESC> nk – “n‟ lines above.

17
5.ENTER (OR) N ENTER :
This command will move the cursor to the starting of next lines or a
group of lines mentioned.
Syntax :
<ESC> enter.
<ESC> n enter.
6.<ESC> + Command :
This command is used to move to the beginning of the next line.
Syntax :
<ESC> +
<ESC> n+
7.<ESC> - Command :
This command is used to move to the beginning of the previous line.
Syntax :
<ESC> -
<ESC> n-
8.<ESC> 0 Command:
This command will bring the cursor to the beginning of the same current
line.
Syntax :
<ESC> 0
9.<ESC> $ Command:
This command will bring the cursor to the end of the current line.
Syntax :
<ESC> $
18
10.<ESC> ^ Command:
This command is used to move to first character of first lines.
Syntax :
<ESC> ^
11.<ESC> b Command :
This command is used to move back to the previous word (or) a number
of words.
Syntax :
<ESC> b
<ESC>nb
12.<ESC> e Command :
This command is used to move towards and replace the cursor at last
character of the word (or) no of words.
Syntax :
<ESC> e
<ESC>ne
13.<ESC> w Command :
This command is used to move forward by a single word or a group of
words.
Syntax :
<ESC> w
<ESC> nw

19
DELETING THE TEXT FROM Vi :
1.<ESC> x Command :
To delete a character to right of current cursor positions , this command is
used.
Syntax :
<ESC> x
<ESC> nx
2.<ESC> X Command :
To delete a character to left of current cursor positions , this command is
used.
Syntax :
<ESC> X
<ESC> nX
3.<ESC> dw Command :
This command is to delete a single word or number of words to right of
current cursor position.
Syntax :
<ESC> dw
<ESC> ndw
4.<ESC> db Command :
This command is to delete a single word to the left of the current cursor
position.
Syntax :
<ESC> db
<ESC> ndb

20
5.<ESC> dd Command :
This command is used to delete the current line (or) a number of line
below the current line.
Syntax :
<ESC> dd
<ESC> ndd

6.<ESC> d$ Command :
This command is used to delete the text from current cursor position to
last character of current line.
Syntax :
<ESC> d$
SAVING AND QUITING FROM vi :-
1.<ESC> w Command :
To save the given text present in the file.
Syntax :
<ESC> : w
2.<ESC> q! Command :
To quit the given text without saving.
Syntax :
<ESC> :q!
3.<ESC> wq Command :
This command quits the vi editor after saving the text in the mentioned
file.
Syntax :

21
<ESC> :wq
4.<ESC> x Command :
This command is same as „wq‟ command it saves and quit.
Syntax :
<ESC> :x
5.<ESC> q Command :
This command would quit the window but it would ask for again to save
the file.
Syntax :
<ESC> : q

RESULT:
Thus , the various commands in Vi editor has been executed successfully
and output was verified.
22
EX .NO:2(a) PROGRAM USING SYSTEM CALL fork()
DATE:
AIM :
To write the program to create a Child Process using system call fork().
ALGORITHM :
Step 1 : Declare the variable pid.
Step 2 : Get the pid value using system call fork().
Step 3 : If pid value is less than zero then print as “Fork failed”.
Step 4 : Else if pid value is equal to zero include the new process in the system‟s
file using execlp system call.
Step 5 : Else if pid is greater than zero then it is the parent process and it waits till
the child completes using the system call wait()
Step 6 : Then print “Child complete”.
SYSTEM CALLS USED:
1. fork( )
Used to create new processes. The new process consistsof a copy of the
address space of the original process. The value of process id for the child process
is zero, whereas the value of process id for the parent is an integer value greater
than zero.
Syntax : fork( )
2.execlp( )
Used after the fork() system call by one of the two processes to replace the
process‟ memory space with a new program. It loads a binary file into memory
destroying the memory image of the program containing the execlp system call
and starts its execution.The child process overlays its address space with the UNIX
command /bin/ls using the execlp system call.

23
Syntax : execlp( )
3. wait( )
The parent waits for the child process to complete using the wait system
call. The wait system call returns the process identifier of a terminated child, so
that the parent can tell which of its possibly many children has terminated.
Syntax : wait( NULL)
4. exit( )
A process terminates when it finishes executing its final statement and asks
the operating system to delete it by using the exit system call. At that point, the
process may return data (output) to its parent process (via the wait system call).
Syntax: exit(0)

24
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
void main(int argc,char *arg[])
{
int pid;
pid=fork();
if(pid<0)
{
printf("fork failed");
exit(1);
}
else if(pid==0)
{
execlp("\n whoami\n"," ls",NULL);
exit(0);
}
else
{
printf("\n Process id is -%d\n",getpid());
wait(NULL);
exit(0);
}}

25
OUTPUT:

RESULT:
Thus , the program using system call fork() has been executed successfully
and the output was verified.

26
EX.NO : 2(b) PROGRAM USING SYSTEM CALL exec( )
DATE:
AIM :
To write the program to implement the system call exec( ).
ALGORITHM :
Step 1 : Include the necessary header files.
Step 2 : Print execution of exec system call for the date Unix command.
Step 3 : Execute the execlp function using the appropriate syntax for the Unix
command date.
Step 4 : The system date is displayed.
SYSTEM CALL USED :
1.execlp( )
Used after the fork() system call by one of the two processes to replace the
process memory space with a new program. It loads a binary file into memory
destroying the memory image of the program containing the execlp system call
and starts its execution. The child process overlays its address space with the
UNIX command /bin/ls using the execlp system call.
Syntax : execlp( )
PROGRAM:
#include<stdio.h>
#include<unistd.h>
main( )
{
printf("\n exec system call\n");
printf("\n displaying the date \n");

27
execlp( "/bin/date", "date", NULL);
}

RESULT:
Thus,the program using system call exec() has been executed
successfully and the output was verified.

28
EX.NO:2(c): PROGRAM USING SYSTEM CALLS getpid() & getppid()
DATE:
AIM :
To write the program to implement the system calls getpid() and getppid().
ALGORITHM :
Step 1 : Declare the variables pid , parent pid , child id and grand child id.
Step 2 : Get the child id value using system call fork().
Step 3 : If child id value is less than zero then print as “error at fork() child”.
Step 4 : If child id !=0 then using getpid() system call get the process id.
Step 5 : Print “I am parent” and print the process id.
Step 6 : Get the grand child id value using system call fork().
Step 7 : If the grand child id value is less than zero then print as “error at fork()
grand child”.
Step 8 : If the grand child id !=0 then using getpid system call get the process id.
Step 9 : Assign the value of pid to my pid.
Step 10 : Print “I am child” and print the value of my pid.
Step 11 : Get my parent pid value using system call getppid().
Step 12 : Print “My parent’s process id” and its value.
Step 13 : Else print “I am the grand child”.
Step 14 : Get the grand child’s process id using getpid() and print it as “my
process id”.
Step 15 : Get the grand child’s parent process id using getppid() and print it as
“my parent’s process id “

29
SYSTEM CALLS USED :
1.getpid( )
Each process is identified by its id value. This function is used to get the id
value of a particular process.
2.getppid( )
Used to get particular process parent‟s id value.
3.perror( )
Indicate the process error.

PROGRAM:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int pid;
pid=fork();
if(pid==-1)
{
perror("fork failed");
exit(0);
}
if(pid==0)
{

30
printf("\n Child process is under execution");
printf("\n Process id of the child process is %d", getpid());
printf("\n Process id of the parent process is %d", getppid());
}
else
{
printf("\n Parent process is under execution");
printf("\n Process id of the parent process is %d", getpid());
printf("\n Process id of the child process in parent is %d", pid);
printf("\n Process id of the parent of parent is %d", getppid());
}
return(0);
}

31
OUTPUT:

RESULT:
Thus, the program using system call getpid() and getppid() has been
executed successfully and the output was verified.

32
EX.NO : 2(d) PROGRAM USING SYSTEM CALLS wait( ) & exit( )
DATE:
AIM :
To write the program to implement the system calls wait( ) and exit( ).
ALGORITHM :
Step 1 : Declare the variables pid and i as integers.
Step 2 : Get the child id value using the system call fork().
Step 3 : If child id value is less than zero then print “fork failed”.
Step 4 : Else if child id value is equal to zero , it is the id value of the child and then
start the child process to execute and perform Steps 6 & 7.
Step 5 : Else perform Step 8.
Step 6 : Use a for loop for almost five child processes to be called.
Step 7 : After execution of the for loop then print “child process ends”.
Step 8 : Execute the system call wait( ) to make the parent to wait for the child
process to get over.
Step 9 : Once the child processes are terminated , the parent terminates and
hence print “Parent process ends”.
Step 10 : After both the parent and the child processes get terminated it execute
the wait( ) system call to permanently get deleted from the OS.

SYSTEM CALL USED :


1. fork ( )
Used to create new process. The new process consists of a copy of the
address space of the original process. The value of process id for the child process

33
is zero, whereas the value of process id for the parent is an integer value greater
than zero.
Syntax: fork ( )
2. wait ( )
The parent waits for the child process to complete using the wait system
call. The wait system call returns the process identifier of a terminated child, so
that the parent can tell which of its possibly many children has terminated.
Syntax: wait (NULL)
3. exit ( )
A process terminates when it finishes executing its final statement and asks
the operating system to delete it by using the exit system call. At that point, the
process may return data (output) to its parent process (via the wait system call).
Syntax: exit(0)

PROGRAM:
#include<stdio.h>
#include<unistd.h>
main( )
{
int i, pid;
pid=fork( );
if(pid== -1)
{
perror("fork failed");
}
else if(pid==0)
34
{
printf("\n Child process starts");
for(i=0; i<5; i++)
{
printf("\n Child process %d is called", i);
}
printf("\n Child process ends");
}
else
{
wait(0);
printf("\n Parent process ends");
}
}

35
OUTPUT:

RESULT:
Thus , the program using system call wait() and exit() has been executed
successfully and the output was verified.

36
EX. NO: 2(e) PROGRAM USING SYSTEM CALL stat( )
DATE:
AIM:
To write the program to implement the system call stat( ).
ALGORITHM :
Step 1 : Include the necessary header files to execute the system call stat( ).
Step 2 : Create a stat structure thebuf. Similarly get the pointers for the two
structures password and group.
Step 3 : Declare an array named path[20] of character type to get the input file
along with its extension and an integer i.
Step 4 : Get the input file along with its extension.
Step 5 : If not of stat of a particular file then do the Steps 6 to 18.
Step 6 : Print the file’s pathname as file’s name along with its extension.
Step 7 : To check the type of the file whether it is a regular file or a directory use
S_ISREG( ).
Step 8 : If the above function returns true value the file is an regular file else it is
directory.
Step 9 : Display the file mode in octal representation using thebuf.st_mode.
Step 10 : Display the device id in integer representation using thebuf.st_dev.
Step 11 : Display the user id in integer representation using thebuf.st_uid.
Step 12 : Display the users pathname.
Step 13 : Display the group id in integer representation using thebuf.st_gid.
Step 14 : Display the group’s pathname.
Step 15 : Display the size of the file in integer representation using thebuf.st_size.

37
Step 16 : Display the last access in time and date format using
ctime(&thebuf.st_atime).
Step 17 : Display the last modification in time and date format
using ctime(&thebuf.st_atime).
Step 18 : Display the last status in time and date format using
ctime(&thebuf.st_atime).
Step 19 : If Step 5 fails then print “Cannot get the status details for the given file”.
SYSTEM CALLS USED :
1. stat( )
2. creat()
3. open( )
4. fstat( )
PROGRAM:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
main()
{
int fd1,fd2,n;
char source[30],ch[5];
struct stat s,t,w;

38
fd1=creat("text.txt",0644);
printf("Enter the file to be copied\n");
scanf("%s",source);
fd2=open(source,0);
if(fd2==-1)
{
perror("file doesnot exist");
exit(0);
}
while((n=read(fd2,ch,1))>0)
write(fd1,ch,n);
close(fd2);
stat(source,&s);
printf("Source file size=%ld\n",s.st_size);
fstat(fd1,&t);
printf("Destination file size =%ld\n",t.st_size);
close(fd1);
}

39
OUTPUT:

RESULT:
Thus , the program using system call stat() has been executed successfully
and the output was verified.

40
EX.NO : 2(f) PROGRAM USING SYSTEM CALLS opendir( ) readdir( )
DATE: closedir()
AIM :
To write the program to implement the system calls opendir( ), readdir( )
and closedir().
ALGORITHM :
Step 1 : Start the program.
Step 2 : In the main function pass the arguments.
Step 3 : Create structure as stat buff and the variables as integer.
Step 4 : Using the for loop, initialization takes place and activation takes place.
Step 5 : Stop the program.
SYSTEM CALLS USED:
1.opendir( )
Open a directory.
2.readdir( )
Read a directory.
3.closedir()
Close a directory.
PROGRAM:
#define _POSIX_SOURCE
#include <dirent.h>
#include <sys/types.h>
#undef _POSIX_SOURCE
#include <stdio.h>

41
main()
{
DIR *dir;
struct dirent *entry;
int count;
if ((dir = opendir("/")) == NULL)
perror("opendir() error");
else
{
count = 0;
while ((entry = readdir(dir)) != NULL) {
printf("directory entry %03d: %s\n", ++count, entry->d_name);
}
closedir(dir);
}

42
OUTPUT:

RESULT:
Thus , the program using system call opendir(),readdir() and closedir() has
been executed successfully and the output was verified.

43
EX. NO: 3(a) SIMULATION OF UNIX COMMANDS “ls”
DATE:
AIM:
To write a C program to simulate the operation of “ls” commands in Unix.
ALGORITHM :
Step 1 : Include the necessary header files.
Step 2 : Define the buffer size as 1024.
Step 3 : Get the file name which has been created already.
Step 4 : Open the file in read mode.
Step 5 :Read the contents of the file and store it in the buffer.
Step 6 : Print the contents stored in the buffer.
Step 7 : Close the file.
PROGRAM:
#include<stdio.h>
#include<dirent.h>
int main()
{
struct dirent **namelist;
int n,i;
char pathname[100];
printf("\nEnter any number");
scanf("%s",pathname);
getcwd(pathname);
n=scandir(pathname,&namelist,0,alphasort);

44
if(n<0)
printf("Error");
else
for(i=0;i<n;i++)
printf("%s\n",namelist[i]->d_name);
return 0;
}
OUTPUT:

RESULT:
Thus , the program for simulation of unix command “ls” has been executed
successfully and the output was verified.

45
EX. NO: 3(a) SIMULATION OF UNIX COMMANDS “grep”
DATE:
AIM:
To write a C program to simulate the operation of “grep” commands in
Unix.
ALGORITHM :
Step 1 : Include the necessary header files.
Step 2 : Define the buffer size.
Step 3 : Get the file name which has been created already.
Step 4 : Open the file in read mode.
Step 5 : Read the contents of the file and store it in the buffer.
Step 6 : Print the contents stored in the buffer.
Step 7 : Close the file
PROGRAM:
#include<stdio.h>
#include<string.h>
void main()
{
char fn[10],pat[10],temp[200];
FILE *fp;
printf("Enter file name\n");
scanf("%s",fn);
printf("Enter pattern to be searched\n");
scanf("%s",pat);
fp=fopen(fn,"r");
while(!feof(fp))
{
fgets(temp,1000,fp);
if(strstr(temp,pat))
printf("%s",temp);

46
}
fclose(fp);
}

OUTPUT:

RESULT:
Thus , the program for simulation of unix command “grep” has been
executed successfully and the output was verified.

47
EX. NO: 4(a) SHELL PROGRAMMING
DATE: BASIC ARITHMETIC OPERATION USIG SHELL PROGRAMMING

AIM:
To write a shell program to solve arithmetic operation.

ALGORITHM :
Step 1 : Include the necessary header files.
Step 2 : Get the input
Step 3 : Perform the arithmetic calculation.
Step 4 : Print the result.
Step 5 : Stop the exeution.

PROGRAM:
#!/bin/bash
echo "enter the a vale"
read a
echo "enter b value"
read b
c=`expr $a + $b`
echo "sum:"$c
c=`expr $a - $b`
echo "sub:"$c
c=`expr $a \* $b`
echo "mul:"$c
c=`expr $a / $b`
echo "div:"$c

48
OUTPUT:

RESULT:
Thus, the shell program for basic arithmetic operation has been
executed successfully and the output was verified.

49
EX. NO: 4(b) NUMBER CHECKING USING SHELL PROGRAM
DATE:

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

ALGORITHM :
Step 1 : Include the necessary header files.
Step 2 : Get the input
Step 3 : Perform the division by 2.
Step 4 : Print the result.
Step 5 : Stop the execution.

PROGRAM:
#!/bin/bash
num="1 2 3 4 5 6 7 8"
for n in $num
do
q=`expr $n % 2`
if [ $q -eq 0 ]
then
echo "even no"
continue
fi
echo "odd no"
done

50
OUTPUT:

RESULT:
Thus, the shell program for number checking has been executed
successfully and the output was verified.

51
EX. NO: 4(C) MULTIPLICATION TABLE USING SHELL PROGRAM
DATE:

AIM:
To write a shell program to get the multiplication table.

ALGORITHM :
Step 1 : Include the necessary header files.
Step 2 : Get the input
Step 3 : Perform the multiplication .
Step 4 : Print the result.
Step 5 : Stop the execution.

PROGRAM:
#!/bin/bash
echo " which table you want"
read n
for i in 1 2 3 4 5 6 7 8 9 10
do
echo $i "*" $n "=" `expr $i \* $n`
done

52
OUTPUT:

RESULT:
Thus, the shell program for multiplication table has been executed
successfully and the output was verified.
53
EX. NO: 4(d) USING WHILE LOOP IN SHELL PROGRAM
DATE:

AIM:
To write a shell program to print the number from 1 to 10 using while
loop.

ALGORITHM :
Step 1 : Include the necessary header files.
Step 2 : Define the buffer size as 1024.
Step 3 : Get the file name which has been created already.
Step 4 : Open the file in read mode.
Step 5 : Read the contents of the file and store it in the buffer.
Step 6 : Print the contents stored in the buffer.
Step 7 : Close the file.

PROGRAM:
#!/bin/bash
a=1
while [ $a -lt 11 ]
do
echo "$a"
a=`expr $a + 1`
done

54
OUTPUT:

RESULT:
Thus, the shell program using while loop has been executed
successfully and the output was verified.

55
EX. NO: 4(e) USING IF STATEMENT IN SHELL PROGRAMMING
DATE:

AIM:
To write a shell program to use simple if statement .

ALGORITHM :
Step 1 : Include the necessary header files.
Step 2 : Define the buffer size as 1024.
Step 3 : Get the file name which has been created already.
Step 4 : Open the file in read mode.
Step 5 : Read the contents of the file and store it in the buffer.
Step 6 : Print the contents stored in the buffer.
Step 7 : Close the file.

PROGRAM:
#!/bin/bash
for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
continue
echo "numbers"
else
echo "$var1 $var2"
fi
done
done

56
OUTPUT:

RESULT:
Thus, the shell program using if statement has been executed
successfully and the output was verified.
57
EX.NO:5.a) CPU SCHEDULING: ROUND ROBIN SCHEDULING
DATE:

AIM :
To write the program to simulate the Round Robin scheduling.

PROBLEM DESCRIPTION:
CPU scheduler will decide which process should be given the CPU for its
execution.For this it use different algorithm to choose among the process. One
among that algorithm is Round robin algorithm.
In this algorithm we are assigning some time slice .The process is allocated
according to the time slice, if the process service time is less than the time slice
then process itself will release the CPU voluntarily. The scheduler will then
proceed to the next process in the ready queue .If the CPU burst of the currently
running process is longer than time quantum, the timer will go off and will cause
an interrupt to the operating system. A
context switch will be executed and the process will be put at the tail of the ready
queue.

ALGORITHM:
Step 1: Initialize all the structure elements
Step 2: Receive inputs from the user to fill process id, burst time and arrival time.
Step 3: Calculate the waiting time for all the process id.
i) The waiting time for first instance of a process is calculated as:
a[i].waittime=count + a[i].arrivaltime
ii) The waiting time for the rest of the instances of the process is calculated
as:
a) If the time quantum is greater than the remaining burst time then
waiting time is calculated as: a[i].waittime=count + tq
b) Else if the time quantum is greater than the remaining burst time
then waiting time is calculated as: a[i].waittime=count - remaining burst time
Step 4: Calculate the average waiting time and average turnaround time
Step 5: Print the results of the step 4.

58
PROGRAM:
#include<stdio.h>
void main()
{
int i,tbt=0,nop,ts=0,flag[20], rem[20];
int from,wt[20],tt[20],b[20], twt=0,ttt=0;
int dur;
float awt,att;
clrscr();
printf("Enter no. of Processes: ");
scanf("%d",&nop);
printf("Enter the time slice: ");
scanf("%d",&ts);
printf("Enter the Burst times..\n");
for(i=0;i<nop;i++)
{
wt[i]=tt[i]=0;
printf("P%d\t: ",i+1);
scanf("%d",&b[i]);
rem[i]=b[i];
tbt+=b[i];
flag[i]=0;
}
from=0;
i=0;
printf("\n\t Gantt Chart");
printf("\n ProcessID\tFrom Time\tTo Time\n");
while(from<tbt)
{
if(!flag[i])
{
if(rem[i]<=ts)
{
dur=rem[i];
flag[i]=1;
tt[i]=dur+from;
wt[i]=tt[i]-b[i];

59
}
else
dur=ts;
printf("%7d%15d%15d\n",i+1, from,from+dur);
rem[i] -= dur;
from += dur;
}
i=(i+1)%nop;
}
for(i=0;i<nop;i++)
{
twt+=wt[i];
ttt+=tt[i];
}
printf("\n\n Process ID \t Waiting Time \t Turn Around Time");
for(i=0;i<nop;i++)
{
printf("\n\t%d\t\t%d\t\t%d",i+1,wt[i],tt[i]);
}
awt=(float)twt/(float)nop;
att=(float)ttt/(float)nop;
printf("\nTotal Waiting Time:%d",twt);
printf("\nTotal Turn Around Time:%d",ttt);
printf("\nAverage Waiting Time:%.2f",awt);
printf("\nAverage Turn Around Time:%.2f\n",att);
getch();
}

60
OUTPUT:

RESULT:
Thus, the c program for CPU scheduling : Round Robin has been executed
successfully and the output was verified.

61
EX.NO:5(b) CPU SCHEDULING: SHORTEST JOB FIRST.
DATE:
AIM:
To write a C program to implement the CPU scheduling algorithm for
shortest job first.

PROBLEM DESCRIPTION:
CPU scheduler will decide which process should be given the CPU for its
execution .For this it uses different algorithm to choose among the process. One
among that algorithm is SJF algorithm.
In this algorithm the process which has less service time given the CPU after
finishing its request only it will allow CPU to execute next other process.

ALGORITHM:
Step 1: Get the number of process.
Step 2: Get the id and service time for each process.
Step 3: Initially the waiting time of first short process as 0 and total time of
first short process is the service time of that process.
Step 4: Calculate the total time and waiting time of remaining process.
Step 5: Waiting time of one process is the total time of the previous process.
Step 6: Total time of process is calculated by adding the waiting time and
service time of each process.
Step 7: Total waiting time calculated by adding the waiting time of each process.
Step 8: Total turn around time calculated by adding all total time of each process.
Step 9: Calculate average waiting time by dividing the total waiting
time by total number of process.
Step 10: Calculate average turn around time by dividing the total waiting time
by total number of process.
Step 11: Display the result.
PROGRAM:
#include<stdio.h>
void main()
{
int n,w[100],tot[100],i,j,awt,atot;
float avwt,avtot;
struct
62
{
int p,bt;
}sjf[10],temp;
clrscr();
printf("Enter the number of Processes:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter the Burst time for Process%d : ",i); scanf("%d",&sjf[i].bt);
sjf[i].p=i;
}
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(sjf[j].bt>sjf[i].bt)
{
temp=sjf[i];
sjf[i]=sjf[j];
sjf[j]=temp;
}
w[1]=0;
tot[1]=sjf[1].bt;
for(i=2;i<=n;i++) tot[i]=tot[i-1]+sjf[i].bt;
awt=0;
atot=0;
for(i=1;i<=n;i++)
{
w[i]=tot[i]-sjf[i].bt; awt+=w[i]; atot+=tot[i];
}
avwt=(float)awt/n;
avtot=(float)atot/n;
printf("\n\nProcessId\tWaiting time\t TurnaroundTime");
for(i=1;i<=n;i++)
printf("\n\t%d\t\t%d\t\t%d",sjf[i].p,w[i],tot[i]);
printf("\n\nTotal Waiting Time :%d",awt);
printf("\n\nTotal Turnaround Time :%d",atot);
printf("\n\nAverage Waiting Time :%.2f",avwt);
printf("\n\nAverage Turnaround Time :%.2f",avtot);

63
getch();
}
OUTPUT:

RESULT:
Thus, the c program for CPU scheduling : shortest job first has been
executed successfully and the output was verified.

64
EX.NO: 5(c) i) CPU SCHEDULING: FIRST COME FIRST SERVE WITHOUT
DATE: ARRIVAL TIME
AIM:
To write a C program to implement the first come first serve without arrival
time CPU scheduling algorithm

PROBLEM DESCRIPTION:
CPU scheduler will decide which process should be given the CPU for its
execution.For this it uses different algorithm to choose among the process. One
among that algorithm is FCFS algorithm.
In this algorithm the process which arrive first is given the CPU after
finishing its request only it will allow CPU to execute other process.

ALGORITHM:
Step 1: Create the number of process.
Step 2: Get the ID and service time for each process.
Step 3: Initially, Waiting time of first process is zero and Total time for the
first process is the starting time of that process.
Step 4: Calculate the Total time and Processing time for the remaining
processes.
Step 5: Waiting time of one process is the Total time of the previous
process.
Step 6: Total time of process is calculated by adding Waiting time and
Service time.
Step 7: Total waiting time is calculated by adding the waiting time for lack
process.
Step 8: Total turn around time is calculated by adding all total time of
each process.
Step 9: Calculate Average waiting time by dividing the total waiting
time by total number of process.
Step 10: Calculate Average turn around time by dividing the total time by
the number of process.
Step 11: Display the result.

PROGRAM:

65
#include<stdio.h>
void main()
{
int n,b[10],t=0,i,w=0,r=0,a=0;
float avg,avg1;
printf("\nEnter number of processes:");
scanf("%d",&n);
printf("\nEnter the burst times : \n");
for(i=1;i<=n;i++)
scanf("%d",&b[i]);
printf("\n Gantt chart ");
for(i=1;i<=n;i++)
printf("P%d\t",i);
printf("\n\nProcess BurstTime WaitingTime TurnaroundTime\n");
for(i=1;i<=n;i++)
{
t=t+w;
r=r+b[i];
printf("P%d\t\t%d\t\t%d\t\t%d\t\t\n",i,b[i],w,r);
w=w+b[i];
a=a+r;
}
avg=(float)t/n;
avg1=(float)a/n;
printf("\n Average WaitingTime is %f",avg);
printf("\n Average TurnaroundTime is %f\n",avg1);
getch();
}

OUTPUT:

66
RESULT:
Thus , the c program for CPU scheduling : First come first serve without
arrival time has been executed successfully and the output was verified.

67
EX.NO: 5(c)ii) CPU SCHEDULING: FIRST COME FIRST SERVE WITH ARRIVAL TIME
DATE:
AIM:
To write a C program to implement the array representation of the CPU
scheduling algorithm first come first serve using arrival time.
PROBLEM DESCRIPTION:
CPU scheduler will decide which process should be given the CPU for its
execution. For this it uses different algorithm to choose among the process. One
among that algorithm is FCFS algorithm.
In this algorithm the process which arrive first is given the CPU after
finishing its request only it will allow CPU to execute other process
ALGORITHM:
Step 1: Create the number of process.
Step 2: Get the ID and Service time for each process.
Step 3: Initially, Waiting time of first process is zero and Total time for the first
process is the starting time of that process.
Step 4: Calculate the Total time and Processing time for the remaining processes.
Step 5: Waiting time of one process is the Total time of the previous process.
Step 6: Total time of process is calculated by adding Waiting time and Service
time.
Step 7: Total waiting time is calculated by adding the waiting time for lack
process.
Step 8: Total turn around time is calculated by adding all total time of each
process.
Step 9: Calculate Average waiting time by dividing the total waiting time by total
number of process.
Step 10: Calculate Average turn around time by dividing the total time by the
number of process.
Step 11: Display the result.

PROGRAM:

68
#include<stdio.h>
struct process
{
char name[5];
int at, bt, wt, tt;
};
int main( )
{
int i, j, n, t;
float awt=0, att=0;
struct process p[10], temp;
clrscr();
printf(“\n Enter the number of process: ”);
scanf(“%d”, &n);
for(i=0; i<=n; i++)
{
printf(“\n Enter the name, arrival time and burst time of process %d:”, i+1);
scanf(“%s %d %d”, &p[i].name, &p[i].at, &p[i].bt);
}
for(i=0; i<n-1; i++)
for(j=0; j<n-1; j++)
if(p[j].at>p[j+1].at)
{
temp=p[j];
p[j]=p[j+1];
p[j+1=temp;
}
p[0].wt=0;
t=p[0].tt=p[0].bt;
att+=p[0].bt;
for(i=1;i<n;i++)
{
p[i].wt=t-p[i].at;
t+=p[i].bt;
p[i].tt=p[i].wt+p[i].bt;
awt+=p[i].wt;
att+=p[i].tt;

69
}
printf(“\n Process Name Arrival time burst time Waiting Time Turnaround
Time\n”);
for(i=0;i<n;i++)
printf(“%s \t\t %d \t\t % d \t\t % d \t\t % d \n”, p[i].name, p[i].at, p[i].bt, p[i].wt,
p[i].tt);
awt/=n;
att/=n;
printf(“\n Average waiting Time : %f”, awt);
printf(“\n Average Turnaround Time : %f\n”, att);
getch();
}
OUTPUT:

RESULT:
Thus , the c program CPU scheduling : First come first serve with arrival has
been executed successfully and the output was verified.

70
EX.NO: 5(c)iii) CPU SCHEDULING: PRIORITY SCHEDULING
DATE:
AIM:
To write a C program to implement the CPU scheduling algorithm for
Priority.
PROBLEM DESCRIPTION:
CPU scheduler will decide which process should be given the CPU for its
execution. For this it uses different algorithm to choose among the process. One
among that algorithm is Priority algorithm.
In this algorithm the processes will be given the priorities. The process
which is having the highest priority is allocated the CPU first. After finishing the
request the CPU is allocated to the next highest priority and so on.
ALGORITHM:
Step 1: Get the number of process.
Step 2: Get the id and service time for each process.
Step 3: Initially the waiting time of first short process as 0 and total time of first
short process is the service time of that process.
Step 4: Calculate the total time and waiting time of remaining process.
Step 5: Waiting time of one process is the total time of the previous process.
Step 6: Total time of process is calculated by adding the waiting time and service
time of each process.
Step 7: Total waiting time calculated by adding the waiting time of each process.
Step 8: Total turn around time calculated by adding all total time of each process.
Step 9: Calculate average waiting time by dividing the total waiting time by total
number of process.
Step 10: Calculate average turn around time by dividing the total waiting time by
total number of process.
Step 11: Display the result.

PROGRAM:

71
#include<stdio.h>
void main()
{
int n,temp=0,w[20],b[20], p[20],t2[20],j,t1,d[20],i,te=0,b1[20],t3=0;
float t,r;
w[1]=0;
clrscr();
printf("\nEnter no. of processes:");
scanf("%d",&n);
printf("\nEnter the burst times : ");
for(i=1;i<=n;i++)
{
printf("P%d : ",i);
scanf("%d",&b[i]); d[i]=i;
}
printf("Enter the priorities:");
for(i=1;i<=n;i++)
{
printf("P%d : ",i);
scanf("%d",&p[i]);
}
for(i=1;i<=n;i++)
for(j=i+1;j<=n;j++)
if(p[i]<p[j])
{
temp=p[i];
t1=d[i];
te=b[i];
p[i]=p[j];
d[i]=d[j];
b[i]=b[j];
p[j]=temp;
d[j]=t1;
b[j]=te;
}
printf("\nGantt Chart : ");
for(i=1;i<=n;i++)

72
printf("P%d\t",d[i]);
printf("\nProcess \t Priority\tBurst Time\t Waiting Time\t Turnaround Time");
for(i=1;i<=n;i++)
{
t=d[i];
w[i+1]=w[i]+b[i];
t2[i]=b[i]+w[i];
t3+=t2[i];
printf("\nP%d\t\t%d\t\t%d\t\t%d\t\t%d",d[i],p[i],b[i],w[i],t2[i]);
}
temp=0;
for(i=1;i<=n;i++)
temp+=w[i];
t=(float)temp/n;
r=(float)t3/n;
printf("\nAverage Waiting time : %.2f",t);
printf("\nAverage Turnaround time : %.2f",r);
getch();
}

73
OUTPUT:

RESULT:
Thus ,the c program for CPU scheduling : priority scheduling has been
executed successfully and the output was verified.

74
EX.NO: 6 IMPLEMENTATION OF SEMAPHORE
DATE:
AIM:
To write a C program to implement the Producer & consumer Problem
(Semaphore)
ALGORITHM:
Step 1: The Semaphore mutex, full & empty are initialized.
Step 2: In the case of producer process
a. Produce an item in to temporary variable.
b. If there is empty space in the buffer check the mutex value for enter into
the critical section.
c. If the mutex value is 0, allow the producer to add value in the temporary
variable to the buffer.
Step 3: In the case of consumer process
a. It should wait if the buffer is empty
b. If there is any item in the buffer check for mutex value, if the mutex==0,
remove item from buffer
c. Signal the mutex value and reduce the empty value by 1.
Consume the item.
Step 4: Print the result .

75
PROGRAM:
#include<stdio.h>
int mutex=1,full=0,empty=3,x=0;
main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
clrscr();
printf("\n1.producer\n2.consumer\n3.exit\n");
while(1) {
printf(" \nEnterur choice");
scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty");
break;
case 3:
exit(0);
break;
}
}
}
76
int wait(int s)
{
return(--s);
}
int signal(int s)
{
return (++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("Producer produces the items %d",x);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("Consumer consumes the item %d",x);
x--;
mutex=signal(mutex);
}

77
OUTPUT:

RESULT:
Thus , the c program for implementation of semaphore has been executed
successfully and the output was verified.

78
EX.NO: 7 IMPLEMENTATION OF SHARED MEMORY AND IPC
DATE:
AIM:
To write a C program to implement shared memory and inter process
communication.
ALGORITHM:
Step 1: Start the Program
Step 2:Obtain the required data through char and int datatypes.
Step 3:Enter the file name,index block.
Step 4: Print the file name index loop.
Step 5:File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
PROGRAM:
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>
int main()
{
int id,semid,count=0,i=1,j;
int *ptr;
id=shmget(8078,sizeof(int),IPC_CREAT|0666);
ptr=(int *)shmat(id,NULL,0);

79
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
}u;
struct sembuf sem;
semid=semget(1011,1,IPC_CREAT|0666);
ushort a[1]={1};
u.array=a;
semctl(semid,0,SETALL,u);
while(1)
{
sem.sem_num=0;
sem.sem_op=-1;
sem.sem_flg=0;
semop(semid,&sem,1);
*ptr=*ptr+1;
printf("process id:%d \ncountis :%d \n",getpid(),*ptr);
for(j=1;j<=1000000000;j++)
{
sem.sem_num=0;
sem.sem_op=+1;
sem.sem_flg=0;

80
semop(semid,&sem,1);
}
}
shmdt(ptr);
}
OUTPUT:

RESULT:
Thus , the program for implementation of shared memory and IPC has been
executed successfully and the output was verified.

81
EX.NO: 8 IMPLEMENTATION BANKERS ALGORITHM FOR DEAD LOCK
DATE: AVOIDANCE

AIM:
To write a C program to implement bankers algorithm for dead lock
avoidance.
ALGORITHM:
Step 1: Start the Program
Step 2: Obtain the required data through char and int datatypes.
Step 3: Enter the filename, index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks.
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void main()
{
int work[5],avl[5],alloc[10][10],l;
int need[10][10],n,m,i,j,avail[10],max[10][10],k,count,fcount=0,pr[10];
char finish[10]={'f','f','f','f','f','f','f','f','f','f'};
clrscr();
printf("Enter the no of process:");
scanf("%d",&n);
printf("Enter the no of resources:");
scanf("%d",&m);
printf("Enter the total no of resources:\n");
for(i=1;i<=m;i++)
scanf("%d",&avail[i]);
printf("Enter the max resources req by each pralloc matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)

82
scanf("%d",&max[i][j]);
printf("Process allocation matrix:\n");
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&alloc[i][j]);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
need[i][j]=max[i][j]-alloc[i][j];
for(i=1;i<=n;i++)
{
k=0;
for(j=1;j<=m;j++)
{
k=k+alloc[i][j];
}
avl[i]=avl[i]-k;
work[i]=avl[i];
}
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
{
count=0;
for(j=1;j<=m;j++)
{
if((finish[i]=='f')&&(need[i][j]<=work[i]))
count++;
}
if(count==m)
{
for(l=1;l<=m;l++)
work[l]=work[l]+alloc[i][l];
finish[i]='t';
pr[k]=i;
break;
}
83
}
for(i=1;i<=n;i++)
if(finish[i]=='t')
fcount++;
if(fcount==n)
{
printf("The system is in safe state ");
for(i=1;i<=n;i++)
printf("%d",pr[i]);
}
else
printf("The system is not in safe state ");
getch();
}

84
OUTPUT:

RESULT:
Thus, the c program for implementation of bankers algorithm for deadlock
avoidance has been executed successfully and the output was verified.

85
EX.NO: 9 IMPLEMENTATION OF DEADLOCK DETECTION ALGORITHM
DATE:

AIM:
To write a C program to implement Deadlock Detection algorithm
ALGORITHM:
Step 1: Start the Program
Step 2: Obtain the required data through char and int data types.
Step 3: Enter the filename, index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
PROGRAM:
#include <stdio.h>
#include <conio.h>
void main()
{
int found,flag,l,p[4][5],tp,tr,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
clrscr();
printf("Enter total no of processes");
scanf("%d",&tp);
printf("Enter total no of resources");
scanf("%d",&tr);
printf("Enter claim (Max. Need) matrix\n");
for(i=1;i<=tp;i++)
{
printf("process %d:\n",i);
for(j=1;j<=tr;j++)
scanf("%d",&c[i][j]);
}
printf("Enter allocation matrix\n");
for(i=1;i<=tp;i++)
{
printf("process %d:\n",i);
86
for(j=1;j<=tr;j++)
scanf("%d",&p[i][j]);
}
printf("Enter resource vector (Total resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&r[i]);
}
printf("Enter availability vector (available resources):\n");
for(i=1;i<=tr;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}
for(i=1;i<=tp;i++)
{
sum=0;
for(j=1;j<=tr;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=1;i<=tp;i++)
{
for(l=1;l<k;l++)
if(i!=m[l])
{
flag=1;
for(j=1;j<=tr;j++)
if(c[i][j]<temp[j])
87
{
flag=0;
break;
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=1;j<=tr;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are:");
for(j=1;j<=tp;j++)
{
found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0)
printf("%d\t",j);
}
getch();
}

88
OUTPUT:

RESULT:
Thus , the c program for implementation of deadlock detection algorithm
has been executed successfully and the output was verified.

89
EX.NO: 10 THREADING & SYNCHRONIZATION
DATE:
AIM:
To write a C program to implement Threading & Synchronization.
ALGORITHM:
Step 1: Start the Program
Step 2: Obtain the required data through char and int data types.
Step 3: Enter the filename, index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int counter;
void* doSomeThing(void *arg)
{
unsigned long i = 0;
counter += 1;

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

91
OUTPUT:

RESULT:
Thus , the program for threading and synchronization has been executed
successfully and the output was verified.

92
EX.NO:11(a) MEMORY ALLOCATION METHOD -FIRST FIT
DATE:

AIM:
To write a C program to implement first fit algorithm for memory
management.

ALGORITHM:
Step1:Start the process.
Step2:Declare the size.
S t e p 3: G e t t he nu m b er o f pr o ces s es to b e i ns er t ed .
S t e p 4:Allocate the first hole that is big enough searching.
Step 5 : S ta r t a t t he b eg i n ni n g o f t he s e t o f ho l es .
S t e p 6:If not start at the hole that is sharing the previous first
fit search end.
Step 7:If large enough then stop searching in the procedure.
Step 8 : D i s p l a y t h e v a l u e s .
Step9:Stop the process.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
printf("\n Memory 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);

93
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)
{
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]);
getch();
}

94
OUTPUT:

RESULT:
Thus ,the c program for Memory allocation method-First Fit has been
executed and the output was verified successfully.

95
EX.NO:11(b) MEMORY ALLOCATION METHOD - WORST FIT
DATE:

AIM:
To write a C program to implement worst fit algorithm for memory
management.

ALGORITHM:
Step 1 : S t a r t t h e p r o g r a m .
Step2:Declare the size.
S t e p 3: G e t t he nu m b er o f pr o ces s es t o b e i ns er t ed .
S t e p 4:Allocate the first hole that is small enough searching.
Step 5:If small enough then stop searching in the procedure.
Step 6 : D i s p l a y t h e v a l u e s .
Step7:Stop the program.

PROGRAM:
#include<conio.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];
clrscr();
printf("\n Memory 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++)

96
{
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)
{
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]);
getch();
}

97
OUTPUT:

RESULT:
Thus , the c program for Memory allocation method-Worst Fit has been
executed successfully and the output was verified.

98
EX.NO:11(c) MEMORY ALLOCATION MOTHOD - BEST FIT
DATE:

AIM:
To write a C program to implement best fit algorithm for memory
management.
ALGORITHM:
Step1:Start the program.
Step2:Declare the size.
S t e p 3: G et t he n u m b er o f pr o ces s es to b e i ns e r te d.
S t e p 4: Allocate the best hole that is small enough searching.
Step 5 : S t a r t a t th e b es t o f t he s et o f ho l es .
S t e p 6: If not start at the hole that is sharing the previous best fit
search end.
Step 7 : C o m p a r e t h e h o l e i n t h e l i s t .
S t e p 8:If small enough then stop searching in the procedure.
Step 9 : D i s p l a y t h e v a l u e s .
S t e p 10:Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.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];
clrscr();
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);
99
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)
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]);
getch();
}

100
OUTPUT:

RESULT:
Thus , the c program for Memory allocation method – Best Fit has been
executed successfully and the output was verified.

101
EX.NO: 12 IMPLEMENTATION OF PAGING TECHNIQUE OF MEMORY
DATE: MANAGEMENT

AIM:
To write a C program to implement the concept of Paging.
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.
Step 6: Stop the process

PROGRAM:
#include<stdio.h>
void main()
{
inti,j,arr[100],pt[20],val,pgno,offset,phymem,fs,nf;
clrscr();
printf("\nMemory Management paging\n");
printf("\nEnter the size of physical memory:");
scanf("%d",&phymem);
for(i=20,j=0;i<phymem+20,j<phymem;i++,j++)
arr[i]=j;
printf("\nEnter size of frame or page:");
scanf("%d",&fs);
nf=phymem/fs;
printf("\nNo of frame available are\t%d",nf);
printf("\nEnter the page table\n");
for(i=0;i<nf;i++)
{
scanf("%d",&pt[i]);
}

102
printf("\nEnter the page no:");
scanf("%d",&pgno);
printf("\nEnter the offset:");
scanf("%d",&offset);
val=(fs*pt[pgno])+offset;
printf("The physical address is:%d\n",arr[val]);
getch();
}
OUTPUT:

RESULT:
Thus , the c program for implementation of paging technique of memory
management has been executed successfully and the output was verified.

103
EX.NO:13(a) IMPLEMENTATION OF FIFO PAGE REPLACEMENT
DATE:

AIM:
To write a c program to implement FIFO page replacement algorithm

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

PROGRAM:
#include<stdio.h>
void main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0;
clrscr();
printf("\n ENTER THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{

104
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count);
getch();
}
OUTPUT:

RESULT:
Thus , the c program for implementation of FIFO page replacement
algorithm has been executed successfully and the output was verified.

105
EX.NO:13(b) IMPLEMENTATION OF LRU PAGE REPLACEMENT ALGORITHM
DATE:

AIM:
To write a C program to implement LRU page replacement algorithm

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

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];
clrscr();
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++)
{

106
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
if(b[r]<b[j])
{

107
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);
getch();
}

108
OUTPUT:

RESULT:
Thus , the c program for implementation of LRU page replacement
algorithm has been executed successfully and the output was verified.

109
EX.NO: 13(c) PAGE REPLACEMENT ALGORITHMS – LFU
DATE:
AIM:
To write a C program to page replacement LFU (Least Frequently Used)
algorithm.
ALGORITHM:
Step 1: Start the Program
Step 2:Obtain the required data through char and int datatypes.
Step 3:Enter the filename,index block.
Step 4: Print the file name index loop.
Step 5:Fill is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
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];
clrscr();
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])
110
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf("\t%d",q[j]);
printf("\n");
}
else
{
for(r=0;r<f;r++)
{
c2[r]=0;
for(j=i-1;j<n;j--)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;

111
}
}
}
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);
getch();
}
OUTPUT:

RESULT:
Thus , the c program for implementation of LFU page replacement
algorithm has been executed successfully and the output was verified.

112
EX.NO:14(a) FILE ORGANIZATION TECHNIQUES - SINGLE LEVEL DIRECTORY
DATE:
AIM:
To write a C program to implement File Organization concept using the
technique Single level directory.

ALGORITHM:
Step 1: Start the Program
Step 2:Obtain the required data through char and int datatypes.
Step 3:Enter the filename,index block.
Step 4: Print the file name index loop.
Step 5:Fill is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm,count,i,j,mid,cir_x;
char fname[10][20];
clrscr();
initgraph(&gd,&gm,"c:\tc\bgi");
cleardevice();
setbkcolor(GREEN);
puts("Enter no of files do u have?");
scanf("%d",&count);
for(i=0;i<count;i++)
{
cleardevice();
setbkcolor(GREEN);
printf("Enter file %d name:",i+1);
scanf("%s",fname[i]);
setfillstyle(1,MAGENTA);
113
mid=640/count;
cir_x=mid/3;
bar3d(270,100,370,150,0,0);
settextstyle(2,0,4);
settextjustify(1,1);
outtextxy(320,125,"Root Directory");
setcolor(BLUE);
for(j=0;j<=i;j++,cir_x+=mid)
{
line(320,150,cir_x,250);
fillellipse(cir_x,250,30,30);
outtextxy(cir_x,250,fname[j]);
}
getch();
}
}

OUTPUT:

114
115
RESULT:
Thus , the c program for File organization technique : single level directory
has been executed successfully and the output was verified.

116
EX.NO:14(b) FILE ORGANIZATION TECHNIQUES : TWO LEVEL
DATE:

AIM:
To write a C program to implement File Organization concept using the
technique two level directory.

ALGORITHM:
Step 1: Start the Program
Step 2: Obtain the required data through char and in datatypes.
Step 3: Enter the filename, index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
PROGRAM:
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
void main()
{
int gd=DETECT,gm;
node *root;
root=NULL;
clrscr();
create(&root,0,"null",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\tc\bgi");
display(root);
getch();
closegraph();

117
}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
node *link[5],*name,*y;
if(*root==NULL)
{
(*root)=(node*)malloc(sizeof(node));
printf("enter name of dir/file(under %s):",dname); fflush(stdin);
gets((*root)->name);
if(lev==0||lev==1)
(*root)->ftype=1;
else
(*root)->ftype=2;
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x; (*root)->lx=lx; (*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
if(lev==0||lev==1)
{
if((*root)->level==0)
printf("How many users");
else
printf("hoe many files");
printf("(for%s):",(*root)->name);
scanf("%d",&(*root)->nc);
}
else
(*root)->nc=0;
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)

118
create(&((*root)->link[i]),lev+1,(*root-
>name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}
return 0;
}
display(node *root)
{
int i;
node *y;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root>y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}

OUTPUT:
119
RESULT:
Thus , the c program for File organization technique : two level has been
executed successfully and the output was verified.

120
EX.NO: 14(c) FILE ORGANIZATION TECHNIQUES : HIERARCHICAL
DATE:
AIM:
To write a C program to implement File Organization concept using the
technique hierarchical level directory.

ALGORITHM:
Step 1: Start the Program
Step 2:Obtain the required data through char and int datatypes.
Step 3:Enter the filename,index block.
Step 4: Print the file name index loop.
Step 5:Fill is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
PROGRAM:
#include<stdio.h>
#include<graphics.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
void main()
{
int gd=DETECT,gm;
node *root,*nc,*link,*name;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
clrscr();
initgraph(&gd,&gm,"c:\tc\BGI");
display(root);
getch();
closegraph();
121
}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("Enter name of dir/file(under %s) : ",dname); fflush(stdin);
gets((*root)->name);
printf("enter 1 for Dir/2 for file :");
scanf("%d",&(*root)->ftype);
(*root)->level=lev;
(*root)->y=50+lev*50;
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("No of sub directories/files(for %s):",(*root)->name);
scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else gap=(rx-lx)/(*root)->nc; for(i=0;i<(*root)->nc;i++)
create(&((*root)->link[i]),lev+1,(*root)-
>name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else (*root)->nc=0;
}
return 0;
}
display(node *root)
{
int i;
node*y;
settextstyle(2,0,4);

122
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14); if(root
!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1) bar3d(root->x-20,root->y-10,root->x+20,root>y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name); for(i=0;i<root->nc;i++)
{
display(root->link[i]); } }
return 0;
}

OUTPUT:

123
RESULT:
Thus , the c program for File organization technique : hierarchical has been
executed successfully and the output was verified.
124
EX.NO: 14(d) FILE ORGANIZATION TECHNIQUES : DAG
DATE:

AIM:
To write a C program to implement File Organization concept using the
technique using DAG.

ALGORITHM:
Step 1: Start the Program
Step 2:Obtain the required data through char and int datatypes.
Step 3:Enter the filename,index block.
Step 4: Print the file name index loop.
Step 5:File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<string.h>
struct tree_element
{
char name[20];
int x,y,ftype,lx,rx,nc,level;
struct tree_element *link[5];
};
typedef struct tree_element node;
typedef struct
{
char from[20];
char to[20];
}link;
link L[10];
int nofl;
node * root;
void main()
{

125
int gd=DETECT,gm;
root=NULL;
clrscr();
create(&root,0,"root",0,639,320);
read_links();
clrscr();
initgraph(&gd,&gm,"c:\tc\BGI");
draw_link_lines();
display(root);
getch();
closegraph();
}
read_links()
{
int i;
printf("how many links");
scanf("%d",&nofl);
for(i=0;i<nofl;i++)
{
printf("File/dir:");
fflush(stdin);
gets(L[i].from);
printf("user name:");
fflush(stdin);
gets(L[i].to);
}
return 0;
}
draw_link_lines()
{
int i,x1,y1,x2,y2;
for(i=0;i<nofl;i++)
{
search(root,L[i].from,&x1,&y1);
search(root,L[i].to,&x2,&y2);
setcolor(LIGHTGREEN);
setlinestyle(3,0,1);

126
line(x1,y1,x2,y2);
setcolor(YELLOW);
setlinestyle(0,0,1);
}
return 0;
}
search(node *root,char *s,int *x,int *y)
{
int i;
if(root!=NULL)
{
if(strcmpi(root->name,s)==0)
{
*x=root->x;
*y=root->y;
return 0;
}
else
{
for(i=0;i<root->nc;i++)
search(root->link[i],s,x,y);
}
}
return 0;
}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i,gap;
if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node));
printf("enter name of dir/file(under %s):",dname);
fflush(stdin);
gets((*root)->name);
printf("enter 1 for dir/ 2 for file:");
scanf("%d",&(*root)->ftype); (*root)->level=lev;
(*root)->y=50+lev*50;

127
(*root)->x=x;
(*root)->lx=lx;
(*root)->rx=rx;
for(i=0;i<5;i++)
(*root)->link[i]=NULL;
if((*root)->ftype==1)
{
printf("no of sub directories /files (for %s):",(*root)->name);
scanf("%d",&(*root)->nc);
if((*root)->nc==0)
gap=rx-lx;
else
gap=(rx-lx)/(*root)->nc;
for(i=0;i<(*root)->nc;i++)
create( & ( (*root)->link[i] ) , lev+1 ,(*root)-
>name,lx+gap*i,lx+gap*i+gap,lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}
return 0;
}
/* displays the constructed tree in graphics mode */
display(node *root)
{
int i;
settextstyle(2,0,4);
settextjustify(1,1);
setfillstyle(1,BLUE);
setcolor(14);
if(root!=NULL)
{
for(i=0;i<root->nc;i++)
{
line(root->x,root->y,root->link[i]->x,root->link[i]->y);
}
if(root->ftype==1)

128
bar3d(root->x-20,root->y-10,root->x+20,root->y+10,0,0);
else
fillellipse(root->x,root->y,20,20);
outtextxy(root->x,root->y,root->name);
for(i=0;i<root->nc;i++)
{
display(root->link[i]);
}
}
return 0;
}

OUTPUT:

129
RESULT:
Thus , the c program for File organization technique : DAG has been
executed successfully and the output was verified.
130
EX.NO:15(a) SEQUENTIAL FILE ALLOCATION TECHNIQUE
DATE:

AIM:
To write a C Program to implement Sequential File Allocation method.

ALGORITHM:
Step 1: Start the Program
Step 2: Obtain the required data through char and int datatypes.
Step 3: Enter the filename,index block.
Step 4: Print the file name index loop.
Step 5: File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution.

PROGRAM:
#include<stdio.h>
void main()
{
int n,i,j,b[20],sb[20],t[20],x,c[20][20];
clrscr();
printf("Enter no.of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter no. of blocks occupied by file%d:",i+1);
scanf("%d",&b[i]);
printf("Enter the starting block of file%d:",i+1);
scanf("%d",&sb[i]);
t[i]=sb[i];
for(j=0;j<b[i];j++)
c[i][j]=sb[i]++;
}
printf("Filename\tStart block\tlength\n");
for(i=0;i<n;i++)
printf("%d\t %d \t %d\n",i+1,t[i],b[i]);
getch();

131
}

OUTPUT:

RESULT:
Thus , the c program sequential file allocation technique has been executed
successfully and the output was verified.
132
EX.NO :15(b) INDEXED FILE ALLOCATION TECHNIQUE
DATE:
AIM:
To write a C program to implement File Allocation concept using the
technique indexed allocation Technique.

ALGORITHM:
Step 1: Start the Program
Step 2:Obtain the required data through char and int datatypes.
Step 3:Enter the filename,index block.
Step 4: Print the file name index loop.
Step 5:File is allocated to the unused index blocks
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution.

PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int n,m[20],i,j,sb[20],s[20],b[20][20],x;
clrscr();
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("Enter starting block and size of file%d:",i+1);
scanf("%d%d",&sb[i],&s[i]);
printf("Enter blocks occupied by file%d:",i+1);
scanf("%d",&m[i]);
printf("enter blocks of file%d:",i+1);
for(j=0;j<m[i];j++)
scanf("%d",&b[i][j]);
} printf("\nFile\t index\tlength\n");
for(i=0;i<n;i++)
{
printf("%d\t%d\t%d\n",i+1,sb[i],m[i]);

133
}printf("\nEnter file name:");
scanf("%d",&x);
printf("file name is:%d\n",x);
i=x-1;
printf("Index is:%d",sb[i]);
printf("Block occupied are:");
for(j=0;j<m[i];j++)
printf("%3d",b[i][j]);
getch();
}

OUTPUT:

RESULT:
Thus , the c program for indexed file allocation technique has been
executed successfully and the output was verified.

134
EX.NO : 15(c) LINKED FILE ALLOCATION TECHNIQUE
DATE:
AIM:
To write a C program to implement File Allocation concept using the
technique Linked List Technique.

ALGORITHM:
Step 1: Start the Program
Step 2:Obtain the required data through char and int datatypes.
Step 3:Enter the filename , starting block ending block.
Step 4: Print the free block using loop.
Step 5:”for‟ loop is created to print the file utilization of linked type of entered
type .
Step 6: This is allocated to the unused linked allocation.
Step 7: Stop the execution.

PROGRAM:
#include<stdio.h>
#include<conio.h>
struct file
{
char fname[10];
int start,size,block[10];
}f[10];
void main()
{
int i,j,n;
clrscr();
printf("Enter no. of files:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter file name:");
scanf("%s",&f[i].fname);
printf("Enter starting block:");
scanf("%d",&f[i].start);

135
f[i].block[0]=f[i].start;
printf("Enter no.of blocks:");
scanf("%d",&f[i].size);
printf("Enter block numbers:");
for(j=1;j<=f[i].size;j++)
{
scanf("%d",&f[i].block[j]);
}
}
printf("File\tstart\tsize\tblock\n");
for(i=0;i<n;i++)
{
printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size);
for(j=1;j<=f[i].size-1;j++)
printf("%d--->",f[i].block[j]);
printf("%d",f[i].block[j]);
printf("\n");
}
getch();
}

136
OUTPUT:

RESULT:
Thus , the c program for linked file allocation has been executed and the
output was verified successfully.

137

You might also like