You are on page 1of 76

Ex No: 1 BASIC COMMANDS IN LINUX

DATE:

Aim: To study the basic commands in Linux operating system.


Commands: The following are the commands to be studied:
1. date
i. date +%m
ii. date +%h
iii. date +%d
iv. date +%y &date +%Y
v. date +%H
vi. date +%M
vii. date +%S
2. cal
i. cal year
3. echo “message”
4. who
i. whoami
5. mkdir
6. cd directory name
7. rmdir directory name
8. cd
9. ls
10. cat>filename
11. cat filename
12. cp source file destination file
13. mv source file destination file
14. cut -c column number file name
15. rm file name
16. grep
17. chmod
18. sort file name

19. wc file name


20. man
21.clear
1
Explanation for the above commands is given below.

1. TASK : To display the system date and time


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

i. TASK : To display the current month.


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

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


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

iii. TASK : To display the current system date.


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

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


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

v. TASK : To display the current system time.


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

2
vi. TASK : To display the current system time.
COMMAND : date
SYNTAX : date +%M
EXPLANATION: This command displays system time (in min) on the screen.
OUTPUT :
[exam1@local host ~]$date +%M
49

vii. TASK : To display the current system time.


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

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


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

-3 Display prev/current/next month output.

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


default.)

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

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

-y Display a calendar for the current year.


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

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

August 2013 September 2013 October 2013


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

3
i. TASK : To display the calendar of a year.
COMMAND : cal
SYNTAX : cal year
EXAMPLE : cal 2007
EXPLANATION: This command displays the calendar of the specified year.
OUTPUT :
[exam88@local host ~] $ cal 2012
It displays all the month of the year 2012

3. TASK : To display the user defined message


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

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


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

i. TASK : To display the user detail.


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

5. TASK : To create directory.


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

6. TASK : To change directory


COMMAND : change directory
SYNTAX : cd directory name
EXAMPLE : cd sun
EXPLANATION : This command is used to switch from one directory to another.
OUTPUT :
[exam88@local host ~] $ cd sun
[exam88@local host sun] $
4
7. TASK : To come out of sub-directory.
COMMAND : change directory
SYNTAX : cd
EXPLANATION : This command help in switching to the main directory.
OUTPUT :
[exam88@local host sun] $ cd
[exam88@local host ~] $

8. TASK : To delete a directory.


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

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


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

10. TASK : To create a file.


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

11. TASK : To view a file


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

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

13. TASK : To move a file.


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

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


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

15. TASK : To delete a file.


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

16. TASK : This command prints the line matching the pattern. grep(globally search a regular expression and print)
COMMAND : grep
SYNTAX : grep „string‟ filename
EXAMPLE : grep „stat‟ stat1.c

6
OUTPUT :
[exam1@CSELAB1 ~]$ grep 'stat' stat1.c
#include<sys/stat.h>
struct stat st;
s=stat("fork1.c",&st);
printf("\n use of stat() is unsuccessful ");

17. TASK :To change file access permission.


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

18. TASK : To sort the content


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

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


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

 wc -l <filename> print the line count


 wc -m <filename> print the character count
 wc -L <filename> print the length of longest line
 wc -w <filename> print the word count

OUTPUT :

[exam88@local host ~] $ wc –l –w –m moon.txt (or)[exam88@local host ~] $ wc moon.txt

2 7 33 moon.txt

20. TASK : To display the manual pages.


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

21. TASK : To clear the screen.


COMMAND : clear

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

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

7
EX.NO: 2 PROGRAM USING SYSTEM CALL fork() , getpid() and getppid()

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 “Error in Creation”.
Step 4 : Else if pid value is equal to zero then print current process id and parent process id.

Step 5 : Else if pid is greater than zero then print current process id and parent process id.

Step 6 : stop.

8
PROGRAM:
#include<sys/types.h>
int main()
{
int pid,p1,p2;
printf("\n Fork Calling ");
pid=fork();
printf("\n After Fork Called ");
if(pid > 0)
{
printf("\n New pid is %d ",pid);
p1=getpid();
printf("\n Current Process1 id : %d ",p1);
p2=getppid();
printf("\n Parent process1 id : %d \n",p2);

}
else if(pid==0)
{
p1=getpid();
printf("\n Current Process2 id : %d ",p1);
p2=getppid();
printf("\n Parent process2 id : %d \n",p2);
}
else if(pid==-1)
{
printf("\n Error in Creation ");
}
return 0;
}

Output: (FORK)
"fork.c" [New] 29L, 521C written
[exam03@localhost ~]$ cc fork.c
[exam03@localhost ~]$ ./a.out

Fork Calling
After Fork Called
Current Process2 id : 28920
Parent process2 id : 28919
Fork Calling
After Fork Called
New pid is 28920
Current Process1 id : 28919
Parent process1 id : 28886
[exam03@localhost ~]$

RESULT:

Thus the above program was executed successfully.


9
EX.NO :2a PROGRAM USING SYSTEM CALLS opendir( ) readdir( ) closedir()
DATE:

AIM :

To write the program to implement the system calls opendir( ), readdir( ).

ALGORITHM :

Step 1 : Start the program


Step 2 : In the main function pass the arguments.
Step 3 : Create structure pointer
Step 4 : Use opendir() system call

Step 5: Then use readdir() system call to read the directory entries.

Step 6: Stop the program.

10
PROGRAM CODING:

#include<stdio.h>
#include<sys/types.h>
#include<sys/dir.h>
void main(int age,char *argv[])
{
DIR *dir;
struct dirent *rddir;
printf("\n Listing the directory content\n");
dir=opendir(argv[1]);
while((rddir=readdir(dir))!=NULL)

{
printf("%s\t\n",rddir->d_name);
}
closedir(dir);

OUTPUT:
RP
roshi.c
first.c
pk6.c f2

abc FILE1

RESULT:
Thus the above program was executed successfully.

11
EX.NO :2b 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. Step
5: stop the program.

PROGRAM CODING:
#include<stdio.h>
#include<unistd.h> main( ){
printf(“\n exec system call”);
printf(“displaying the date”);
execlp( “/bin/date”, “date”, 0);

OUTPUT:
Tue Dec 25 02 : 57 : 38 IST 2018

RESULT:
Thus the program was executed and verified successfully.

12
EX.NO : 2c 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.

Step7 : 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 chid processes get terminated it execute the wait( )
system call to permanently get deleted from the OS.

13
PROGRAM CODING:
#include<stdio.h> #include<unistd.h>
main( ){ int
i, pid;
pid=fork( );
if(pid== -1)
{perror(“fork failed”);

exit(0);
}else if(pid==0){
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”);
}exit(0);}

OUTPUT:
Child process starts Child
process 0 is called Child
process 1 is called Child
process 2 is called Child
process 3 is called Child
process 4 is called Child
process ends Parent process
ends

RESULT:
Thus the above program was executed successfully

14
EX. NO:3 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.

15
PROGRAM CODING:

#include<stdio.h>
#include<dirent.h>
int main()
{
struct dirent **namelist;
int n,i;
char pathname[100];
scanf("%s",&pathname);
getcwd(pathname);

n=scandir(pathname,&namelist,0,alphasort);

if(n<0)
printf("Error");
else
for(i=0;i<n;i++)

printf("%s\n",namelist[i]->d_name);
}

16
OUIPUT:

[exam100@localhost ~]$ ./a.out


