Os Lab Manual
Os Lab Manual
TECHNOLOGY
UDAYA NAGAR, VELLAMODI
KANYAKUMARI DISTRICT
Reg. No:
Name :
Semester :
Department :
Subject Name :
Subject Code :
SUN COLLEGE OF ENGINEERING AND
TECHNOLOGY
UDAYA NAGAR, VELLAMODI
Kanyakumari District
Bonafide Certificate
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)
Ex.no: 1a(i) Simulation of ls command
Date:
Aim:
To simulate ls command using UNIX system calls.
Algorithm:
1. Store path of current working directory using getcwd system call.
2. Scan directory of the stored path using scandir system call and sort the resultant
array of structure.
3. Display dname member for all entries if it is not a hidden file.
4. Stop.
Program:-
#include <stdio.h>
#include <dirent.h>
main()
{
struct dirent **namelist;
int n,i;
char pathname[100];
getcwd(pathname);
n = scandir(pathname, &namelist, 0, alphasort);
if(n < 0)
printf("Error\n");
else
for(i=0; i<n; i++)
if(namelist[i]->d_name[0] != '.')
printf("%-20s", namelist[i]->d_name);
}
Result
Thus the filenames/subdirectories are listed, similar to ls command
Ex.no: 1a(ii) Simulation of grep command
Date:
Aim:
To simulate grep command using UNIX system call.
Algorithm:
1. Get filename and search string as command-line argument.
2. Open the file in read-only mode using open system call.
3. If file does not exist, then stop.
4. Let length of the search string be n.
5. Read line-by-line until end-of-file
a. Check to find out the occurrence of the search string in a line by examining
characters in the range 1–n, 2–n+1, etc.
b. If search string exists, then print the line.
6. Close the file using close system call.
7. Stop.
Program:-
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main(int argc,char *argv[])
{
FILE *fd;
char str[100];
char c;
int i, flag, j, m, k;
char temp[30];
if(argc != 3)
{
printf("Usage: gcc mygrep.c –o mygrep\n");
printf("Usage: ./mygrep <search_text> <filename>\n");
exit(-1);
}
fd = fopen(argv[2],"r");
if(fd == NULL)
{
printf("%s is not exist\n",argv[2]);
exit(-1);
}
while(!feof(fd))
{
i = 0;
while(1)
{
c = fgetc(fd);
if(feof(fd))
{
str[i++] = '\0';
break;
}
if(c == '\n')
{
str[i++] = '\0';
break;
}
str[i++] = c;
}
if(strlen(str) >= strlen(argv[1]))
for(k=0; k<=strlen(str)-strlen(argv[1]); k++)
{
for(m=0; m<strlen(argv[1]); m++)
temp[m] = str[k+m];
temp[m] = '\0';
if(strcmp(temp,argv[1]) == 0)
{
printf("%s\n",str);
break;
}
}
}
}
Result
Thus the program simulates grep command by listing lines containing the search text.
Ex.no:1a(iii) Simulation of cp command
Date:
Aim
To simulate cp command using UNIX system call.
Algorithm
1. Get source and destination filename as command-line argument.
2. Declare a buffer of size 1KB
3. Open the source file in readonly mode using open system call.
4. If file does not exist, then stop.
5. Create the destination file using creat system call.
6. If file cannot be created, then stop.
7. File copy is achieved as follows:
a. Read 1KB data from source file and store onto buffer using read system call.
b. Write the buffer contents onto destination file using write system call.
c. If end-of-file then step 8 else step 7a.
8. Close source and destination file using close system call.
9. Stop.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#define SIZE 1024
main(int argc, char *argv[])
{
int src, dst, nread;
char buf[SIZE];
if (argc != 3)
{
printf("Usage: gcc copy.c -o copy\n");
printf("Usage: ./copy <filename> <newfile> \n");
exit(-1);
}
if ((src = open(argv[1], O_RDONLY)) == -1)
{
perror(argv[1]);
exit(-1);
}
if ((dst = creat(argv[2], 0644)) == -1)
{
perror(argv[1]);
exit(-1);
}
while ((nread = read(src, buf, SIZE)) > 0)
{
if (write(dst, buf, nread) == -1)
{
printf("can't write\n");
exit(-1);
}
}
close(src);
close(dst);
}
Result:
Thus a file is copied using file I/O. The cmp command can be used to verify that contents
of both file are same
Ex.no:1B STUDY OF SHELL PROGRAMMING
Date:
Aim:
To study about the Unix Shell Programming Commands and its usages.
INTRODUCTION:
Shell programming is a group of commands grouped together under single filename. After
logging onto the system a prompt for input appears which is generated by a Command String
Interpreter program called the shell. The shell interprets the input, takes appropriate action, and
finally prompts for more input. Shell scripts are dynamically interpreted, NOT compiled.
SHELL KEYWORDS:
echo, read, if fi, else, case, esac, for , while , do , done, until , set, unset, readonly, shift,
export, break, continue, exit, return, trap , wait, eval ,exec, ulimit , umask.
General things about SHELL:
The shbang line: The "shbang" line is the very first line of the script and lets the kernel know
what shell will be interpreting the lines in the script. The shbang line consists of a #! followed by
the full pathname to the shell, and can be followed by options to control the behavior of the shell.
EXAMPLE
#!/bin/sh
Comments: Comments are descriptive material preceded by a # sign. They are in effect until the
end of a line and can be started anywhere on the line.
EXAMPLE
# this text is not
# interpreted by the shell
Wildcards: There are some characters that are evaluated by the shell in a special way. They are
called shell metacharacters or "wildcards." These characters are neither numbers nor letters. For
example, the *, ?, and [ ] are used for filename expansion. The <, >, 2>, >>, and | symbols are used
for standard I/O redirection and pipes. To prevent these characters from being interpreted by the
shell they must be quoted.
SHELL VARIABLES:Shell variables change during the execution of the program. The C Shell
offers a command "Set" to assign a value to a variable.
For example:
set myname= Fred
set myname = "Fred Bloggs"
set age=20
Local variables: Local variables are in scope for the current shell. When a script ends, they are
no longer available; i.e., they go out of scope. Local variables are set and assigned values.
For example:
variable_name=value
name="John Doe"
x=5
Global variables: Global variables are called environment variables. They are set for the currently
running shell and any process spawned from that shell. They go out of scope when the script ends.
For example:
VARIABLE_NAME=value
export VARIABLE_NAME
PATH=/bin:/usr/bin:.
export PATH
Extracting values from variables: To extract the value from variables, a dollar sign is used.
For example:
echo $variable_name
echo $name
echo $PATH
Rules: -
1. A variable name is any combination of alphabets, digits and an underscore („-„);
2. No commas or blanks are allowed within a variable name.
3. The first character of a variable name must either be an alphabet or an underscore.
4. Variables names should be of any reasonable length.
5. Variables name are case sensitive. That is Name, NAME, name, NAme, are all different
variables.
EXPRESSION Command: To perform all arithmetic operations.
Syntax:
var = „expr $value1 + $ value2‟
Arithmetic: The Bourne shell does not support arithmetic. UNIX/Linux commands must be used
to perform calculations.
EXAMPLE
n=`expr 5 + 5`
echo $n
Operators: The Bourne shell uses the built-in test command operators to test numbers and strings.
EXAMPLE
Equality:
= string
!= string
-eq number
-ne number
Logical:
-a and
-o or
! not
Logical:
AND &&
OR ||
Relational:
-gt greater than
-ge greater than, equal to
-lt less than
-le less than, equal to
Arithmetic:
+, -, \*, /, %
Arguments (positional parameters): Arguments can be passed to a script from the command line.
Positional parameters are used to receive their values from within the script.
For example:
At the command line:
$ scriptname arg1 arg2 arg3 ...
In a script:
echo $1 $2 $3 Positional parameters
echo $* All the positional parameters
echo $# The number of positional parameters
READ Statement:
To get the input from the user.
Syntax :
read x y
(no need of commas between variables)
ECHO Statement:
Similar to the output statement. To print output to the screen, the echo command is used. Wildcards
must be escaped with either a backslash or matching quotes.
Syntax :
Echo “String” (or) echo $ b(for variable).
For example:
echo "What is your name?"
Reading user input: The read command takes a line of input from the user and assigns it to a
variable(s) on the right-hand side. The read command can accept muliple variable names. Each
variable will be assigned a word.
For example:
echo "What is your name?"
read name
read name1 name2 ...
CONDITIONAL STATEMENTS:
The if construct is followed by a command. If an expression is to be tested, it is enclosed
in square brackets. The then keyword is placed after the closing parenthesis. An if must end with
a fi.
1. if This is used to check a condition and if it satisfies the condition if then does the next action ,
if not it goes to the else part.
2. if else
If cp $ source $ target
Then
Echo File copied successfully
Else
Echo Failed to copy the file.
3. nested if
Here sequence of condition is checked and the corresponding operation performed accordingly.
Syntax :
if test condition
then
command
if test condition
then
command
else
command
fi
fi
4. case .. esac
This construct helps in execution of the shell script based on Choice. The case command construct
is:
case variable_name in
pattern1)
statements
;;
pattern2)
statements
;;
pattern3)
;;
*) default value
;;
esac
Example:
case "$color" in
blue)
echo $color is blue
;;
green)
echo $color is green
;;
red|orange)
echo $color is red or orange
;;
*) echo "Not a color" # default
LOOPS
There are three types of loops: while, until and for.
The while loop is followed by a command or an expression enclosed in square brackets, a do
keyword, a block of statements, and terminated with the done keyword. As long as the expression
is true, the body of statements between do and done will be executed.
The until loop is just like the while loop, except the body of the loop will be executed as long as
the expression is false.
The for loop used to iterate through a list of words, processing a word and then shifting it off, to
process the next word. When all words have been shifted from the list, it ends. The for loop is
followed by a variable name, the in keyword, and a list of words then a block of statements, and
terminates with the done keyword.
The loop control commands are break and continue.
Syntax:
(1) while test command
do
block of statements
done
or
$ sh sum.sh
Result:
Thus the Shell commands and their usages.
Ex. no: 1b(i) Program to display student grades
Date:
Aim:
To write a Shell program to display student grades.
Algorithm:
1. Get the name, register number and three subject marks.
2. Find the total.
3. If any one of the mark is less than 50 then print fail. Otherwise print false.
4. Find the total and average.
5. If the average is greater than 80 then print Distinction.
6. If the average is greater than 70 then print First Class.
7. If the average is greater than 60 then print Second Class.
8. If the average is greater than 50 then print Third Class.
Program:
echo "Enter the student name"
read name
echo "Enter the Reg.No"
read no
echo "enter the 3 subject mark"
read m1 m2 m3
total=`expr $m1 + $m2 + $m3`
echo " Mark List"
echo " Student Name : $name"
echo " Reg No : $no"
echo " Subject marks : $m1 $m2 $m3"
echo "Total : $total"
if test $m1 -lt 50 -o $m2 -lt 50 -o $m3 -lt 50
then
echo "Result: Fail"
else
echo "Result: Pass"
avg=`expr $total / 3`
echo "Average:$avg"
if test $avg -gt 80
then
echo "Grade:Distinction"
elif test $avg -gt 70
then
echo "Grade: FIrst Class"
elif test $avg -gt 60
then
echo "Grade: Second Class"
elif test $avg -gt 50
then
echo "Grade: Third Class"
fi
fi
Output:
student@acew:~$ sh pgm1.sh
Enter the student name
jano
Enter the Reg.No
97113104030
enter the 3 subject mark
90 95 92
Mark List
Student Name : jano
Reg No : 97113104030
Subject marks : 90 95 92
Total : 277
Result: Pass
Average:92
Grade:Distinction
student@acew:~$
Result:
Thus the shell program to display student grades has been implemented and verified.
Ex.no :1b(ii) Program to check whether the given year is leap year or not
Date:
Aim:
To write a Shell program to check whether the given year is leap year or not.
Algorithm:
1. Get the year.
2. Check whether it is divisible by 100, if it is true then check if it is divisible by 400. Then
print the year is leap year.
3. Otherwise check whether it is divisible by 4 and if it is true then print the year is leap year.
Program:
echo "Enter the year"
read year
if test `expr $year % 100` -eq 0
then
if test `expr $year % 400` -eq 0
then
echo "$year is a leap year"
else
echo "$year is not a leap year"
fi
elif test `expr $year % 4` -eq 0
then
echo "$year is a leap year"
else
echo "$year is not a leap year"
fi
Output:
student@acew:~$ sh pgm2.sh
Enter the year
2004
2004 is a leap year
Result:
Thus the shell program to check whether the given year is leap year or not has been
implemented and verified.
Ex.no: 1b(iii) Program to print the first ‘N’ prime numbers
Date:
Aim:
To write a Shell program to print the first „N‟ prime numbers
Algorithm:
1. Get the range.
2. Use the while loop and set the loop counter to 2.
3. Repeat the loop until the loop counter reaches the range.
4. Check whether the number is divisible by the same number, if it is true then print the
number.
Program:
echo "Enter range"
read n
j=3
echo "Prime numbers are"
echo 2
while test $j -le $n
do
x=0
i=2
while test $i -lt $j
do
if test `expr $j % $i` -eq 0
then
x=`expr $x + 1`
fi
i=`expr $i + 1`
done
if test $x -eq 0
then
echo "$j "fi
j=`expr $j + 1`
done
Output:
student@acew:~$ sh pgm3.sh
enter a range
15
the prime nos are
2
3
5
7
11
13
Result:
Thus the shell program to print the first „N‟ prime numbers has been implemented and
verified.
Ex.no:1b(iv) Program to print the factorial of first ‘N’ numbers
Date:
Aim:
To write a Shell program to print the factorial of first „N‟ numbers
Algorithm:
1. Get the number
2. Initialize a variable fact to 1.
3. Set a while loop ranges from 1 to the number.
4. Multiply the loop counter with fact and store it again in fact.
5. Print the result.
Program:
fact=1
echo -n "Enter number to find factorial : "
read n
i=1
while test $i -le $n
do
fact=`expr $fact \* $i`
echo "factorial of $i is $fact"
i=`expr $i + 1`
done
Output:
student@acew:~$ sh pgm4.sh
Enter number to find factorial : 5
factorial of 1 is 1
factorial of 2 is 2
factorial of 3 is 6
factorial of 4 is 24
factorial of 5 is 120
student@sxcce:~$
Result:
Thus the shell program to print the factorial of first „N‟ numbers has been implemented
and verified.
Ex.no: 1b(v) Program to find the roots of a quadratic equation
Date:
Aim:
To write a Shell program to find the roots of a quadratic equation
Algorithm:
1. Get three numbers.
2. Find the roots of quadratic equation using formulas.
3. Print the values of the roots.
Program:
echo "Enter a value: "
read a
echo "Enter a value: "
read b
echo "Enter a value: "
read c
d=`expr $b \* $b - 4 \* $a \* $c`
x1=`echo "scale=3; (-$b + sqrt($d)) / (2 * $a)" | bc`
x2=`echo "scale=3; (-$b - sqrt($d)) / (2 * $a)" | bc`
echo "Root 1 : $x1"
echo "Root 2 : $x2"
Output:
student@acew:~$ sh pgm5.sh
Enter a value:
1
Enter a value:
3
Enter a value:
1
Root 1 : -.382
Root 2 : -2.618
student@acew:~$
Result:
Thus the shell program to find the roots of a quadratic equation has been implemented
and verified.
Ex.no: 1b(vi) Program to find the smallest number from a set of numbers
Date:
Aim:
To write a Shell program to find the smallest number from a set of numbers.
Algorithm:
1. Read the elements in to an array.
2. Compare the adjacent elements. If it is greater than next one, then interchange it.
3. Print the first element of the array
Program:
echo "enter a number"
read n
echo "enter nos one by one"
for((i=1;i<=n;i++))
do
read a[$i]
done
for((i=1;i<=n;i++))
do
for((j=`expr $i + 1`;j<=n;j++))
do
if [ ${a[$i]} -gt ${a[$j]} ]
then
t=${a[$i]}
a[$i]=${a[$j]}
a[$j]=$t
fi
done
done
echo "The smallest number is"
echo "${a[1]}"
Output:
student@acew:~$ chmod +x sor.sh
student@acew:~$ ./sor.sh
enter a number
3
enter nos one by one
5
2
7
The smallest number is
2
student@sxcce:~$
Result:
Thus the shell program to find the smallest number from a set of numbers has been
implemented and verified.
Ex.no: 1b(vii) Program to sort numbers using arrays
Date:
Aim:
To write a Shell program to sort numbers using arrays
Algorithm:
1. Read the elements in to an array.
2. Compare the adjacent elements. If it is greater than next one, then interchange it.
3. Print all the element of the array
Program:
echo "enter a number"
read n
echo "enter nos one by one"
for((i=1;i<=n;i++))
do
read a[$i]
done
for((i=1;i<=n;i++))
do
for((j=`expr $i + 1`;j<=n;j++))
do
if test ${a[$i]} -gt ${a[$j]}
then
t=${a[$i]}
a[$i]=${a[$j]}
a[$j]=$t
fi
done
done
echo "The sorted numbers are"
for((i=1;i<=n;i++))
do
echo "${a[$i]}"
done
Output:
student@sxcce:~$ chmod +x sorting.sh
student@sxcce:~$ ./sorting.sh
enter a number
5
enter nos one by one
45
67
23
12
89
The sorted numbers are
12
23
45
67
89
Result:
Thus the shell program to sort numbers using arrays has been implemented and verified
.
Ex.no: 1b(viii) Program using strings
Date:
Aim:
To write a Shell program using strings.
Algorithm:
1. Get two strings.
2. Concatenate the strings and print it.
3. Change the case and print it.
4. Find the length of the string and print it.
Program:
echo enter first string
read st1
echo enter second string
read st2
st=$st1$st2
echo concatenated string is $st
t=`echo $st|tr [a-z] [A-Z]`
echo The changed case string is $t
len=`expr $st|wc -c`
len1=`expr $len - 1`
echo "length of the string is $len1"
Output:
studentacew:~$ sh pgm8.sh
enter first string
operating
enter second string
system
concatenated string is operatingsystem
The changed case string is OPERATINGSYSTEM
length of the string is 15
student@acew:~$
Result:
Thus the shell program using strings has been implemented and verified.
Ex.No 3 PROCESS MANAGEMENT USING SYSTEM CALLS
Ex.no: 3a Program using system call fork()
Date:
Aim : To write the program to create a Child Process using system call fork().
Algorithm :
1. Declare the variable pid.
2. Get the pid value using system call fork().
3. If pid value is less than zero then print as “Fork failed”.
4. Else if pid value is equal to zero include the new process in the system‟s
Fil. using execlp system call.
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()
6. Then print “Child complete”.
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)
{
}
else{
execlp("whoami","ls",NULL);exit(0);
Output:
[cse6@localhost Pgm]$ cc prog4a.c
Result:
Thus the program was executed and verified successfully
Ex.no : 2b Program using system calls getpid() & getppid()
Date:
Aim :
To write the program to implement the system calls getpid() and getppid().
Algorithm :
1. Declare the variables pid , parent pid , child id and grand chil id.
2 .Get the child id value using system call fork().
3.If child id value is less than zero then print as “error at fork() child”.
4 .If child id !=0 then using getpid() system call get the process id.
5. Print “I am parent” and print the process id.
6 .Get the grand child id value using system call fork().
7 .If the grand child id value is less than zero then print as “error at fork() grand
child”.
8. If the grand child id !=0 then using getpid system call get the process id.
9 .Assign the value of pid to my pid.
10 .Print “I am child” and print the value of my pid.
11 .Get my parent pid value using system call getppid().
12. Print “My parent‟s process id” and its value.
13. Else print “I am the grand child”.
14 .Get the grand child‟s process id using getpid() and print it as “my process id”.
15. Get the grand child‟s parent process id using getppid() and print it as “my parent‟s
process id
return(0);
}
Output:
Child process is under execution
Process id of the child process is 9314
Process id of the parent process is 9313 Parent
process is under execution
Process id of the parent process is 9313
Process id of the child process in parent is 9314 Process
id of the parent of parent is 2825
Result:
Thus the program was executed and verified successfully
Ex.no: 2c. Program using system calls opendir( ) readdir( ) closedir()
Date:
Aim :
To write the program to implement the system calls opendir( ), readdir( ).
Algorithm :
Result:
Thus the program was executed and verified successfully
Ex.no:2d Program using system call exec( )
Date:
Aim :
To write the program to implement the system call exec( ).
Algorithm :
1 : Include the necessary header files.
2 : Print execution of exec system call for the date Unix command.
3 : Execute the execlp function using the appropriate syntax for the Unix
command date.
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”);
printf(“displaying the date”);
execlp( “/bin/date”, “date”, 0);
}
Output:
Sat Dec 14 02 : 57 : 38 IST 2010
Result:
Thus the program was executed and verified successfully
Ex.no:2e Program using system calls wait( ) & exit( )
Date:
Aim :
To write the program to implement the system calls wait( ) and exit( ).
Algorithm :
1 : Declare the variables pid and i as integers.
2 : Get the child id value using the system call fork().
3 : If child id value is less than zero then print “fork failed”.
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.
5 : Else perform Step 8.
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”.
8 : Execute the system call wait( ) to make the parent to wait for the child
process to get over.
9 : Once the child processes are terminated , the parent terminates and hence
print “Parent process ends”.
10 : After both the parent and the chid processes get terminated it execute the
wait( ) system call to permanently get deleted from the OS.
Result:
Thus the program was executed and verified successfully
Ex.no: 2f Program using system call stat( ) and close()
Date:
Aim:
To write the program to implement the system call stat( ) and close().
Algorithm :
1 : Include the necessary header files to execute the system call stat( ).
2 : Create a stat structure thebuf. Similarly get the pointers for the two structures
passwd and group.
3 : Declare an array named path[20] of character type to get the input file along
with its extension and an integer i.
4 : Get the input file along with its extension.
5 : If not of stat of a particular file then do the Steps 6 to 18.
6 : Print the file‟s pathname as file‟s name along with its extension.
7 : To check the type of the file whether it is a regular file or a directory use
S_ISREG( ).
8 : If the above function returns true value the file is an regular file else it is
directory.
9 : Display the file mode in octal representation using thebuf.st_mode.
10 : Display the device id in integer representation using thebuf.st_dev.
11 : Display the user id in integer representation using thebuf.st_uid.
12 : Display the user‟s pathname.
13 : Display the group id in integer representation using thebuf.st_gid.
14 : Display the group‟s pathname.
15 : Display the size of the file in integer representation using thebuf.st_size.
16 : Display the last access in time and date format using
ctime(&thebuf.st_atime).
17 : Display the last modification in time and date format using
ctime(&thebuf.st_atime).
18 : Display the last status in time and date format using
ctime(&thebuf.st_atime).
19 : If Step 5 fails then print “Cannot get the status details for the given file”.
Program:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
main()
{int fd1,fd2,n;
char source[30],ch[5];
struct stat s,t,w;
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=%d\n",s.st_size);
fstat(fd1,&t);
printf("Destination file size =%d\n",t.st_size);
close(fd1);
}
Result:
Thus the program was executed successfully.
Ex.no: :2g Program using system calls open( ), read() & write( )
Date:
Aim :
Bo write the program to implement the system calls open( ),read( ) and write( ).
Algorithm :
1 : Declare the structure elements.
2 : Create a temporary file named temp1.
3 : Open the file named “test” in a write mode.
4 : Enter the strings for the file.
5 : Write those strings in the file named “test”.
6 : Create a temporary file named temp2.
7 : Open the file named “test” in a read mode.
8 : Read those strings present in the file “test” and save it in temp2.
9 : Print the strings which are read.
Program:
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
main( )
{
int fd[2];
char buf1[25]= ”just a test\n”; char
buf2[50];
fd[0]=open(“file1”, O_RDWR);
fd[1]=open(“file2”, O_RDWR);
write(fd[0], buf1, strlen(buf1));
printf(“\n Enter the text now….”);
gets(buf1);
write(fd[0], buf1, strlen(buf1));
lseek(fd[0], SEEK_SET, 0);
read(fd[0], buf2, sizeof(buf1));
write(fd[1], buf2, sizeof(buf2));
close(fd[0]);
close(fd[1]);
printf(“\n”);return0;
}
Output:
Enter the text now….progress
Cat file1 Just a
test progress
Cat file2 Just a test progress
Result:
Thus the program was executed successfully
Ex.No: 3 CPU SCHEDULING ALGORITHMS
Ex.no: 3a Simulation of First Come First Serve Scheduling Algorithm(FCFS)
Date:
Aim:
To write a c program to simulate the First Come First Serve Scheduling Algorithm.
Algorithm:
1. Get the number of processes.
2. Get the process name, CPU burst time (execution time) and its corresponding arrival time.
3. Print the Gantt chart with respect to its arrival time.
4. Calculate the waiting time and turn-around time for each of the process.
5. Print the average waiting time and average turn-around time.
Program:
#include<stdio.h>
#include<string.h>
main()
{
int n,Bu[20],Twt=0,Ttt=0,A[10],Wt[10],w,ch,i,j,temp,temp1;
float Awt,Att;
char pname[20][20],c[20][20];
printf("\n Enter the number of processes: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\n\n Enter the process name: ");
scanf("%s",pname[i]);
printf("\n BurstTime for %s",pname[i]);
scanf("%d",&Bu[i]);
printf("\n Arrival Time for %s = ",pname[i]);
scanf("%d",&A[i]);
}
printf("\n\n FIRST COME FIRST SERVED ALGORITHM\n\n");
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(A[i]>A[j])
{
temp=Bu[i];
temp1=A[i];
Bu[i]=Bu[j];
A[i]=A[j];
Bu[j]=temp;
A[j]=temp1;
strcpy(c[i],pname[i]);
strcpy(pname[i],pname[j]);
strcpy(pname[j],c[i]);
}
}
}
Wt[1]=0;
for(i=2;i<=n;i++)
{
Wt[i]=Bu[i-1]+Wt[i-1];
}
for(i=1;i<=n;i++)
{
Twt=Twt+(Wt[i]-A[i]);
Ttt=Ttt+((Wt[i]+Bu[i])-A[i]);
}
Att=(float)Ttt/n;
Awt=(float)Twt/n;
printf("\n\n Average Turn around time=%3.2f ms ",Att);
printf("\n\n AverageWaiting Time=%3.2f ms",Awt);
printf("\n\n\t\t\tGANTT CHART\n");
for(i=1;i<=n;i++)
printf("|\t%s\t",pname[i]);
printf("|\t\n");
printf("\n");
for(i=1;i<=n;i++)
printf("%d\t\t",Wt[i]);
printf("%d",Wt[n]+Bu[n]);
printf("\n");
}
Output:
Enter the number of processes: 3
Enter the process name: a
BurstTime for a24
Arrival Time for a = 0
Enter the process name: b
BurstTime for b3
Arrival Time for b = 0
Enter the process name: c
BurstTime for c3
Arrival Time for c = 0
GANTT CHART
|a | b | c |
0 24 27 30
student@acew:~$
Result:
Thus the C program to simulate First Come First Serve Scheduling Algorithm has been
implemented and verified.
Ex.no: 3b Simulation of Shortest Job First Scheduling Algorithm(SJF)
Date:
Aim:
To write a c program to simulate the Shortest Job First Scheduling Algorithm.
Algorithm:
1. Get the number of processes.
2. Get the process name, CPU burst time (execution time) and its corresponding arrival time.
3. Print the Gantt chart with respect to its arrival time & shortest execution time also.
4. Calculate the waiting time and turn-around time for each of the process.
5. Print the average waiting time and average turn-around time.
Program:
#include<stdio.h>
#include<string.h>
main()
{
int n,Bu[20],Twt=0,Ttt=0,A[10],Wt[10],w,ch,i,j,temp,temp1;
float Awt,Att;
char pname[20][20],c[20][20];
printf("\n Enter the number of processes: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("\n\n Enter the process name: ");
scanf("%s",pname[i]);
printf("\n BurstTime for %s",pname[i]);
scanf("%d",&Bu[i]);
}
printf("\n\n SHORTEST JOB FIRST SCHEDULING ALGORITHM\n\n");
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(Bu[i]>Bu[j])
{
temp=Bu[i];
Bu[i]=Bu[j];
Bu[j]=temp;
strcpy(c[i],pname[i]);
strcpy(pname[i],pname[j]);
strcpy(pname[j],c[i]);
}
}
}
for(i=1;i<=n;i++)
{
A[i]=0;
}
Wt[1]=0;
for(i=2;i<=n;i++)
{
Wt[i]=Bu[i-1]+Wt[i-1];
}
for(i=1;i<=n;i++)
{
Twt=Twt+(Wt[i]-A[i]);
Ttt=Ttt+((Wt[i]+Bu[i])-A[i]);
}
Att=(float)Ttt/n;
Awt=(float)Twt/n;
printf("\n\n Average Turn around time=%3.2f ms ",Att);
printf("\n\n AverageWaiting Time=%3.2f ms",Awt);
printf("\n\n\t\t\tGANTT CHART\n");
for(i=1;i<=n;i++)
printf("|\t%s\t",pname[i]);
printf("|\t\n");
printf("\n");
for(i=1;i<=n;i++)
printf("%d\t\t",Wt[i]);
printf("%d",Wt[n]+Bu[n]);
printf("\n \n");
printf("\n");
}
Output:
student@acew:~$ ./a.out
Enter the number of processes: 3
Enter the process name: a
BurstTime for a 7
Enter the process name: b
BurstTime for b 4
Enter the process name: c
BurstTime for c 10
SHORTEST JOB FIRST SCHEDULING ALGORITHM
Average Turn around time=12.00 ms
AverageWaiting Time=5.00 ms
GANTT CHART
|b | a | c |
0 4 11 21
Result:
Thus the C program to simulate Shortest Job First Scheduling Algorithm has been
implemented and verified.
Ex.no: 3c Simulation of Priority Scheduling Algorithm
Date:
Aim:
To write a c program to simulate the Priority Scheduling Algorithm.
Algorithm:
1. Get the number of processes.
2. Get the process name, CPU burst time (execution time) and its corresponding priority.
3. Print the Gantt chart with respect to its priority given by the user.
4. Calculate the waiting time and turn-around time for each of the process.
5. Print the average waiting time and average turn-around time.
Program:
#include<stdio.h>
#include<string.h>
void main()
{
int n,Bu[20],Twt=0,Ttt=0,A[10],Wt[10],w,ch,i,j,temp,temp1,P[10];
float Awt,Att;
char pname[20][20],c[20][20];
Twt=Twt+(Wt[i]-A[i]);
Ttt=Ttt+((Wt[i]+Bu[i])-A[i]);
}
Att=(float)Ttt/n;
Awt=(float)Twt/n;
printf("\n\n Average Turn around time=%3.2f ms ",Att);
printf("\n\n AverageWaiting Time=%3.2f ms",Awt);
printf("\n\n\t\t\tGANTT CHART\n");
for(i=1;i<=n;i++)
printf("|\t%s\t",pname[i]);
printf("|\t\n");
printf("\n");
for(i=1;i<=n;i++)
printf("%d\t\t",Wt[i]);
printf("%d",Wt[n]+Bu[n]);
printf("\n");
}
Output:
Enter the number of processes: 3
Enter the process name: a
BurstTime for a 6
Enter the priority 2
Enter the process name: b
BurstTime for b 7
Enter the priority 6
Enter the process name: c
BurstTime for c 3
Enter the priority 1
PRIORITY SCHEDULING ALGORITHM
Average Turn around time=9.33 ms
AverageWaiting Time=4.00 ms
GANTT CHART
|c | a | b |
0 3 9 16
Result:
Thus the C program to simulate Priority Scheduling Algorithm has been implemented and
verified.
Ex. no: 3d Simulation of Round Robin Scheduling Algorithm
Date:
Aim:
To write a c program to simulate the Round Robin Scheduling Algorithm.
Procedure:
1. Get the number of processes.
2. Get the process name; CPU burst time (execution time), arrival time and time slice
(quantum).
3. Print the Gantt chart as per the Round Robin Scheduling algorithm [i.e. processes are
dispatched FIFO but are given a limited amount of CPU time called a time slice or a
quantum. If a process does not complete before its CPU time expires, the CPU is preempted
and given o the next waiting process. The preempted process is then placed at the back of
the ready queue] i.e. with respect to its arrival time & time slice.
4. Calculate the waiting time and turn-around time for each of the process.
5. Print the average waiting time and average turn-around time.
Program:
#include<string.h>
#include<stdio.h>
void main()
{
struct rrsa
{
char name[10];
int st,pt;
}r[15];
int n,Bu[20],Twt=0,Ttt=0,A[10],Wt[20],rt[20],temp,temp1,size=0;
int z,q,i,j,s,k=0,t,t1,tt[20];
float Awt,Att;
char pname[20][20],c[20][20];
for(i=0;i<n;i++)
{
strcpy(r[i].name," ");
r[i].st=0;
r[i].pt=0;
}
printf("\n Enter the number of processes: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\n Enter the process name: ");
scanf("%s",pname[i]);
printf("\n BurstTime for %s",pname[i]);
scanf("%d",&Bu[i]);
printf("Enter Arrival time ");
scanf("%d",&A[i]);
}
printf("Enter the time slice ");
scanf("%d",&q);
printf("\n\n R R SCHEDULING ALGORITHM\n\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(A[i]<A[j])
{
temp=Bu[i];
temp1=A[i];
Bu[i]=Bu[j];
A[i]=A[j];
Bu[j]=temp;
A[j]=temp1;
strcpy(c[i],pname[i]);
strcpy(pname[i],pname[j]);
strcpy(pname[j],c[i]);
}
}
}
k=0;
for(i=0;i<n;i++)
{
rt[i]=Bu[i];
Wt[i]=0;
}
r[0].st=A[0];
label1:
for(j=0;j<n;j++)
{
if((rt[j]<=q)&&(rt[j]!=0))
{
if(r[k].st>=A[j])
{
strcpy(r[k].name,pname[j]);
r[k].pt=r[k].st+rt[j];
r[k+1].st=r[k].pt;
rt[j]=0;
k++;
size++;
}
}
else if((rt[j]>q)&&(rt[j]!=0))
{
if(r[k].st>=A[j])
{
strcpy(r[k].name,pname[j]);
r[k].pt=r[k].st+q;
r[k+1].st=r[k].pt;
rt[j]=rt[j]-q;
k++;
size++;
}
}
}
for(i=1;i<n;i++)
{
if(rt[i-0]!=0)
{
goto label1;
}
}
for(i=0;i<n;i++)
{
s=i;
label2:
if(strcmp(pname[i],r[s].name)==0)
{
t=s;
goto label3;
}
else
{
s++;
t=s;
goto label2;
}
label3:
k=s+1;
for(;k<size;k++)
{
if(strcmp(r[s].name,r[k].name)==0)
{
t1=r[k].st-r[s].pt;
Wt[i]+=t1;
s=k;
}
}
Wt[i]=Wt[i]+r[t].st-A[i];
tt[i]=Bu[i]+Wt[i];
Twt=Twt+Wt[i];
Ttt=Ttt+tt[i];
}
Awt=(float)Twt/n;
Att=(float)Ttt/n;
printf("Gantt chart\n\n");
for(i=0;i<size;i++)
{
printf("%d\t%s\t%d\n\n",r[i].st,r[i].name,r[i].pt);
}
printf("\n\nAvg. wt time :%f\n",Awt);
printf("Avg. T Time:%f\n",Att);
}
Output
Enter the number of processes: 3
Enter the process name: a
BurstTime for a 4
Enter Arrival time 2
Enter the process name: b
BurstTime for b 6
Enter Arrival time 0
Enter the process name: c
BurstTime for c 9
Enter Arrival time 3
Enter the time slice 5
R R SCHEDULING ALGORITHM
Gantt chart
0 b 5
5 a 9
9 c 14
14 b 15
15 c 19
Avg. wt time: 6.333333
Avg. T Time: 12.666667
student@acew:~$
Result:
Thus the C program to simulate Round Robin Scheduling Algorithm has been implemented
and verified.
Ex.no: 4 INTERPROCESS COMMUNICATION
Ex.no:4a Shared Memory
Aim:
To demonstrate communication between process using shared memory.
Algorithm:
Server
1. Initialize size of shared memory shmsize to 27.
2. Initialize key to 2013 (some random value).
3. Create a shared memory segment using shmget with key & IPC_CREAT as parameter.
a. If shared memory identifier shmid is -1, then stop.
4. Display shmid.
5. Attach server process to the shared memory using shmmat with shmid as parameter.
a. If pointer to the shared memory is not obtained, then stop.
6. Clear contents of the shared region using memset function.
7. Write a–z onto the shared memory.
8. Wait till client reads the shared memory contents
9. Detatch process from the shared memory using shmdt system call.
10. Remove shared memory from the system using shmctl with IPC_RMID argument
Client
1. Initialize size of shared memory shmsize to 27.
2. Initialize key to 2013 (same value as in server).
3. Obtain access to the same shared memory segment using same key.
a. If obtained then display the shmid else print "Server not started"
4. Attach client process to the shared memory using shmmat with shmid as parameter.
a. If pointer to the shared memory is not obtained, then stop.
5. Read contents of shared memory and print it.
6. After reading, modify the first character of shared memory to '*'
Program
Server: /* Shared memory server - shms.c */
#include <stdio.h>
#include <stdlib.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define shmsize 27
main()
{
char c;
int shmid;
key_t key = 2013;
char *shm, *s;
if ((shmid = shmget(key, shmsize, IPC_CREAT|0666)) < 0)
{
perror("shmget");
exit(1);
}
printf("Shared memory id : %d\n", shmid);
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
perror("shmat");
exit(1);
}
memset(shm, 0, shmsize);
s = shm;
printf("Writing (a-z) onto shared memory\n");
for (c = 'a'; c <= 'z'; c++)
*s++ = c;
*s = '\0';
while (*shm != '*');
printf("Client finished reading\n");
if(shmdt(shm) != 0)
fprintf(stderr, "Could not close memory segment.\n");
shmctl(shmid, IPC_RMID, 0);
}
Client:/* Shared memory client - shmc.c */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define shmsize 27
main()
{
int shmid;
key_t key = 2013;
char *shm, *s;
if ((shmid = shmget(key, shmsize, 0666)) < 0)
{
printf("Server not started\n");
exit(1);
}
else
printf("Accessing shared memory id : %d\n",shmid);
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
{
perror("shmat");
exit(1);
}
printf("Shared memory contents:\n");
for (s = shm; *s != '\0'; s++)
putchar(*s);
putchar('\n');
*shm = '*';
}
Output:-
Server
$ gcc shms.c -o shms
$ ./shms
Shared memory id : 196611
Writing (a-z) onto shared memory
Client finished reading
Client
$ gcc shmc.c -o shmc
$ ./shmc
Accessing shared memory id : 196611
Shared memory contents:
abcdefghijklmnopqrstuvwxyz
Result
Thus contents written onto shared memory by the server process is read by the client
process.
Exp: 4b Fibonacci & Prime Number
Date:
Aim:
To write a C program to implement Inter Process Communication using pipes.
Algorithm:
1. Create a pipe using pipe()system call and check for error condition.
2. Create a child using fork system call and check for error condition.
3. If the return value is not zero, then display it as “Parent Process” and get the limit from
the user. While getting the inputs, write each data into pipe1 by closing its read end and
after completion, close the write end of pipe1.
4. If the return value is zero, read data from pipe0 by closing its write end and then display
it as “Child Process” by printing the Fibonacci series and close the read end of pipe0.
5. Terminate the program.
Program:
#include<stdio.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/uio.h>
#include<sys/types.h>
#include<stdlib.h>
main()
{
int pid,pfd[2],n,a,b,c;
if(pipe(pfd)==-1)
{
printf("Error in pipe connection\n");
exit(1);
}
pid=fork();
if(pid>0)
{
printf("\n\nParent process");
printf("\nFibonacci series");
printf("\nEnter the limit for the series:");
scanf("%d",&n);
close(pfd[0]);
write(pfd[1],&n,sizeof(n));
close(pfd[1]);
exit(0);
}
else
{
close(pfd[1]);
read(pfd[0],&n,sizeof(n));
printf("\nchild process");
a=0;
b=1;
close(pfd[0]);
printf("\nFibonacci Series is:");
printf("\n\n%d\n%d\n",a,b);
while(n>2)
{
c=a+b;
printf("%d\n",c);
a=b;
b=c;
n--;
}
}
}
Output:
student@acew:~$ ./a.out
Parent process
Fibonacci series
Enter the limit for the series:5
child process
Fibonacci Series is:
0
1
1
2
3
student@acew:~$
Result:
Thus the C program to implement Inter Process Communication using pipes has been
implemented and verified.
Ex.no: 5 MUTUAL EXCLUSION BY SEMAPHORE
Aim:
To write a C program to implement the Producer & consumer Problem
(Semaphore)
Algorithm:
1: The Semaphore mutex, full & empty are initialized.
2: In the case of producer process
i) Produce an item in to temporary variable.
ii) If there is empty space in the buffer check the mutex value for enter into the
critical section.
iii) If the mutex value is 0, allow the producer to add value in the temporary
variable to the buffer.
3: In the case of consumer process
i) It should wait if the buffer is empty
ii) If there is any item in the buffer check for mutex value, if the mutex==0,
remove item from buffer
iii) Signal the mutex value and reduce the empty value by 1.
iv) Consume the item.
4: Print the result
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);
printf("\n 1.producer\n2.consumer\n3.exit\n");
while(1)
{
printf(" \nenter ur choice");
scanf("%d",&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer();
else
printf("buffer is full\n");
break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else
printf("buffer is empty");
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s)
{
return(--s);
}
int signal(int s)
{
return (++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
Result:
Thus the program was executed successfully
Ex.no: 6 IMPLEMENTATION OF BANKERS ALGORITHM FOR
DEAD LOCK AVOIDANCE
Date:
Aim:
To write a C program to implement Bankers algorithm for deadlock avoidance.
Algorithm:
1. Get total number of processes.
2. Get total number of resources of each resource type.
3. Get the maximum need of each process.
4. Enter allocation matrix.
5. Get the available resources of each resource type.
6. Find out the order in which we can complete the execution of processes with the
available resources.
7. If all the processes can complete with the available resources then display the safe
sequence.
8. Otherwise display deadlock occurs.
Program:
#include<stdio.h>
struct da
{
int max[10],a1[10],need[10],before[10],after[10];
}p[10];
main()
{
int i,j,k,l,r,n,tot[10],av[10],cn=0,cz=0,temp=0,c=0;
printf("\nEnter the no.of processes ");
scanf("%d",&n);
printf("\nEnter 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++)
{
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("\nResource Max Allocated \t 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\nResource Avail Before 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)
{
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("\nP%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("\nDeadlock occured");
}
Output:
student@acew:~$ ./a.out
Enter the no.of processes 5
Enter the no.of resources 3
Process1
Program:
#include<stdio.h>
#include<stdlib.h>
main()
{
int found,flag,l,p[4][5],tp,c[4][5],i,j,k=1,m[5],r[5],a[5],temp[5],sum=0;
printf("Enter total no of processes");
scanf("%d",&tp);
printf("Enter claim matrix");
for(i=1;i<=4;i++)
{
for(j=1;j<=5;j++)
{
scanf("%d",&c[i][j]);
}
}
printf("Enter allocation matrix");
for(i=1;i<=4;i++)
for(j=1;j<=5;j++)
{
scanf("%d",&p[i][j]);
}
printf("Enter resource vector:\n");
for(i=1;i<=5;i++)
{
scanf("%d",&r[i]);
}
printf("Enter availability vector:\n");
for(i=1;i<=5;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}
for(i=1;i<=4;i++)
{
sum=0;
for(j=1;j<=5;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
k++;
}
}
for(i=1;i<=4;i++)
{
for(l=1;l<k;l++)
if(i!=m[l])
{
flag=1;
for(j=1;j<=5;j++)
if(c[i][j]>temp[j])
{ flag=0;break;
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=1;j<=5;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are:");
for(j=1;j<=tp;j++)
{
found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0)
printf("%d\t",j);
}
Output:
Enter total no of processes4
Enter claim matrix
01001
00101
00001
10101
Enter allocation matrix1 0 1 1 0
11000
00010
00000
Enter resource vector:
21121
Enter availability vector:
00001
deadlock causing processes are:1 2
Result:
Thus the C program to implement deadlock detection algorithm has been
implemented and verified.
Ex.no:8 MULTITHREADING
Date:
Aim:
To write a C program to implement Multithreading.
Algorithm:
1. Declare two objects.
2. Create two threads from pthread library.
3. Call the functions simultaneously using thread.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* fun()
{
printf("\nThe thread 1 is running");
}
void* van()
{
printf("\nthread 2 is running ");
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1,NULL,fun,NULL);
pthread_create(&t2,NULL,van,NULL);
printf("\nI'm in main\n");
pthread_join(t2,NULL);
}
Output:
student@acew:~$ cc mul.c -lpthread
student@acew:~$ ./a.out
I'm in main
thread 2 is running
The thread 1 is running
student@acew:~$
Result:
Thus the C program to implement Multithreading Technique has been implemented and
verified.
Ex. no: 9 PAGING
Date:
Aim: To implement the Memory management policy- Paging.
Algorithm:
1. Read all the necessary input from the keyboard.
2. Pages - Logical memory is broken into fixed - sized blocks. 3: Frames – Physical
memory is broken into fixed – sized blocks.
3.Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
5.Display the physical address. 6: Stop the process.
Program:
#include <stdio.h>
#include <conio.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;
}
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;
}
}
getch();
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);
0 5 1
1 6 1
2 7 1
3 2 1
FRAME TABLE
FrameAddress PageNo
0 32555
1 32555
2 3
3 32555
4 32555
5 0
6 1
7 2
Process to create the Physical Address
Enter the Base Address: 1000
Enter theLogical Address: 3
The Physical Address where the instruction present: 1013
Result:
Thus the C program for Paging technique is Implemented.
Ex.no:10 IMPLEMENTATION OF CONTIGUOUS MEMORY ALLOCATION
TECHNIQUE
Date:
Aim:
To write a C program to implement Contiguous memory allocation Technique.
Algorithm:
1. Get the number of processes & its corresponding size.
2. Get the number of segment frames & its corresponding size.
3. Select the allocation strategy to place an incoming segment in primary storage, among the
following
a. Best Fit
b. Worst Fit
c. First Fit
4. First Fit strategy – An incoming process is placed in the main storage in the first available
segment large enough to hold it i.e. scan the primary memory from the beginning and
chooses the first available segment that is large enough.
5. Best Fit strategy – An incoming process is placed in the segment in main storage in which
it fits most tightly and leaves the smallest amount of unused space i.e. this strategy chooses
the segment that is closest in size to the request i.e. the unused space is minimum.
6. Worst Fit strategy – An incoming process is placed in the largest possible segment in the
main storage i.e. the unused space is maximum.
7. Find the efficient placement strategy.
Program:
#include<stdio.h>
main()
{
int p,s,i,n,j,unf=0,usedf=0,usedw=0,usedb=0,unb=0;
int unw=0,total=0,t;
struct segment
{
int size,pos,flag,flag2,flag3;
}seg[20];
struct process
{
int size,flag;
}proc[20];
printf("Enter the no. of process : ");
scanf("%d",&p);
printf("\nEnter the process size : ");
for(i=0;i<p;i++)
{
scanf("%d",&proc[i].size);
proc[i].flag=0;
}
printf("Enter the no.of partitions :");
scanf("%d",&s);
printf("Enter the partition size :");
for(i=0;i<s;i++)
{
scanf("%d",&seg[i].size);
seg[i].pos=i;
seg[i].flag=seg[i].flag2=seg[i].flag3=0;
total=total+seg[i].size;
}
printf("\nFIRST FIT ALLOCATION STRATEGY\n");
printf("process-id\tprocess size\tpartition no.\tpartition size\n");
for(i=0;i<p;i++)
{
proc[i].flag=0;
for(j=0;j<s;j++)
{
if((proc[i].size<=seg[j].size)&&(seg[j].flag==0))
{
seg[j].flag=1;
proc[i].flag=1;
usedf=usedf+proc[i].size;
printf("\n%d\t\t%d\t\t%d\t\t\t%d\t",i,proc[i].size,seg[j].pos,seg[j].size);
break;
}
}
}
for(i=0;i<p;i++)
{
if(proc[i].flag==0)
{
printf("\nprocess %d cannot be stored in any partitions.\n",i);
}
}
unf=total-usedf;
printf("\nUnused space after first fit allocation =%d",unf);
printf("\nBEST FIT ALLOCATION STRATEGY\n");
for(i=0;i<s;i++)
{
for(j=i+1;j<s;j++)
{
if(seg[i].size>=seg[j].size)
{
t=seg[i].size;
seg[i].size=seg[j].size;
seg[j].size=t;
t=seg[i].pos;
seg[i].pos=seg[j].pos;
seg[j].pos=t;
}
}}
printf("process-id\tprocess size\tpartition number\tpartition size\n");
for(i=0;i<p;i++)
{
proc[i].flag=0;
for(j=0;j<s;j++)
{
if((proc[i].size<=seg[j].size)&&(seg[j].flag2==0))
{
seg[j].flag2=1;
proc[i].flag=1;
usedb=usedb+proc[i].size;
printf("\n%d\t\t%d\t\t%d\t\t\t%d\t",i,proc[i].size,seg[j].pos,seg[j].size);
break;
}
}
}
for(i=0;i<p;i++)
{
if(proc[i].flag==0)
{
printf("\nprocess %d cannot be stored in any partitions.\n",i);
}
}
unb=total-usedb;
printf("\nUnused space after best fit allocation =%d",unb);
printf("\nWORST FIT ALLOCATION STRATEGY\n");
for(i=0;i<s;i++)
{
for(j=i+1;j<s;j++)
{
if(seg[i].size<=seg[j].size)
{
t=seg[i].size;
seg[i].size=seg[j].size;
seg[j].size=t;
t=seg[i].pos;
seg[i].pos=seg[j].pos;
seg[j].pos=t;
}
}
}
printf("process-id\tprocess size\tpartition number\tpartition size\n");
for(i=0;i<p;i++)
{
proc[i].flag=0;
for(j=0;j<s;j++)
{
if((proc[i].size<=seg[j].size)&&(seg[j].flag3==0))
{
seg[j].flag3=1;
proc[i].flag=1;
usedw=usedw+proc[i].size;
printf("\n%d\t\t%d\t\t%d\t\t\t%d\t",i,proc[i].size,seg[j].pos,seg[j].size);
break;
}
}
}
for(i=0;i<p;i++)
{
if(proc[i].flag==0)
{
printf("\nprocess %d cannot be stored in any partitions.\n",i);
}
}
unw=total-usedw;
printf("\nUnused space after worst fit allocation =%d",unw);
printf("\nEfficient algorithm among the three strategies...\n");
if((unf<=unb)&&(unb<=unw))
printf("\nFirst fit algorithm is efficient\n");
if((unb<=unw)&&(unb<=unf))
printf("\nBest fit algorithm is efficient\n");
if((unw<=unf)&&(unw<=unb))
printf("\nworst fit algorithm is efficient\n");
Output:
student@acew:~$ ./a.out
Enter the no. of process : 4
Enter the process size : 212 417 112 426
Enter the no.of partitions :5
Enter the partition size :100 500 200 300 600
FIRST FIT ALLOCATION STRATEGY
process-id process size partition no. partition size
0 212 1 500
1 417 4 600
2 112 2 200
process 3 cannot be stored in any partitions.
Unused space after first fit allocation =959
BEST FIT ALLOCATION STRATEGY
process-id process size partition number partition size
0 212 3 300
1 417 1 500
2 112 2 200
3 426 4 600
Unused space after best fit allocation =533
WORST FIT ALLOCATION STRATEGY
process-id process size partition number partition size
0 212 4 600
1 417 1 500
2 112 3 300
process 3 cannot be stored in any partitions.
Unused space after worst fit allocation =959
Efficient algorithm among the three strategies...
Best fit algorithm is efficient
student@acew:~$
Result:
Thus the C program to implement Contiguous memory allocation Technique has been
implemented and verified.
Ex.No :11 PAGE REPLACEMENT
Ex.no:11 a FIFO Page Replacement
Date:
Aim:
To implement demand paging for a reference string using FIFO method.
Algorithm:
1. Get length of the reference string, say l.
2. Get reference string and store it in an array, say rs.
3. Get number of frames, say nf.
4. Initalize frame array upto length nf to -1.
5. Initialize position of the oldest page, say j to 0.
6. Initialize no. of page faults, say count to 0.
7. For each page in reference string in the given order, examine:
a. Check whether page exist in the frame array
b. If it does not exist then
i. Replace page in position j.
ii. Compute page replacement position as (j+1) modulus nf.
iii. Increment count by 1.
iv. Display pages in frame array.
8. Print count.
Program:
#include <stdio.h>
main()
{
int i,j,l,rs[50],frame[10],nf,k,avail,count=0;
printf("Enter length of ref. string : ");
scanf("%d", &l);
printf("Enter reference string :\n");
for(i=1; i<=l; i++)
scanf("%d", &rs[i]);
printf("Enter number of frames : ");
scanf("%d", &nf);
for(i=0; i<nf; i++)
frame[i] = -1;
j = 0;
printf("\nRef. str Page frames");
for(i=1; i<=l; i++)
{
printf("\n%4d\t", rs[i]);
avail = 0;
for(k=0; k<nf; k++)
if(frame[k] == rs[i])
avail = 1;
if(avail == 0)
{
frame[j] = rs[i];
j = (j+1) % nf;
count++;
for(k=0; k<nf; k++)
printf("%4d", frame[k]);
}
}
printf("\n\nTotal no. of page faults : %d\n",count);
}
Output:
$ gcc fifopr.c
$ ./a.out
Enter length of ref. string : 20
Enter reference string :
12342156212376321236
Enter number of frames : 5
Ref. str Page frames
1 1 -1 -1 -1 -1
2 1 2 -1 -1 -1
3 1 2 3 -1 -1
4 1 2 3 4 -1
2
1
5 1 2 3 4 5
6 6 2 3 4 5
2
1 6 1 3 4 5
2 6 1 2 4 5
3 6 1 2 3 5
7 6 1 2 3 7
6
3
2
1
2
3
6
Total no. of page faults : 10
Result
Thus page replacement was implemented using FIFO algorithm.
Ex.no:: 11b LRU PAGE REPLACEMENT
Date:
Aim:
To implement demand paging for a reference string using LRU method.
Algorithm:
#include <stdio.h>
main()
{
int i,j,len,rs[50],frame[10],nf,k,avail,count=0;
int access[10], freq=0, dm;
printf("Length of Reference string : ");
scanf("%d", &len);
printf("Enter reference string :\n");
for(i=1; i<=len; i++)
scanf("%d", &rs[i]);
printf("Enter no. of frames : ");
scanf("%d", &nf);
for(i=0; i<nf; i++)
frame[i] = -1;
j = 0;
printf("\nRef. str Page frames");
for(i=1; i<=len; i++)
{
printf("\n%4d\t", rs[i]);
avail = 0;
for(k=0; k<nf; k++)
{
if(frame[k] == rs[i])
{
avail = 1;
access[k] = ++freq;
break;
}
}
if(avail == 0)
{
dm = 0;
for(k=0; k<nf; k++)
{
if(frame[k] == -1)
dm = 1;
break;
}
if(dm == 1)
{
}
else
{
frame[k] = rs[i]; access[k] =
++freq; count++;
Output:
$ gcc lrupr.c
$ ./a.out
Length of Reference string : 20
Enter reference string :
1234 2 1 5 6 2 1 2 3 7 6 3 2 1 2 3 6
Enter no. of frames : 5
Ref. str Page frames
1 1 -1 -1 -1 -1
2 1 2 -1 -1 -1
3 1 2 3 -1 -1
4 1 2 3 4 -1
2
1
5 1 2 3 4 5
6 1 2 6 4 5
2
1
2
3 1 2 6 3 5
7 1 2 6 3 7
6
3
2
1
2
3
6
Total no. of page faults: 8
Result
Thus page replacement was implemented using LRU algorithm.
Ex.no: 11c LFU PAGE REPLACEMENT (OPTIMAL)
Date:
Aim:
To implement demand paging for a reference string using LFU method.
Algorithm:
1. Create a array
2. When the page fault occurs replace page that will not be used for the longest
period of time
Program:
#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],optcal[50],count=0;
int optvictim();
void main()
{
clrscr();
printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHN");
printf("\n. .............................. ");
printf("\nEnter the no.of frames");
scanf("%d",&nof);
printf("Enter the no.of reference string");
scanf("%d",&nor);
printf("Enter the reference string");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
clrscr();
printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHM");
printf("\n. ............................. ");
printf("\nThe given string");
printf("\n. ................. \n");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=0;i<nof;i++)
{
frm[i]=-1;
optcal[i]=0;
}
for(i=0;i<10;i++)
recent[i]=0;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\tref 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=optvictim(i);
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
}
printf("\n Number of page faults: %d",pf);
getch();
}
int optvictim(int index)
{
int i,j,temp,notfound;
for(i=0;i<nof;i++)
{
notfound=1;
for(j=index;j<nor;j++)
if(frm[i]==ref[j])
{
notfound=0;
optcal[i]=j;
break;
}
if(notfound==1)
return i;
}
temp=optcal[0];
for(i=1;i<nof;i++)
if(temp<optcal[i])
temp=optcal[i];
for(i=0;i<nof;i++)
if(frm[temp]==frm[i])
return i;
return 0;
}
Output: $ gcc lfupr.c
$ ./a.out
Enter no.of Frames 3
Enter no.of reference string 6
Enter reference string
654231
OPTIMAL 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
Result :
Thus page replacement was implemented using LFU algorithm.
Ex.No: 12 FILE ORGANIZATION TECHNIQUES
Ex.no: 12a Implementation of Single level directory structure
Date:
Aim:
To write a C program to implement Single level directory structure.
Agorithm:
1. Get the number and names of directories.
2. Get the number of files in each directory.
3. Read the names of files in each directory.
4. If the entered name exists read a new name.
5. Display directories along with its files.
Program:
#include<stdio.h>
#include<string.h>
main()
{
int master,s[20],i,j,k;
char f[20][20][20],d[20][20];
printf("Enter number of directories: ");
scanf("%d",&master);
printf("Enter names of directories : ");
for(i=0;i<master;i++)
scanf("%s",d[i]);
for(i=0;i<master;i++)
{
printf("Enter number of files in directory %d :",i+1);
scanf("%d",&s[i]);
}
for(i=0;i<master;i++)
{
printf("Enter names of files in directory %d :",i+1);
for(j=0;j<s[i];j++)
{
scanf("%s",f[i][j]);
for(k=0;k<j;k++)
{
if(strcmp(f[i][j],f[i][k])==0)
{
printf("File Exists...");
printf("Enter new file name");
scanf("%s",f[i][j]);
}
}
}
printf("\n");
}
printf("Directory\t Size\t File name\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\t\t",f[i][j]);
printf("\n");
}
printf("\t\n");
}
Output:
student@acew:~$ ./a.out
Enter number of directories: 3
Enter names of directories : dir1
dir2
dir3
Enter number of files in directory 1 :2
Enter number of files in directory 2 :2
Enter number of files in directory 3 :2
Enter names of files in directory 1 :file1
file2
Result:
Thus the C program to implement Single level directory structure has been implemented
and verified.
Ex.no: 12b Implementation of Two level directory structures
Aim:
To write a C program to implement Two level directory structure.
Agorithm:
1. Get the number and names of master file directories.
2. Get the number of user file directories.
3. Read the names of files in each user file directory.
4. If the entered name exists read a new name.
5. Display master file directories along with user file directories and the files inside each
user file directory.
Program:
#include<stdio.h>
struct st
{
char dname[20],sdname[20][20],fname[20][20][20];
int ds,sds[20];
}dir[20];
main()
{
int i,j,k,n;
printf("Enter number of master file directories :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Name of directory %d",i+1);
scanf("%s",dir[i].dname);
printf("Enter number of user file directories :");
scanf("%d",&dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("Enter user file directory name and size");
scanf("%s",dir[i].sdname[j]);
scanf("%d",&dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
{
printf("Enter file name :");
scanf("%s",dir[i].fname[j][k]);
}}}
printf("\n Master dir name\tsize\t sub dir name\t size\t files\n");
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:
student@acew:~$ ./a.out
Enter number of master file directories :1
Enter Name of directory 1dir1
Enter number of user file directories :3
Enter user file directory name and size uf1
2
Enter file name :f1
Enter file name :f2
Enter user file directory name and size uf2
3
Enter file name :f3
Enter file name :f4
Enter file name :f5
Enter user file directory name and size uf3
2
Enter file name :f6
Enter file name :f7
Master size sub dir size files
****************************************************
dir1 3 uf1 2 f1 f2
uf2 3 f3 f4 f5
uf3 2 f6 f7
student@acew:~$
Result:
Thus the C program to implement Two level directory structure has been implemented and
verified.
Ex:no 13 FILE ALLOCATION STRATEGIES
Ex.no. 13a Sequential file allocation
Date:
Aim:
Write a C Program to implement Sequential File Allocation method.
Algorithm:
1: Start the program.
2: Get the number of memory partition and their sizes.
3: Get the number of processes and values of block size for each process.
4: First fit algorithm searches all the entire memory block until a hole which is
big enough is encountered. It allocates that memory block for the requesting
process.
5: Best-fit algorithm searches the memory blocks for the smallest hole which can
be allocated to requesting process and allocates if.
6: Worst fit algorithm searches the memory blocks for the largest hole and
allocates it to the process.
7: Analyses all the three memory management techniques and display the best
algorithm which utilizes the memory resources effectively and efficiently.
8: Stop the program.
Program:
#include<stdio.h>
#include<conio.h>
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]);
printf("Enter file name:");
scanf("%d",&x);
printf("File name is:%d",x);
printf("length is:%d",b[x-1]);
printf("blocks occupied:");
for(i=0;i<b[x-1];i++)
printf("%4d",c[x-1][i]);
getch();
}
Output:
Enter no.of files: 2
Enter no. of blocks occupied by file1 4
Enter the starting block of file1 2
Enter no. of blocks occupied by file2 10
Enter the starting block of file2 5
Filename Start block length
1 2 4
2 5 10
Enter file name: rajesh
File name is:12803 length is:0blocks occupied
Result:
Thus the C Program for Sequential File Allocation method is implemented
Ex. no: 13b Indexed file allocation
Date:
Aim: Write a C Program to implement Indexed File Allocation method.
Algorithm:
1: Start.
2: Let n be the size of the buffer
3: check if there are any producer
4: if yes check whether the buffer is full
5: If no the producer item is stored in the buffer
6: If the buffer is full the producer has to wait
7: Check there is any cosumer. If yes check whether the buffer is empty
8: If no the consumer consumes them from the buffer
9: If the buffer is empty, the consumer has to wait.
10: Repeat checking for the producer and consumer till required
11: Terminate the process.
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]);
}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:
Enter no.of files: 2
Enter no. of blocks occupied by file1 4
Enter the starting block of file1 2
Enter no. of blocks occupied by file2 10
Enter the starting block of file2 5
Filename Start block length
1 2 4
2 5 10
Enter file name: rajesh
File name is:12803 length is:0blocks occupied
Result:
Thus the C Program for Indexed File Allocation method is implemented.
Ex. no: 13c Linked file allocation
Date:
Aim:
Write a C Program to implement Linked File Allocation method.
Algorithm:
1. Create a queue to hold all pages in memory
2. When the page is required replace the page at the head of the queue
3. Now the new page is inserted at the tail of the queue
4.Create a stack
5. When the page fault occurs replace page present at the bottom of the stack
6. Stop the allocation.
Program:
#include<stdio.h>
#include<conio.h>
struct file
{
char fname[10];
int start,size,block[10];
}f[10];
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);
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();
}
Output:
Enter no. of files:2
Enter file name:venkat
Enter starting block:20
Enter no.of blocks:6
Enter block numbers: 4
12
15
45
32
25
Enter file name:rajesh
Enter starting block:12
Enter no.of blocks:5
Enter block numbers:6
5
4
3
2
File start size block
venkat 20 6 4--->12--->15--->45--->32--->25
rajesh 12 5 6--->5--->4--->3--->2
Result:
Thus the C Program for Linked File Allocation method is implemented.
Ex:No 14 IMPLEMENTATION OF VARIOUS DISK SCHEDULING ALGORITHMS
Aim: To Write a C program to simulateFCFS disk scheduling algorithms
Date:
15 a) FCFS DISK SCHEDULING ALGORITHM
Algorithm:
1. Let Request array represents an array storing indexes of tracks that have been requested in ascending
order of their time of arrival. „head‟ is the position of disk head.
2. Let us one by one take the tracks in default order and calculate the absolute distance of the track from
the head.
3. Increment the total seek count with this distance.
4. Currently serviced track position now becomes the new head position.
5. Go to step 2 until all tracks in request array have not been serviced.
Program:
#include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
return 0;
Output:
Enter the max range of disk 200
Enter the size of queue request 8
Enter the queue of disk positions to be read
90 120 35 122 38 128 65 68
Enter the initial head position 50
Disk head moves from 50 to 90 with seek 40
Disk head moves from 90 to 120 with seek 30
Disk head moves from 120 to 35 with seek 85
Disk head moves from 35 to 122 with seek 87
Disk head moves from 122 to 38 with seek 84
Disk head moves from 38 to 128 with seek 90
Disk head moves from 128 to 65 with seek 63
Disk head moves from 65 to 68 with seek 3
Total seek time is 482
Average seek time is 60.250000
Result:
Thus the C program for SCAN disk scheduling was written and executed successfully
14 b) SCAN DISK SCHEDULING ALGORITHM
Aim:
To Write a C program to simulate SCAN disk scheduling algorithm.
Description
In the SCAN algorithm, the disk arm starts at one end of the disk and moves toward the other
end,servicing requests as it reaches each cylinder,until it gets to the other end of the disk. At the other
end, the direction of head movement is reversed, and servicing continues. The head continuously scans
back and forth across the disk. The SCAN algorithm is sometimes called the elevator algorithm, since the
disk arm behaves just like an elevator in a building, first servicing all the requests going up and then
reversing to service requests the other way.
Algorithm-
1. Let Request array represents an array storing indexes of tracks that have been requested in ascending
order of their time of arrival. „head‟ is the position of disk head.
2. Let direction represents whether the head is moving towards left or right.
3. In the direction in which head is moving service all tracks one by one.
4. Calculate the absolute distance of the track from the head.
5. Increment the total seek count with this distance.
6. Currently serviced track position now becomes the new head position.
7. Go to step 3 until we reach at one of the ends of the disk.
8. If we reach at the end of the disk reverse the direction and go to step 2 until all tracks in request array
have not been serviced.
Program:
#include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],
temp1=0,temp2=0;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the initial head position\n");
scanf("%d",&head);
{
scanf("%d",&temp);
if(temp>=head)
{
queue1[temp1]=temp;
temp1++;
}
else
{
queue2[temp2]=temp;
temp2++;
}
}
for(i=0;i<temp1-1;i++)
{
for(j=i+1;j<temp1;j++)
{
if(queue1[i]>queue1[j])
{
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
}
}
}
for(i=0;i<temp2-1;i++)
{
for(j=i+1;j<temp2;j++)
{
if(queue2[i]<queue2[j])
{
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
}
}
}
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];
queue[i]=max;
for(i=temp1+2,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[i]=0;
queue[0]=head;
for(j=0;j<=n+1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n”, queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}
Output:
Enter the max range of disk 200
Enter the initial head position 50
Enter the size of queue request 8
Enter the queue of disk positions to be read
90 120 35 122 38 128 65 68
Disk head moves from 50 to 65 with seek 15
Disk head moves from 65 to 68 with seek 3
Disk head moves from 68 to 90 with seek 22
Disk head moves from 90 to 120 with seek 30
Disk head moves from 120 to 122 with seek 2
Disk head moves from 122 to 128 with seek 6
Disk head moves from 128 to 200 with seek 72
Disk head moves from 200 to 38 with seek 162
Disk head moves from 38 to 35 with seek 3
Disk head moves from 35 to 0 with seek 35
Total seek time is 350
Average seek time is 43.750000
Result:
Thus the C program for SCAN disk scheduling was written and executed successfully
14 c) C-SCAN DISK SCHEDULING ALGORITHM
Aim:
To write a C program to implement C-SCAN Disk Scheduling Algorithm
Description
Circular SCAN (C-SCAN) scheduling is a variant of SCAN designed to provide a more uniform wait
time. Like SCAN, C-SCAN moves the head from one end of the disk to the other, servicing requests
along the way. When the head reaches the other end, however, it immediately returns to the beginning of
the disk without servicing any requests on the return trip .The C-SCAN scheduling algorithm essentially
treats the cylinders as a circular list that wraps around from the final cylinder to the first one
Algorithm:
1. Let Request array represents an array storing indexes of tracks that have been requested in ascending order
of their time of arrival. „head‟ is the position of disk head.
2. The head services only in the right direction from 0 to the size of the disk.
3. While moving in the left direction do not service any of the tracks.
4. When we reach the beginning(left end) reverse the direction.
5. While moving in the right direction it services all tracks one by one.
6. While moving in the right direction calculate the absolute distance of the track from the head.
7. Increment the total seek count with this distance.
8. Currently serviced track position now becomes the new head position.
9. Go to step 6 until we reach the right end of the disk.
10. If we reach the right end of the disk reverse the direction and go to step 3 until all tracks in the request
array have not been serviced.
Program:
#include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],
temp1=0,temp2=0;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the initial head position\n");
scanf("%d",&head);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
for(i=1;i<=n;i++)
{
scanf("%d",&temp);
if(temp>=head)
{
queue1[temp1]=temp;
temp1++;
}
else
{
queue2[temp2]=temp;
temp2++;
}
}
for(i=0;i<temp1-1;i++)
{
for(j=i+1;j<temp1;j++)
{
if(queue1[i]>queue1[j])
{
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
}
}
}
for(i=0;i<temp2-1;i++)
{
for(j=i+1;j<temp2;j++)
{
if(queue2[i]>queue2[j])
{
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
}
}
}
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];
queue[i]=max;
queue[i+1]=0;
for(i=temp1+3,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[0]=head;
for(j=0;j<=n+1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with seek %d\n”, queue[j],queue[j+1],diff); }
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}
Output:
Enter the max range of disk 200
Enter the initial head position 50
Enter the size of queue request 8
Enter the queue of disk positions to be read
90 120 35 122 38 128 65 68
Disk head moves from 50 to 65 with seek 15
Disk head moves from 65 to 68 with seek 3
Disk head moves from 68 to 90 with seek 22
Disk head moves from 90 to 120 with seek 30
Disk head moves from 120 to 122 with seek 2
Disk head moves from 122 to 128 with seek 6
Disk head moves from 128 to 200 with seek 72
Disk head moves from 200 to 0 with seek 200
Disk head moves from 0 to 35 with seek 35
Disk head moves from 35 to 38 with seek 3
Total seek time is 388
Average seek time is 48.500000
Result:
Thus the C program for C- SCAN disk scheduling was written and executed successfully
Ex: No 15 INSTALL LINUX OPERATING SYSTEM USING VMWARE.
Aim:
To install any guest operating system like linux using VMware
Description:
Installing a Linux operating System using a VMware consists of two steps.
Part 1: Prepare a Computer for Virtualization
distribution.
The VMware Player has 32-bit and 64-bit versions for Windows and Linux. To download the software, you
must register a free user account with VMware.
Note: The Linux version of VMware Player might work on Mac OS X; if not, http://virtualbox.org has a free
c. When you have downloaded the VMware Player installation file, run the installer and accept the default
installation settings.
a. To download Linux, you first must select a distribution such as Mint, Ubuntu, Fedora, Suse, Debian, or
CentOS. (There are many others to choose from.) In this lab, the instructions follow an installation of Linux Mint.
b. Go to http://linuxmint.com, hover over the Download button, and click Linux Mint 16 (or current
version number).
c. Scroll down the page until you see the version of the Mint code name, Cinnamon (or the current code
name). Choose either the 32-bit or 64-bit version, depending on your current operating system platform,
d. A new web page will appear. Select a download mirror site from which to download the operating
system. Click a mirror site to activate the Linux file download. When prompted by the browser, choose to save the
Linux .iso file to a local directory.
e. When the file has finished downloading, you should have a Linux Mint .iso bootable image.
Then, using the Linux Mint .iso file that you downloaded in Part 1, you will install the Linux Mint operating
b. A new window will appear. Select I will install the operating system later. The virtual machine will be
created with a blank hard disk option. Click Next.
c. A new window will appear. Select Linux as the guest operating system. Under version, you may notice
that Mint is not listed. In this case, select an alternate Linux distribution, one that is closely related to Mint
(like Ubuntu). Lastly, select either the 32-bit or 64-bit version and click Next.
d. A new window will appear. Select a name and storage location for the virtual machine.
e. A new window will appear. Select the maximum size of the virtual hard drive storage. You can also decide
whether or not to store the virtual hard drive in a single file or in multiple files.
f. When a new window appears, click Finish to finish creating the virtual machine hardware, or click
Customize Hardware to customize the virtual hardware. For example, you can specify the amount of
RAM, how many CPU cores you want, and add additional drives and peripheral components (see video
tutorial).
g. When you have customized and completed the process, you are now ready to run your virtual machine
and install an operating system.
b. In the pop-up window, under the Hardware tab, select CD/DVD (SATA), and on the right side (under
Connections), select the Use ISO image file option, and click Browse to search through your file
system for the Linux Mint .iso image file downloaded in Part 1.
Selecting the Linux .iso file causes it to be automatically mounted to the CD/DVD drive when the virtual
machine boots, which, in turn, causes the system to boot and run the Linux installation image.
The network adapter is currently set to NAT mode, which allows your virtual machine to access the
network through the host computer system by translating all Internet requests through the VMware player,
much like a gateway router. This gives your virtual machine a private network address separate from your
home network.
(Optional) To have your virtual machine on the same network as the computer hosting the virtual
machine, select the Bridged option and click Configure Adapters to identify to which physical network
Note: This is especially important on laptops that have both wireless and wired network adapters that can
e. Click Play virtual machine to launch your virtual machine and boot to Linux.
When the boot process has completed you should be presented with a Linux Mint desktop.
f. (Optional) To permanently install Linux Mint on the virtual machine hard disk drive, on the desktop,
double-click the Install Linux Mint disk icon and follow the installation procedure (see video).
During the installation, you will be presented with a warning message that installing to the drive will erase
everything on the disk drive; this refers to the virtual disk drive, not the host computer physical disk drive.
g. When you have finished the installation procedure, you should have a Linux Mint virtual machine that you