.
..
.bash_history
.bash_logout
.bash_profile
.bashrc
.emacs
.f.c.swo
.gtkrc
.kde
.viminfo
a.out
aa
bb
dir.c
e.c
ex.c
exe.c
exec.c
l.c
sk
[exam100@localhost ~]$

RESULT:
Thus the above program was executed successfully.

17
EX. NO:3a 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 : Declare command line arguments.

Step 3 : Declare file pointer, buffer and char pointer

Step 4 : Now check the arguments and display corresponding messages.

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.

18
PROGRAM:

#include<stdio.h>
#include<string.h>
#define buffer 1024
int main(int argc,char *argv[])
{
FILE *fp;
char fline[buffer];
char *newline;
int line=1;
if(argc!=3)
{
printf("Please use the following syntax \n");
printf("./a.out filename searchstring \n");
printf("Example: ./a.out test1.c print \n");
exit(1);
}
// argv[1] is filename
if(!(fp=fopen(argv[1],"r")))
{
printf("grep : Couldnot open file : %s\n",argv[1]);
exit(1);
}
while(fgets(fline,buffer,fp)!=NULL)
{
// argv[2] is search string
if(strstr(fline,argv[2])!=NULL)
{
printf("Line number: %d text: %s\n",line,fline);
}
line++;
}

19
OUTPUT:

"grep.c" [New] 34L, 629C written

[exam100@localhost ~]$ cc grep.c

[exam100@localhost ~]$ ./a.out grep.c printf

Line number: 12 text: printf("Please use the following syntax \n");

Line number: 13 text: printf("./a.out filename searchstring \n");

Line number: 14 text: printf("Example: ./a.out test1.c print \n");

Line number: 20 text: printf("grep : Couldnot open file : %s\n",argv[1]);

Line number: 28 text: printf("Line number: %d text: %s\n",line,fline);

[exam100@localhost ~]$

RESULT:
Thus the above program was executed successfully.

20
EX. NO:4 SHELL PROGRAMMING

DATE:

Assume that a =10 and b=20

Arithmetic Operators:

Operator Description Example


Addition - Adds values on either
+ `expr $a + $b` will give 30
side of the operator
Subtraction - Subtracts right hand
- `expr $a - $b` will give -10
operand from left hand operand
Multiplication - Multiplies values on
* `expr $a \* $b` will give 200
either side of the operator
Division - Divides left hand operand
/ `expr $b / $a` will give 2
by right hand operand
Modulus - Divides left hand operand
% by right hand operand and returns `expr $b % $a` will give 0
remainder
Assignment - Assign right operand a=$b would assign value of b into
=
in left operand a
Equality - Compares two numbers, if
== [ $a == $b ] would return false.
both are same then returns true.
Not Equality - Compares two
!= numbers, if both are different then [ $a != $b ] would return true.
returns true.

Relational Operators:

Operator Description Example


Checks if the value of two operands are
-eq equal or not, if yes then condition [ $a -eq $b ] is not true.
becomes true.
Checks if the value of two operands are
-ne equal or not, if values are not equal [ $a -ne $b ] is true.
then condition becomes true.
Checks if the value of left operand is
-gt greater than the value of right operand, [ $a -gt $b ] is not true.
if yes then condition becomes true.
Checks if the value of left operand is
-lt less than the value of right operand, if [ $a -lt $b ] is true.
yes then condition becomes true.
Checks if the value of left operand is
greater than or equal to the value of
-ge [ $a -ge $b ] is not true.
right operand, if yes then condition
becomes true.
21
Checks if the value of left operand is
less than or equal to the value of right
-le [ $a -le $b ] is true.
operand, if yes then condition becomes
true.

Note:

All the conditional expressions would be put inside square braces with one space
around them
[ $a == $b ] is correct where as [$a==$b] is incorrect
[ $a <= $b ] is correct where as [$a <= $b] is incorrect.

Boolean Operators:

Operator Description Example


This is logical negation. This inverts a
! true condition into false and vice [ ! false ] is true.
versa.
This is logical OR. If one of the
-o operands is true then condition would [ $a -lt 20 -o $b -gt 100 ] is true.
be true.
This is logical AND. If both the
[ $a -lt 20 -a $b -gt 100 ] is
-a operands are true then condition would
false.
be true otherwise it would be false.

22
4A. EVEN OR ODD NUMBER
AIM:
To find whether the given number is odd or even.

ALGORITHM:
1. Start the program.
2. Get the value for variable n.
3. Divide the value of n by 2 and store the value in r.
4. If the remainder of r is equal to zero then goto step 5 else goto step 6.
5. Print the given number is even number and goto step 7.
6. Print the given number is odd number and goto step 7.
7. Stop the program execution.

PROGRAM:

echo "ENTER THE NUMBER"


read n
r=$(($n%2))
if [ $r -eq 0 ]
then
echo "EVEN"
else
echo "ODD"
fi

OUTPUT:

[exam1@localhost ~]$ sh ex01.sh


ENTER THE NUMBER
450
EVEN
[exam1@localhost ~]$

RESULT:
Thus the program was executed successfully.

23
4B. LINUX USING ECHO COMMAND
AIM:
To print the commands using echo.

ALGORITHM:
1. Start the program.
2. Print 1.WHO AM I?
3. Print 2.WHO IS LOGGED ON?
4. Print 3.DATE
5. Get the value for variable n.
6. Use switch case, if the value of n is 1 then displays the information about the current
user of the system on the screen else if the value of n is 2 then lists the information about all
the users who have logged on else if the value of n is 3 then displays the current system date
and time on the screen.
7. Stop the program execution.

PROGRAM:
echo "1.WHO AM I?"
echo "2.WHO IS LOGGED ON?"
echo "3.DATE"
read n
case $n in
1) whoami;;
2) who;;
3) date;;
esac

OUTPUT:

[exam1@localhost ~]$ sh ex02.sh


1.WHO AM I?
2.WHO IS LOGGED ON?
3.DATE
1
exam1
[exam1@localhost ~]$

RESULT:
Thus the program was executed successfully.

24
4C. FACTORIAL OF A NUMBER
AIM:
To find the factorial of a given number.

ALGORITHM:
1. Start the program.
2. Get the value for variable num.
3. Initialize the value of i and fact as 1.
4. Check whether i is less than num, if so calculate fact=fact*i, increment the value of i
by 1, goto step 4.else goto step 5.
5. Print the factorial of a number.
6. Stop the program execution.

PROGRAM:

echo “FACTORIAL OF A GIVEN NUMBER”


echo "ENTER THE NUMBER"
read num
i=1
fact=1
while [ $i -le $num ]
do
fact=$(($fact*$i))
i=$(($i+1))
done
echo "FACTORIAL OF $num IS $fact"

OUTPUT:
[exam1@CSELAB1 ~]$ sh ex3.sh
ENTER THE NUMBER
5
FACTORIAL OF 5 IS 120
[exam1@CSELAB1 ~]$

RESULT:
Thus the program was executed successfully.

25
4D. GREATEST OF THREE NUMBERS
AIM:
To find the greatest of three numbers.

ALGORITHM:
1. Start the program.
2. Enter the value for a, b &c.
3. If a is greater than b and a is greater than c then goto step 4 else check b is greater than
c then goto step 5 else Print c is greatest.
4. Print a is greatest goto step 6.
5. Print b is greatest goto step 6.
6. Stop the program execution.

PROGRAM:

echo "ENTER THE VALUES:"


read a b c
if [ $a -gt $b -a $a -gt $c ]
then
echo "$a IS GREATEST"
elif [ $b -gt $c ]
then
echo "$b IS GREATEST"
else
echo "$c IS GREATEST"
fi

OUTPUT:
[exam1@localhost ~]$ sh ex04.sh
ENTER THE VALUES:
23 98 -1
98 IS GREATEST
[exam1@localhost ~]$

RESULT:
Thus the program was executed successfully.

26
IMPLEMENTATION OF CPU SCHEDULING

EX.NO.5A

DATE:
IMPLEMENTATION OF FCFS SCHEDULING
AIM:
To write a c program to implement FCFS scheduling.

ALGORITHM:

1. Start the program.


2. With Process number, burst time, turnaround time and waiting time and create object
for the structure
3. In main function get the number of processes and burst time for each processes.
4. Calculate Waiting time and turnaround time as
 TURNARROUND TIME=WAITING TIME+BURST TIME.
5. Average waiting time and average turn around can be calculated by
 Average waiting time=sum of waiting time /No of process.
 Average Turnaround time= sum of Turnaround time/ No of processes.
6. Print Process number, Burst time, Waiting time and Turnaround time for each
processes and Average waiting and Turnaround time.
7. Terminate the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX 10

struct process
{
int pro;
int brt;
int tt;
int wt;
}pr[MAX];

// main program
int main()
{
int i,j,n,totwt,tottt;
float avgwt,avgtt;
int prevtt;
clrscr();

printf("\n\t\t First Come First Serve \n");


printf("\t\t ~~~~~ ~~~~ ~~~~~ ~~~~~ \n");
printf("\n\t Enter the no of process:");
scanf("%d",&n);

27
//Getting Process no. and Burst Time
for(i=1;i<=n;i++)
{
pr[i].pro = i;
printf("\nProcess no: %d ",pr[i].pro);
printf("\tEnter burst time:");
scanf("%d",&pr[i].brt);
}
//calculating Waiting time and Turn Aruond Time
prevtt =0;
for(i=1;i<=n;i++)
{
pr[i].wt=prevtt;
pr[i].tt=pr[i].wt+pr[i].brt;
prevtt = pr[i].tt;
}

printf("\n PROCESS NO \t BURST TIME \t WAITING TIME \t TURN AROUND


TIME");
printf("\n ~~~~~~~~~~ \t ~~~~~~~~~~ \t ~~~~~~~~~~~~ \t ~~~~~~~~~~~~~~~~");

//Sum of Waiting time and Turn Aruond Time


totwt=0;
tottt=0;
for(i=1;i<=n;i++)
{
printf("\n\t%d\t\t%d\t\t%d\t\t%d",pr[i].pro,pr[i].brt,pr[i].wt,pr[i].tt);
totwt=totwt+pr[i].wt;
tottt=tottt+pr[i].tt;
}
//Average of Waiting time and Turn Aruond Time
avgwt=(float)totwt/n;
avgtt=(float)tottt/n;
printf("\n\n Average Waiting time:%6.2f",avgwt);
printf("\n\n Average Turnaround Time:%6.2f",avgtt);
printf("\n\n");

// Top Line
for(i=1;i<=pr[n].tt;i++)
{
printf("-");
}
printf("\n");

//Gantt Chart
j=pr[1].wt;
printf("%d",j);

28
for(i=1;i<=n;i++)
{
printf("%*d",pr[i].brt,pr[i].tt);
}
printf("\n");

// Bottom Line
for(i=1;i<=pr[n].tt;i++)
{
printf("-");
}
printf("\n");
getch();
return 0;
}

OUTPUT:
First Come First Serve
~~~~~ ~~~~ ~~~~~ ~~~~~

Enter the no of process:5

Process no: 1 Enter burst time:8

Process no: 2 Enter burst time:3

Process no: 3 Enter burst time:4

Process no: 4 Enter burst time:2

Process no: 5 Enter burst time:6

PROCESS NO BURST TIME WAITING TIME TURN AROUND TIME


~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
1 8 0 8
2 3 8 11
3 4 11 15
4 2 15 17
5 6 17 23

Average Waiting time: 10.20

Average Turnaround Time: 14.80

-----------------------
0 8 11 1517 23
-----------------------
RESULT:
Thus the program was executed successfully.
29
EX.NO.5B
IMPLEMENTATION OF SJF SCHEDULING
AIM:
To write a c program to implement SJF scheduling.

ALGORITHM:

1. Start the program.


2. With Process number, burst time, turnaround time and waiting time and create object
for the structure
3. In main function get the number of processes and burst time for each processes.
4. Sort the process in ascending order with its burst time along with process number.
5. Calculate Waiting time and turnaround time as
 TURNARROUND TIME=WAITING TIME+BURST TIME.
6. Average waiting time and average turn around can be calculated by
 Average waiting time=sum of waiting time /No of process.
 Average Turnaround time= sum of Turnaround time/ No of processes.
7. Print Process number, Burst time, Waiting time and Turnaround time for each
processes and Average waiting and Turnaround time.
8. Terminate the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX 50
struct process
{
int pro;
int brt;
int tt;
int wt;
}pr[MAX];

// Main program
int main()
{
int i,j,n,t,totwt,tottt;
float avgwt,avgtt;
int prevtt;
clrscr();

printf("\n\t\t\t SHORTEST JOB FIRST");


printf("\n\n Enter the no of process:");
scanf("%d",&n);

//Getting Process no. and Burst Time


for(i=1;i<=n;i++)
{
pr[i].pro = i;
printf("\nProcess no: %d ",pr[i].pro);
printf("\nEnter burst time:");
30
scanf("%d",&pr[i].brt);
}

// Sorting the Burst Time in Ascending order


for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(pr[i].brt> pr[j].brt)
{
t= pr[j].pro;
pr[j].pro= pr[i].pro;
pr[i].pro=t;

t= pr[j].brt;
pr[j].brt= pr[i].brt;
pr[i].brt=t;
}
}
}

//calculating Waiting time and Turn Aruond Time


prevtt =0;
for(i=1;i<=n;i++)
{
pr[i].wt=prevtt;
pr[i].tt=pr[i].wt+pr[i].brt;
prevtt = pr[i].tt;
}

//Sum of Waiting time and Turn Aruond Time


printf("\n PROCESS NO \t BURST TIME \t WAITING TIME \t TURN AROUND
TIME");
printf("\n ------------- \t ------------- \t---------- \t --------------");
totwt=0;
tottt=0;
for(i=1;i<=n;i++)
{
printf("\n\t%d\t\t%d\t\t%d\t\t%d",pr[i].pro,pr[i].brt,pr[i].wt,pr[i].tt);
totwt=totwt+pr[i].wt;
tottt=tottt+pr[i].tt;
}

//Average of Waiting time and Turn Aruond Time


avgwt=(float)totwt/n;
avgtt=(float)tottt/n;

printf("\n\n Average Waiting time:%6.2f",avgwt);


printf("\n\n Average Turnaround Time:%6.2f\n\n",avgtt);

31
// Top Line
for(i=1;i<=pr[n].tt;i++)
{
printf("-");
}
printf("\n");

//Gantt Chart
j=pr[1].wt;
printf("%d",j);
for(i=1;i<=n;i++)
{
printf("%*d",pr[i].brt,pr[i].tt);
}
printf("\n");

// Bottom Line
for(i=1;i<=pr[n].tt;i++)
{
printf("-");
}
printf("\n");
getch();
return 0;
}
OUTPUT:
SHORTEST JOB FIRST
Enter the no of process:4
Process no: 1
Enter burst time:6
Process no: 2
Enter burst time:8
Process no: 3
Enter burst time:7
Process no: 4
Enter burst time:3
PROCESS NO BURST TIME WAITING TIME TURN AROUND TIME
------------- ------------- ---------- --------------
4 3 0 3
1 6 3 9
3 7 9 16
2 8 16 24

Average Waiting time: 7.00


Average Turnaround Time: 13.00
------------------------
0 3 9 16 24

RESULT:
Thus the program was executed successfully.

32
EX.NO.5C
IMPLEMENTATION OF PRIORITY SCHEDULING
AIM:
To write a c program to implement PRIORITY scheduling.

ALGORITHM:

1. Start the program.


2. With Process number, burst time, turnaround time and waiting time and create object
for the structure
3. In main function get the number of processes and burst time for each processes.
4. Sort the process in ascending order with its Priority number along with burst time and
process number.
5. Calculate Waiting time and turnaround time as
 TURNARROUND TIME=WAITING TIME+BURST TIME.
6. Average waiting time and average turn around can be calculated by
 Average waiting time=sum of waiting time /No of process.
 Average Turnaround time= sum of Turnaround time/ No of processes.
7. Print Process number, Burst time, Waiting time and Turnaround time for each
processes and Average waiting and Turnaround time.
8. Terminate the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX 50
struct process
{
int pro;
int brt;
int tt;
int wt;
int pri;
}pr[MAX];

// Main program
int main()
{
int i,j,n,t,totwt,tottt;
float avgwt,avgtt;
int prevtt;
clrscr();
printf("\n\t\t\t PRIORITY SCHEDULING");
printf("\n\n Enter the no of process:");
scanf("%d",&n);
//Getting Process no. and Burst Time
for(i=1;i<=n;i++)
{
pr[i].pro = i;
printf("\nProcess no: %d ",pr[i].pro);

33
printf("\nEnter burst time:");
scanf("%d",&pr[i].brt);
printf("\nEnter Priority:");
scanf("%d",&pr[i].pri);
}

// Sorting the Priority in Ascending order


for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
if(pr[i].pri> pr[j].pri)
{
t= pr[j].pro;
pr[j].pro= pr[i].pro;
pr[i].pro=t;

t= pr[j].brt;
pr[j].brt= pr[i].brt;
pr[i].brt=t;

t= pr[j].pri;
pr[j].pri= pr[i].pri;
pr[i].pri=t;
}
}
}

//calculating Waiting time and Turn Aruond Time


prevtt =0;
for(i=1;i<=n;i++)
{
pr[i].wt=prevtt;
pr[i].tt=pr[i].wt+pr[i].brt;
prevtt = pr[i].tt;
}

//Sum of Waiting time and Turn Aruond Time


printf("\n PROCESS NO \t BURST TIME \t WAITING TIME \t TURN AROUND
TIME");
printf("\n ------------- \t ------------- \t---------- \t --------------");

totwt=0;
tottt=0;
for(i=1;i<=n;i++)
{
printf("\n\t%d\t\t%d\t\t%d\t\t%d",pr[i].pro,pr[i].brt,pr[i].wt,pr[i].tt);
totwt=totwt+pr[i].wt;
tottt=tottt+pr[i].tt;
}
34
//Average of Waiting time and Turn Aruond Time
avgwt=(float)totwt/n;
avgtt=(float)tottt/n;

printf("\n\n Average Waiting time:%6.2f",avgwt);


printf("\n\n Average Turnaround Time:%6.2f\n\n",avgtt);

// Top Line
for(i=1;i<=pr[n].tt;i++)
{
printf("-");
}
printf("\n");

//Gantt Chart
j=pr[1].wt;
printf("%d",j);
for(i=1;i<=n;i++)
{
printf("%*d",pr[i].brt,pr[i].tt);
}
printf("\n");

// Bottom Line
for(i=1;i<=pr[n].tt;i++)
{
printf("-");
}
printf("\n");
getch();
return 0;
}
OUTPUT:
PRIORITY SCHEDULING

Enter the no of process:5

Process no: 1
Enter burst time:10

Enter Priority:3

Process no: 2
Enter burst time:1

Enter Priority:1

Process no: 3
Enter burst time:2

35
Enter Priority:4

Process no: 4
Enter burst time:1

Enter Priority:5

Process no: 5
Enter burst time:5

Enter Priority:2

PROCESS NO BURST TIME WAITING TIME TURN AROUND TIME


------------- ------------- ---------- --------------
2 1 0 1
5 5 1 6
1 10 6 16
3 2 16 18
4 1 18 19

Average Waiting time: 8.20

Average Turnaround Time: 12.00

-------------------
01 6 161819
-------------------

RESULT:
Thus the program was executed successfully.

36
EX.NO.5D IMPLEMENTATION OF RR SCHEDULING

AIM:
To write a c program to implement Round Robin scheduling.

ALGORITHM:

1. Start the program.


2. Declare a structure with burst time, Process number,waiting time, and turnaround time
, and create Objects for that structure.
3. In main function get the number of processes , burst time,Arrival time for each
process and time slice.
4. Store the burst time in temporary variable array and total burst time in totbrt.
5. Execution of a process can be calculated by.
 Assign zero to a variable tottt and if it is equal to totbrt whole process is
finished.
 If burst time is equal to zero continue the process.
 If burst time for each process greater than time slice do:
 tottt= tottt+ ts.
 remtime=remtime –ts.
Else burst time less than ts and greater than zero
 tottt=tottt+remtime.
 remtime=0.
6. Waiting time and turnaround time can be calculated by
 waiting time=tottt-burst time.
 turnaround time=tottt.
7. Average waiting time and average turn around can be calculated by
 Average waiting time=sum of waiting time /No of process.
 Average Turnaround time= sum of Turnaround time/No of processes.
8. Print process number Burst time waiting time Turnaround time for each processes
and Average waiting and Turnaround time.
9. Terminate the program.

PROGRAM:

#include<stdio.h>
#include<conio.h>
#define MAX 50
struct process
{
int pro;
int brt;
int tt;
int wt;
int remtime;
}pr[MAX];

// Main program
void main()
{
37
int i,j,n,t,totwt,tottt;
float avgwt,avgtt;
int ts;
int totbrt;
printf("\n Enter the no of process:");
scanf("%d",&n);
printf("\nEnter the time slice:");
scanf("%d",&ts);
//Getting Process no. and Burst Time
totbrt = 0;
for(i=1;i<=n;i++)
{
printf("\nEnter process no: %d \n", i);
pr[i].pro = i;
printf("\nEnter burst time:");
scanf("%d",&pr[i].brt);
pr[i].remtime = pr[i].brt;
totbrt = totbrt + pr[i].brt;
}
//calculating Waiting time and Turn Around Time
tottt = 0;
while (1)
{
if(tottt == totbrt)
{
break;
}

for(i=1;i<=n;i++)
{
if(pr[i].remtime == 0)
{
continue;
}

if(pr[i].remtime > ts)


{
tottt = tottt + ts;
pr[i].remtime = pr[i].remtime - ts;
}
else
{
tottt = tottt + pr[i].remtime;
pr[i].remtime = 0;
}
pr[i].wt = tottt-pr[i].brt;
pr[i].tt = tottt;
}
}
//Sum of Waiting time and Turn Around Time
38
printf("\n PROCESS NO \t BURST TIME \t WAITING TIME \t TURN AROUND
TIME");
printf("\n ------------- \t ------------- \t---------- \t --------------");
totwt=0;
tottt=0;
for(i=1;i<=n;i++)
{
printf("\n\t%d\t\t%d\t\t%d\t\t%d",pr[i].pro,pr[i].brt,pr[i].wt,pr[i].tt);
totwt=totwt+pr[i].wt;
tottt=tottt+pr[i].tt;
}
//Average of Waiting time and Turn Around Time
avgwt=(float)totwt/n;
avgtt=(float)tottt/n;

printf("\n\n Average Waiting time:%6.2f",avgwt);


printf("\n\n Average Turnaround Time:%6.2f",avgtt);
getch();
}
}
OUTPUT:
Enter the no of process:
3

Enter the time slice:4


Enter process no: 1
Enter burst time:24
Enter process no: 2
Enter burst time:3
Enter process no: 3
Enter burst time:3

PROCESS NO BURST TIME WAITING TIME TURN AROUND TIME


------------- ------------- ---------- --------------
1 24 6 30
2 3 4 7
3 3 7 10

Average Waiting time: 5.67

Average Turnaround Time: 15.67

RESULT:
Thus the program was executed successfully.

39
EX.No.6 IMPLEMENTATION OF SEMAPHORE -DINING PHILOSOPHER'S PROBLEM

DATE:

AIM:
To write a c program to implement the Dining Philosopher problem using semaphore .

ALGORITHM:

1. Start the program.


2. Assign the number of philosopher‟s as 5 and initialize their state as thinking.
3. Display the menu and get the choice.
4. If choice is 1,Enter which philosopher want to eat, call take_sticks() function .
5. Call test() function to check the status of the neighbour philosopher and returns the value to
take_sticks() function and it returns state to the value f.
6. Depends on the value the print statement will work.
7. If choice is 2 , Enter which philosopher want to release the chopstick, call put_sticks()
function .
8. Call test() function to check the status of the neighbour philosopher and returns the value to
put_sticks() function and it returns state to the value f.
9. Depends on the value the print statement will work.
10. If choice is 3, then exit.
11. Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
#define N 5
#define LEFT (j-1)%N
#define RIGHT (j+1)%N
#define THINKING 0
#define HUNGRY 1
#define EATING 2

int state[N];
void test(int);
int lt, rt;

void main()
{
int f,ch=0,i,a,b;
int take_sticks(int);
int put_sticks(int);
clrscr();
printf("\n \t *** DINING PHILOSOPHER PROBLEM**\n");
printf("ENTER THE NUMBER OF PHILOSOPHER IN THE TABLE IS %d:",N);
40
printf("\n STATUS OF THE PHILOSOPHER:\n");
for(i=0;i<N;i++)
{
state[i]=THINKING;
printf("\n P%d IS THINKING",i);
}
do
{
printf("\n\t\t MENU\n\n");
printf("\n\t1.START EATING\n\n");
printf("\n\t2.STOP EATING\n\n");
printf("\n\t3.EXIT\n\n");
printf("ENTER YOUR CHOICE:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n ENTER THE PHILOSOPHER WHO IS GOING TO EAT:");
scanf("%d",&a);
f=take_sticks(a);
if(f==EATING)
{
printf("\n THE PHILOSOPHER HAS STARTED EATING...\n\n");
}
else
{
printf("\nTHE PHILOSOPHER IS HUNGRY!!..\n\n");
printf("\n THE CHOPSTICK IS ENGAGED\n\n");
}
for(i=0;i<N;i++)
{
if(state[i]==THINKING)
{
printf("\nP%d IS THINKING",i);
}
else if(state[i]==HUNGRY)
{
printf("\nP%d IS HUNGRY",i);
}
else
{
printf("\nP%d IS EATING",i);
}
} break;
41
case 2:
printf("\n ENTER THE PHILOSOPHER NUMBER TO RELEASE THE CHOPSTICK");
scanf("%d",&b);
if(state[b]==EATING)
{
f=put_sticks(b);
printf("\n THE PHILOSOPHER HAS STOPPED EATING!!..\n\n");
}
else
{
printf("\n THE PHILOSOPHER IS NOT EATING!!\n\n");
}
for(i=0;i<N;i++)
{
if(state[i]==THINKING)
{
printf("\nP%d IS THINKING",i);
}
else if(state[i]==HUNGRY)
{
printf("\nP%d IS HUNGRY",i);
}
else
{
printf("\nP%d IS EATING",i);
}
}
break;
case 3:
exit(0);
break;
}
}
while(ch!=3);
getch();
}

int take_sticks(int j)
{
state[j]=HUNGRY;
test(j);
return state[j];
}

42
int put_sticks(int j)
{
state[j]=THINKING;
if(j==0) test(N-1); else test(LEFT);
if(j==N-1) test(0); else test(RIGHT);
return state[j];
}

void test(int j)
{
if(j==0) rt = N-1; else rt = LEFT;
if(j==N-1) lt = 0; else lt = RIGHT;
if(state[j]==HUNGRY && state[lt]!=EATING && state[rt]!=EATING)
{
state[j]=EATING;
}
}
OUTPUT:

*** DINING PHILOSOPHER PROBLEM**


ENTER THE NUMBER OF PHILOSOPHER IN THE TABLE IS 5:
STATUS OF THE PHILOSOPHER:

P0 IS THINKING
P1 IS THINKING
P2 IS THINKING
P3 IS THINKING
P4 IS THINKING
MENU

1.START EATING
2.STOP EATING
3.EXIT

ENTER YOUR CHOICE:1

ENTER THE PHILOSOPHER WHO IS GOING TO EAT:1

THE PHILOSOPHER HAS STARTED EATING...

43
P0 IS THINKING
P1 IS EATING
P2 IS THINKING
P3 IS THINKING
P4 IS THINKING
MENU

1.START EATING
2.STOP EATING
3.EXIT

ENTER YOUR CHOICE:1

ENTER THE PHILOSOPHER WHO IS GOING TO EAT:3

THE PHILOSOPHER HAS STARTED EATING...

P0 IS THINKING
P1 IS EATING
P2 IS THINKING
P3 IS EATING
P4 IS THINKING
MENU

1.START EATING

2.STOP EATING

3.EXIT

ENTER YOUR CHOICE:1

ENTER THE PHILOSOPHER WHO IS GOING TO EAT:0

THE PHILOSOPHER IS HUNGRY!!..

THE CHOPSTICK IS ENGAGED

44
P0 IS HUNGRY
P1 IS EATING
P2 IS THINKING
P3 IS EATING
P4 IS THINKING
MENU

1.START EATING
2.STOP EATING
3.EXIT

ENTER YOUR CHOICE:2

ENTER THE PHILOSOPHER NUMBER TO RELEASE THE CHOPSTICK 1

THE PHILOSOPHER HAS STOPPED EATING!!..

P0 IS EATING
P1 IS THINKING
P2 IS THINKING
P3 IS EATING
P4 IS THINKING
MENU

1.START EATING
2.STOP EATING
3.EXIT

ENTER YOUR CHOICE: 3

RESULT:
Thus the program was executed successfully.

45
IMPLEMENT SHARED MEMORY AND IPC

EX NO: 7A INTERPROCESS COMMUNICATION USING PIPES

DATE:

AIM:
To write a program in C to implement interprocess communication using pipes.

/* fd is the file descriptor(accessing the file)


fd[0] – standard input
fd[1] – standard output
fd[2] – standard error
pipe- is a technique for passing information from one program process to another.
*/

ALGORITHM:
1. Start
2. Create the child process using fork().
3. create the pipe structure using pipe().
4. Now close the read end of the parent process using close().
5. Write the data in the pipe using write().
6. Now close the write end of the child process using close().
7. Read the data in the pipe using read ().
8. Display the string.
9. Stop.

PROGRAM:
#include<stdio.h>
int main()
{
int fd[2],child;
char a[10];
char b[10];
printf("\n Enter the string to enter into the pipe:");
scanf("%s",&a);
pipe(fd);
child=fork();
if(child>0)
{
write(fd[1],a,10);
}

46
else
{
read(fd[0],b,10);

printf("\n The string retrieved from the pipe is %s\n",b);


}
return 0;
}

OUTPUT:
Enter the string to enter into the pipe: Operating system
The string retrieved from the pipe is Operating system

RESULT:
Thus the program was executed successfully.

47
I
EX NO: 7B INTERPROCESS COMMUNICATION USING SHARED MEMORY

DATE:

AIM:
To write a program in C to implement interprocess communication using shared
memory.

ALGORITHM:
1. Start
2. Declare the variable for server program.
3. Using key,shmat,sgmid function to allocate the shared memory.
4. Declare the variable for client program.
5. Using key,shmat,sgmid function to allocate the shared memory for client
6. Print the value of shared memory client program.
7. Display the string.
8. Stop.

PROGRAM:Server Program:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#define SHMSIZE 25
void main()
{
char c;
int shmid;
key_t key;
char *shm ,*s;
key = 9647;
printf("\n\t SHARED MEMORY SERVER PROGRAM \n");
if((shmid = shmget(key,SHMSIZE,IPC_CREAT|0666))<0)
{
perror("\n SHARED MEMORY CREATE ERROR");
exit(0);
}
if((shm = shmat(shmid,0,0))==(char *) -1)
{
perror("\n SHARED MEMORY ALLOCATED ERROR");
exit(1);
}
s = shm;
for(c='A';c<='Z';c++)
{
*s++ = c;
*s = '\0';
}
48
exit(0);
}
Client Program:
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#define SHMSIZE 0
void main()
{
char c;
int shmid;
key_t key;
char *shm ,*s;
key = 9647;
printf("\n\t SHARED MEMORY CLIENT PROGRAM\n ");
if((shmid = shmget(key,SHMSIZE,IPC_CREAT|0666))<0)
{
perror("\n SHARED MEMORY CREATE ERROR");

exit(0);
} .
if((shm = shmat(shmid,0,0))==(char *) -1)
{
perror("\n SHARED MEMORY ALLOCATED ERROR");
exit(1);
}
for(s=shm;*s!='\0';s++)
{
printf("\t");
putchar(*s);
}
exit(0);
}

"cli_shamem.c" 30L, 696C written


[mca01@localhost ~]$ cc ser_shamem.c
[mca01@localhost ~]$ cc cli_shamem.c
[mca01@localhost ~]$ ./a.out

SHARED MEMORY CLIENT SERVER PROGRAM


A B C D E F G H I
J K L M N O P Q R S
T U V W X Y Z

[mca01@localhost ~]$

RESULT:
Thus the program was executed successfully.
49
EX.NO.8 IMPLEMENTATION OF BANKER’S ALGORITHM FOR
DATE: DEADLOCK AVOIDANCE

AIM:
To write a c program to implement BANKER‟ algorithm for Deadlock Avoidance.

ALGORITHM:

1. Start the program.


2. Get the number of processes and number of resources for each process.
3. Get the Allocated resources and maximum required resources for each process. Get
the total resource present.
4. Check whether the maximum resources is less than or equal to the total resource
present.

5. Calculate the available matrix.


6. Calculate the need matrix as follows:
Need= max-allocation
7. Check need matrix of each process is less than available resource, if so allocate the
process
Available =available+allocation
8. Else check with next process and do the same processing.
9. Finally if all process is allocated then conclude deadlock is avoided and print the safe
state of the process.
10. Else print deadlock occurred.
11. Stop the program.

PROGRAM:
#include<stdio.h>
#include<conio.h>
void matrix_get(int[5][5],int,int);

void main()
{
int max[5][5],all[5][5],total[1][5];
int avail[1][5],f[5],need[5][5],state[5];
int s,i,j,p,r,c,ch,ch1,k=0;
clrscr();
printf("\t\t DEADLOCK -BANKER'S ALGORITHM \n");
printf("ENTER THE NUMBER OF PROCESS:");
scanf("%d",&p);
ch=p;
printf("ENTER THE NUMBER OF RESOURCE TYPE:");
scanf("%d",&r);
printf("ENTER THE MAX MATRIX:\n");
matrix_get(max,p,r);
printf("\nENTER THE ALLOCATED MATRIX:\n");
50
matrix_get(all,p,r);
printf("ENTER THE TOTAL RESOURCE PRESENT:\n");
matrix_get(total,1,r);
for(i=0;i<r;i++)
{
for(j=0;j<p;j++)
{
if(max[j][i]>total[0][i]||all[j][i]>total[0][i])
{
printf("\nINPUT IS > TOTAL RESOURCE PRESENT\n");
exit(0);
}
}
s=total[0][i];
for(j=0;j<p;j++)
{
s=s-all[j][i];
}
avail[0][i]=s;
}

printf("\n\n AVAILABLE MATRIX \n\n");


for(i=0;i<r;i++)
{
printf("%d\t",avail[0][i]);
}
printf("\n\n NEED MATRIX:\n\n");
for(i=0;i<p;i++)
{
f[i]=0;
for(j=0;j<r;j++)
{
need[i][j]=max[i][j]-all[i][j];
if(need[i][j]<0)
{
need[i][j]=0;
}
printf("%d\t",need[i][j]);

}
printf("\n");
}
while(ch>0)
{
ch1=ch;
for(i=0;i<p;i++)
{

51
if(f[i]==0)
{
c=0;
for(j=0;j<r;j++)
{
if(need[i][j]<=avail[0][j])
{
c++;
}
}
if(c==r)
{
f[i]=1;
state[k++]=i;
ch--;
for(j=0;j<r;j++)
{
avail[0][j]=avail[0][j]+all[i][j];
need[i][j]=0;
}
}
}
}

if(ch==p)
{
printf("\n ALREADY DEADLOCK OCCURRED");
exit(0);
}

if(ch1==ch)
{
printf("\n ALLOCATION LEADS TO DEADLOCK");
exit(0);
}
}
printf("\n\n SAFE STATE S:{");

for(i=0;i<p;i++)
{
printf("P%d ",state[i]);
}
printf("}");

void matrix_get(int a[5][5],int p,int r)


{
int i,j;

52
for(i=0;i<p;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&a[i][j]);
}
}
}

OUTPUT:
DEADLOCK -BANKER'S ALGORITHM
ENTER THE NUMBER OF PROCESS:5
ENTER THE NUMBER OF RESOURCE TYPE:3
ENTER THE MAX MATRIX:
753
322
902
222
433

ENTER THE ALLOCATED MATRIX:


010
200
302
211
002
ENTER THE TOTAL RESOURCE PRESENT:
10 5 7

AVAILABLE MATRIX

3 3 2

NEED MATRIX:

7 4 3
1 2 2
6 0 0
0 1 1
4 3 1

SAFE STATE S:{P1 P3 P4 P0 P2 }

RESULT:
Thus the program was executed successfully.

53
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 in 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:

//Deadlock Detection algorithm implementation


#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);
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++)
{

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

55
OUTPUT:
Enter total no. of processes : 4
Enter total no. of resources : 5
Enter claim (Max. Need) matrix :
01001
00101
00001
10101
Enter allocation matrix :
10110
11000
00010
00000
Enter resource vector (Total resources) :
21121
Enter availability vector (available resources) :
00001
deadlock causing processes are : 2 3

RESULT:

Thus the program was executed successfully.

56
EX.NO: 10 THREADING & SYNCHRONIZATION
DATE:

AIM:
To write a c program to implement threading and synchronization.

ALGORITHM:
Step 1: Start the Program
Step 2: Obtain the required data through char and in 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 CODING:

#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;
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;
}

RESULT:
Thus the program was executed successfully.

57
EX.NO: 11 IMPLEMENTATION OF THE FOLLOWING MEMORY
ALLOCATION METHODS FIXED PARTITION FIRST FIT &
BEST FIT MEMORY MANAGEMENT

DATE:

AIM:

To implement first fit, best fit algorithm for memory management.

ALGORITHM:
1. Start the program.

2. Get the segment size, number of process to be allocated and their corresponding size.

3. Get the options. If the option is „2‟ call first fit function.

4. If the option is „1‟ call best fit function. Otherwise exit.

5. For first fit, allocate the process to first possible segment which is free and set the personnel
slap as „1‟. So that none of process to be allocated to segment which is already allocated and vice
versa.

6. For best fit, do the following steps,.

7. Sorts the segments according to their sizes.

8. Allocate the process to the segment which is equal to or slightly greater than the process size
and set the flag as the „1‟ .So that none of the process to be allocated to the segment which is
already allocated and vice versa. Stop the program.

9. Stop the program

58
PROGRAM:
#include<stdio.h>
#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\tMemory Management Scheme - First Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);}
for(i=1;i<=nf;i++)
{ for(j=1;j<=nb;j++){
if(bf[j]!=1) //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();
}

59
OUTPUT:
Enter the number of blocks: 3
Enter the number of files: 2
Enter the size of the blocks:-
Block 1: 5
Block 2: 2
Block 3: 7
Enter the size of the files:-
File 1: 1
File 2: 4 File File Size Block No Block Size Fragment
No
1 1 3 7 6
2 4 1 5 1

RESULT:
Thus the program was executed successfully.

60
EX.NO:12 MEMORY MANAGEMENT SCHEME – PAGING

DATE:

AIM:
To implement the memory management using paging concept.

ALGORITHM:

1. Start
2. Declare the variables.
3. Get the number of blocks in memory.
4. Get the size of each block.
5. Get the number of jobs and size of jobs.
6. If the size of the process is greater than the available pages then display error
message.
7. If the size of the process is lesser than the available pages then allocate the block.
8. Display the output.
9. Stop.

PROGRAM:

#include<stdio.h>
int main()
{
int nb,sb,nj,i,j;
int js[10];
printf("Number of blocks in memory :");
scanf("%d",&nb);
printf("Size of Each block:");
scanf("%d",&sb);
printf("Number of jobs :");
scanf("%d",&nj);
for(j=1;j<=nj;j++)
{
printf("Size of job %d:", j);
scanf("%d",&js[j]);
}
j=1;
for(i=1;i<=nb;i++)
{
printf("job %d stored in memory block %d\n ", j,i);
js[j] = js[j] - sb;
if(js[j] <= 0)
{
j++;
}

61
if(j > nj)
{
break;
}
}
if( i > nb)
{
printf("Out of memory");
}
return 0;
}

OUTPUT:

[itstu001@localhost ~]$ cc me.c


[itstu001@localhost ~]$ ./a.out
Number of blocks in memory :2
Size of Each block:50
Number of jobs :3
Size of job 1:10
Size of job 2:20
Size of job 3:10
job 1 stored in memory block 1
job 2 stored in memory block 2
Out of memory[itstu001@localhost ~]$

RESULT:
Thus the program was executed successfully.

62
EX.NO.13 PAGE REPLACEMENT ALGORITHM

AIM :
To write a C program to implement the following page replacement algorithms
1)FIFO
2)LRU
3)OPTIMAL

13A. FIFO PAGE REPLACEMENT ALGORITHM

ALGORITHM:

1: Start
2: Get the number of frames, reference string and the number of elements in the reference
string using getdata() function.
3: Using fifo() function insert the pages into the frames and using search() function check
whether the page is already exist in the frame.
4: In the fifo() function check whether the page fault occurs or not using fifo replacement
algorithm.
5: Print the number of hits and number of miss.
6: Stop.

PROGRAM
#include<stdio.h>
#include<conio.h>
int nf;
int ne;
int hit,miss;
int ref[50];
int fr[15];
void getdata();
void fifo();

void getdata()
{
int i;
printf("\nEnter the number of frames:");
scanf("%d",&nf);
printf("\nEnter the number of elements in the reference string:\n");
scanf("%d",&ne);
printf("\nEnter the reference string:\n");
for(i=0;i<ne;i++)
{
scanf("%d",&ref[i]);
}
}

void fifo()
{

63
int i,j,found=0,rear=-1;
miss=hit=0;
int search(int);
for(i=0;i<nf;i++)
{
fr[i]=-1;
}
for(i=0;i<ne;i++)
{
printf("\nThe no to be inserted :%d",ref[i]);
found=search(ref[i]);
if(found==0)
{
miss++;
if(rear==nf-1)
{
rear=-1;
}
rear++;
fr[rear]=ref[i];
}
else
{
hit++;
}
printf("\n");
for(j=0;j<nf;j++)
printf("%d ",fr[j]);
}
printf("\n\n No. of page faults=%d\n",miss);
printf("\n No. of Hits=%d",hit);
}
int search(int item)
{
int i;
for(i=0;i<nf;i++)
{
if(fr[i]==item)
{
return(1);
}
}
return 0;
}
int main()
{
printf("\n\t\t\t FIFO PAGE REPLACEMENT");
getdata();
printf("\t\t\t FIFO PAGE REPLACEMENT");
fifo();

} 64
OUTPUT:

FIFO PAGE REPLACEMENT


Enter the number of frames:3

Enter the number of elements in the reference string:


5

Enter the reference string:


1
2
3
4
2
FIFO PAGE REPLACEMENT
The no to be inserted :1
1 -1 -1
The no to be inserted :2
1 2 -1
The no to be inserted :3
123
The no to be inserted :4
423
The no to be inserted :2
423

No. of page faults=4

No. of Hits=1

RESULT:
Thus the program was executed successfully.

65
13B. LRU PAGE REPLACEMENT ALGORITHM

AIM :
To write a C program to implement the following page replacement algorithms.
1)FIFO
2)LRU
3)OPTIMAL

ALGORITHM:
1: Start
2: Get the number of frames, reference string and the number of elements in the reference
string using getdata() function.
3: Using lru() function insert the pages into the frames and using search() function check
whether the page is already exist in the frame.
4: In the lru() function check whether the page fault occurs or not using lru replacement
algorithm.
5: Print the number of page faults.
6: Stop.

PROGRAM:
#include<stdio.h>
int nf;
int i,ne;
int miss=0;
int ref[50];
int fr[15];
void getdata();
void lru();

void getdata()
{
printf("\nEnter the number of frames:");
scanf("%d",&nf);
printf("\nEnter the number of elements in the reference string:\n");
scanf("%d",&ne);
printf("\nEnter the reference string:\n");
for(i=0;i<ne;i++)
{
scanf("%d",&ref[i]);
}
}
void lru()
{
int check,j,k;
int count=0,index[5];
printf("\n\n Simulation of LRU page replacement technique!...........\n");

66
for(i=0;i<nf;i++)
{
fr[i]=-1;
}

for(i=0;i<ne;i++)
{
check=0;
for(j=0;j<nf;j++)
{
if(fr[j]==ref[i])
{
check=1;
}
}

if(check==0)
{
miss+=1;
if(count<nf)
{
fr[count++] = ref[i];
}
else
{
for(j=0;j<i;j++)
{
for(k=0;k<nf;k++)
{
if(ref[j]==fr[k])
{
index[k] = j;
}
}
}

for(j=0;j<nf;j++)
{
if(index[check]>index[j])
{
check=j;
}
}
fr[check]=ref[i];
}
printf("\n");
for(j=0;j<nf;j++)
{
printf("%d\t",fr[j]);
}
}
67
}
printf("\n Number of page faults:%d",miss);
}
void main()
{
printf("\n\t\t\t LRU PAGE REPLACEMENT");
getdata();
printf("\t\t\t LRU PAGE REPLACEMENT");
lru();
}

OUTPUT:

LRU PAGE REPLACEMENT


Enter the number of frames:3

Enter the number of elements in the reference string:


6

Enter the reference string:


1
2
3
4
2
1
LRU PAGE REPLACEMENT

Simulation of LRU page replacement technique!...........

1 -1 -1
1 2 -1
1 2 3
4 2 3
4 2 1
Number of page faults:5

RESULT:
Thus the program was executed successfully.

68
13C. OPTIMAL PAGE REPLACEMENT ALGORITHM
AIM :
To write a C program to implement the following page replacement algorithms.
1)FIFO
2)LRU
3)OPTIMAL

ALGORITHM:
1: Start
2: Read total number of pages in reference string
3: Read total number of frames
4: Read number of page faults if all the condition satisfies the following statements are
displayed
5: Replacement stratergies are efficient
6: Optimal page replacement stratergy is efficient
7: End

PROGRAM:

#include<stdio.h>
#include<conio.h>
int fr[100],n;
void main()
{
void display();
int page[100],pages,p,i,j,fs[3];
int max,found=0,lg[3],index,k,l,flag1=0,flag2=0,pf=0;
clrscr();
printf("\n Enter total number of frames :\n");
scanf("%d",&n);
printf("\n Enter the total number of page reference string :\n");
scanf("%d",&pages);
for(i=0;i<n;i++)
{
fr[i]=-1;
}
printf("\nEnter the page reference string :");
for(i=0;i<pages;i++)
{
scanf("%d",&p);
page[i]=p;
}
for(j=0;j<pages;j++)
{
flag1=0;
flag2=0;
for(i=0;i<n;i++)
{
if(fr[i]==page[j])
{ 69
flag1=1;
flag2=1;
break;
}
}
if(flag1==0)
{
for(i=0;i<n;i++)
{
if(fr[i]==-1)
{
fr[i]=page[j];
flag2=1;
pf++;
break;
} } }
if(flag2==0)
{
for(i=0;i<n;i++)
{ lg[i]=0;
}
for(i=0;i<n;i++)
{
for(k=j+1;k<pages;k++)
{
if(fr[i]==page[k])
{
lg[i]=k-j;
break;
}
}
}
found=0;
for(i=0;i<n;i++)
{
if(lg[i]==0)
{
index=i;
found=1;
break;
}
}
if(found==0)
{
max=lg[0];
index=0;
for(i=1;i<n;i++)
{
if(max<lg[i])
{
max=lg[i];
70
index=i;
} } }
fr[index]=page[j];
pf++;
}
display();
}
printf("\n no of page faults:%d",pf);
getch();
}
void display()
{
int i;
printf("\n");
for(i=0;i<n;i++)
printf("\t%d",fr[i]);
}
OUTPUT:
Enter total number of frames :
3
Enter the total number of page reference string :
20
Enter the page reference string :
70120304230321201701

7 -1 -1
7 0 -1
7 0 1
2 0 1
2 0 1
2 0 3
2 0 3
2 4 3
2 4 3
2 4 3
2 0 3
2 0 3
2 0 3
2 0 1
2 0 1
2 0 1
2 0 1
7 0 1
7 0 1
7 0 1
no of page faults:9

RESULT:
Thus the program was executed successfully.

71
EX NO: 15a FILE ALLOCATION METHODS

SEQUENTIAL FILE ALLOCATION


DATE:

AIM:
To write a program in C for contiguous or sequential file allocation.

ALGORITHM:

1. Start
2. Declare the variables.
3. Get the number of files.
4. Get the number of blocks for file.
5. Allocate the blocks for file depending on length.
6. Finally display the result.
7. Stop

PROGRAM:
#include<stdio.h>
int main()
{
int i,j,n,block[20],start;
printf("Enter the no. of file : ");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
printf("Enter the number of blocks needed for file %d: ", i);
scanf("%d",&block[i]);
}
start=0;
for(i=1;i<=n;i++)
{
printf("File %d Start %d Size %d\n",i,start,block[i]);
start=start+block[i];
}
}
OUTPUT:
"con.c" 22L, 314C written
[exam100@localhost ~]$ cc con.c
[exam100@localhost ~]$ ./a.out
Enter the no. of file : 2
Enter the number of blocks needed for file 1: 3
Enter the number of blocks needed for file 2: 2
File 1 Start 0 Size 3
File 2 Start 3 Size 2
[exam100@localhost ~]$

RESULT:
Thus the program was executed successfully.
72
EX NO: 15B INDEXED FILE ALLOCATION

AIM:
To write a program in C for Indexed file allocation.

ALGORITHM:

1. Start
2. Declare the variables.
3. Get the number of blocks are already allocated.
4. Enter the allocated block numbers.
5. Give the starting index block & length.
6. Finally display the result.
7. Stop

PROGRAM:
#include<stdio.h>
#include<conio.h>
main()
{
int f[50],i,n,st,len,k;

for(i=0;i<50;i++)
{
f[i]=1;
}
printf("How many blocks are already allocated ?");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the allocated block numbers ");
scanf("%d",&k);
f[k]=0;
}
printf("Enter the starting index block & length");
scanf("%d %d",&st,&len);

i=0;
k=st;
while(i<len)
{
if(f[k]==1)
{
f[k]=0;
printf("\n %d-> file allocating",k);
i++;
}
else
{
printf("\n %d->file is already allocated",k);
}
k++;
}}
73
OUTPUT:

"pc.c" 41L, 480C written


[exam100@localhost ~]$ cc pc.c
[exam100@localhost ~]$ ./a.out
How many blocks are already allocated ?2

Enter the allocated block numbers 2

Enter the allocated block numbers 4


Enter the starting index block & length0 4

0-> file allocating


1-> file allocating
2->file is already allocated
3-> file allocating
4->file is already allocated
5-> file allocating[exam100@localhost ~]$

RESULT:
Thus the program was executed successfully.

74
EX.NO :15C LINKED FILE ALLOCATION
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: Get the number of files.
Step 3: Allocate the required locations by selecting a location randomly
Step 4: Check whether the selected location is free.
Step 5: If the location is free allocate and set flag =1 to the allocated locations.
Step 6: Print the results file no, length, blocks allocated.
Step 7: Stop the execution

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

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

RESULT :
Thus the program was executed successfully.

76

You might also like