0% found this document useful (0 votes)
15 views34 pages

LAB MANUAL - OS - 2021 Regulation Final

The document provides an overview of Unix commands and shell programming fundamentals, including command usage for file manipulation, directory navigation, and system information retrieval. It also covers shell scripting basics, decision-making, loops, and examples of simple scripts for various tasks. Additionally, it discusses process scheduling with a focus on First Come First Serve (FCFS) scheduling, highlighting its characteristics and inefficiencies.

Uploaded by

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

LAB MANUAL - OS - 2021 Regulation Final

The document provides an overview of Unix commands and shell programming fundamentals, including command usage for file manipulation, directory navigation, and system information retrieval. It also covers shell scripting basics, decision-making, loops, and examples of simple scripts for various tasks. Additionally, it discusses process scheduling with a focus on First Come First Serve (FCFS) scheduling, highlighting its characteristics and inefficiencies.

Uploaded by

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

3

Aim
To study and execute Unix commands.

Login
Type telnet in run window.
User has to authenticate himself by providing and . Once verified, a greeting and $
prompt appears. The shell is now ready to receive commands from the user. Options suffixed with a
hyphen ( ) and arguments are separated by space.

General commands

Command Function
Date Used to display the current system date and time.
date +%D Displays date only
date +%T Displays time only
date +%Y Displays the year part of date
date +%H Displays the hour part of time
Cal Calendar of the current month
cal Displays calendar for all months of the specified year
cal Displays calendar for the specified month of the year
Who Login details of all users such as their IP, Terminal No, User name,
who am i Used to display the login details of the user
Uname Displays the Operating System
uname r Shows version number of the OS (kernel).
uname n Displays domain name of the server
echo$HOME Displays the user's home directory
Bc Basic calculator. Press Ctrl+dto quit
lp Allows the user to spool a job along with others in a print queue.
man Manual for the given command. Press qto exit
history To display the commands used by the user since log on.
exit Exit from a process. If shell is the only process then logs out

Directory commands

Command Function
Pwd Path of the present working directory
mkdir A directory is created in the given name under the current directory
mkdir A number of sub-directories can be created under one stroke
cd Change Directory. If the starts with / then path starts from
root (absolute) otherwise from current working directory.
cd To switch to the home directory.
cd / To switch to the root directory.
cd .. To move back to the parent directory
rmdir Removes an empty sub-directory.
4

File commands

Command Function
cat > To create a file with some contents. To end typing press Ctrl+d. The >
symbol means redirecting output to a file. (< for input)
cat Displays the file contents.
cat>> Used to append contents to a file
cp Copy files to given location. If already exists, it will be overwritten
cp i Warns the user prior to overwriting the destination file
cp r Copies the entire directory, all its sub-directories and files.
mv To rename an existing file or directory. i option can also be used
mv To move a group of files to a directory.
mv v Display name of each file as it is moved.
rm Used to delete a file or group of files. i option can also be used
rm * To delete all the files in the directory.
rm r * Deletes all files and sub-directories
rm f * To forcibly remove even write-protected files
Ls Lists all files and subdirectories (blue colored) in sorted manner.
ls To check whether a file or directory exists.
ls * Short-hand notation to list out filenames of a specific pattern.
ls a Lists all files including hidden files (files beginning with .)
ls x To have specific listing of a directory.
ls R Recursive listing of all files in the subdirectories
ls l Long listing showing file access rights (read/write/execute-rwx for
user/group/others-ugo).
cmp Used to compare two files. Displays nothing if files are identical.
wc It produces a statistics of lines (l), words(w), and characters(c).
chmod Changes permission for the specified file. (r=4, w=2, x=1)
chmod 740 sets all rights for user, read only for groups and no rights
for others

The commands can be combined using the pipeline (|) operator. For example, number of users
logged in can be obtained as.

who | wc -l

Finally to terminate the unix session execute the command exit or logout.

Output

$ date
Sat Apr 9 13:03:47 IST 2011

$ date +%D
04/09/11

$ date +%T
13:05:33
5

$ date +%Y
2011

$ date +%H
13

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

$ who
root :0 Apr 9 08:41
vijai pts/0 Apr 9 13:00 (scl-64)
cse4001 pts/3 Apr 9 13:18 (scl-41.smkfomra.com)

$ uname
Linux

$ uname -r
2.4.20-8smp

$ uname -n
localhost.localdomain

$ echo $HOME
/home/vijai

$ echo $USER
vijai

$ bc
3+5
8

$ pwd
/home/vijai/shellscripts/loops

$ mkdir filter
$ ls
filter list.sh regexpr shellscripts

$ cd shellscripts/loops/
6

$ cd
$

$ cd /
[vijai@localhost /]$

[vijai@localhost /]$ cd /home/vijai/shellscripts/loops/


$ cd ..
[vijai@localhost shellscripts]$

$ rmdir filter
$ ls
list.sh regexpr shellscripts

$ cat > greet


hi cse
wishing u the best

$ cat greet
hi ece-a
wishing u the best

$ cat >> greet


bye
$ cat greet
hi cse
wishing u the best bye

$ ls
greet list.sh regexpr shellscripts

$ ls -a
. .bash_logout .canna .gtkrc regexpr .viminfo.tmp
.. .bash_profile .emacs .kde shellscripts .xemacs
.bash_history .bashrc greet list.sh .viminfo

$ ls -l
-rw-rw-r-- 1 vijai vijai 32 Apr 11 14:52 greet
-rw-rw-r-- 1 vijai vijai 30 Apr 4 13:58 list.sh
drwxrwxr-x 2 vijai vijai 4096 Apr 9 14:30 regexpr

$ cp greet ./regexpr/
$ ls
greet list.sh regexpr shellscripts
$ ls ./regexpr
7

demo greet

$ cp -i greet ./regexpr/
cp: overwrite 'greet'? n

$ mv greet greet.txt
$ ls
greet.txt list.sh regexpr shellscripts

$ mv greet.txt ./regexpr/
$ ls
list.sh regexpr shellscripts

$ rm -i *.sh
rm: remove regular file 'fact.sh'? y rm: remove regular
file 'prime.sh'?y
$ ls
list.sh regexpr shellscripts

$ wc list.sh
4 9 30 list.sh
$ wc -l list.sh
4 list.sh

$ cmp list.sh fact.sh


list.sh fact.sh differ: byte 1, line 1

$ ls -l list.sh
-rw-rw-r-- 1 vijai vijai 30 Apr 4 13:58 list.sh

$ chmod ug+x list.sh

$ ls -l list.sh
-rwxrwxr-- 1 vijai vijai 30 Apr 4 13:58 list.sh
$ chmod 740 list.sh
$ ls -l list.sh
-rwxr----- 1 vijai vijai 30 Apr 4 13:58 list.sh

Result
Thus the study and execution of Unix commands has been completed successfully.
8

Exp. No. 2 Shell Programming


Date:

Aim
To write simple shell scripts using shell programming fundamentals.

The activities of a shell are not restricted to command interpretation alone. The shell also has
rudimentary programming features. Shell programs are stored in a file (with extension .sh). Shell
programs run in interpretive mode. The original UNIX came with the Bourne shell (sh) and it is universal
even today. C shell (csh) and Korn shell (ksh) are also widely used. Linux offers Bash shell (bash) as a
superior alternative to Bourne shell.

Preliminaries
1. Comments in shell script start with #.
2. Shell variables are loosely typed i.e. not declared. Variables in an expression or output must be
prefixed by $.
3. The read statement is shell's internal tool for making scriptsinteractive.
4. Output is displayed using echostatement.
5. Expressions are computed using the exprcommand. Arithmetic operators are + -
* / %. Meta characters * ( ) should be escaped with a \.
6. The shell scripts are executed
$ sh

Decision-making
Shell supports decision-making using if statement. The if statement like its counterpart in
programming languages has the following formats.

if [ ] then if [ ] then if [ ] then

fi else elif [ ] then

fi
else

fi
9

The set of relational operators are –eq –ne –gt –ge –lt –le and logical operators used in conditional
expression are –a –o !

Multi-way branching
The case statement is used to compare a variables value against a set of constants. If it matches a
constant, then the set of statements followed after ) is executed till a ;; is encountered. The optional
block is indicated by *. Multiple constants can be specified in a single pattern separated by |.

case in
)
;;
)
;;

*)

esac

Loops
Shell supports a set of loops such as for, while and until to execute a set of statements
repeatedly. The body of the loop is contained between do and done statement. The for

loop doesn't test a condition, but uses a list instead.

for in
do

done

The while loop executes the as long as the condition remains true.
while [ ]
do

done

The until loop complements the while construct in the sense that the are executed as long as
the condition remains false.
until [ ] do

done
10

A) Swapping values of two variables


# Swapping values – swap.sh
echo –n "Enter value for A : "
read a
echo –n "Enter value for B : "
read b
t=$a
a=$b
b=$t
echo "Values after Swapping"
echo "A Value is $a and B Value is $b"

Output
$ sh swap.sh
Enter value for A : 12
Enter value for B : 23
Values after Swapping
A Value is 23 and B Value is 12

B) Farenheit to Centigrade Conversion


# Degree conversion – degconv.sh
echo -n "Enter Fahrenheit : "
read f
c=`expr \( $f - 32 \) \* 5 / 9` echo
"Centigrade is : $c"

Output
$ sh degconv.sh
Enter Fahrenheit : 213
Centigrade is : 100

C) Biggest of 3 numbers
# Biggest – big3.sh
echo -n "Give value for A B and C: "
read a b c
if [ $a -gt $b -a $a -gt $c ] then
echo "A is the Biggest number"
elif [ $b -gt $c ]
then
echo "B is the Biggest number"
else
echo "C is the Biggest number"
fi

Output
$ sh big3.sh
Give value for A B and C: 4 3 7
C is the Biggest number
11

D) Grade Determination
# Grade – grade.sh
echo -n "Enter the mark : "
read mark
if [ $mark -gt 90 ]
then
echo "S Grade" elif [ $mark -gt 80 ]
then
echo "A Grade" elif [ $mark -gt 70 ]
then
echo "B Grade" elif [ $mark -gt 60 ]
then
echo "C Grade" elif [ $mark -gt 55 ]
then
echo "D Grade" elif [ $mark -ge 50 ]
then
echo "E Grade" else
echo "U Grade"
fi

Output
$ sh grade.sh Enter the mark :
65 C Grade

E) Vowel or Consonant

# Vowel - vowel.sh
echo -n "Key in a lower case character : "
read choice
case $choice in a|e|i|o|u)
echo "It's a Vowel";;
*) echo "It's a Consonant"
esac

Output
$ sh vowel.
Key in a lower case character : e It's a Vowel
12

F) Simple Calculator

# Arithmetic operations calc.sh


echo -n "Enter the two numbers : "
read a b
echo " 1. Addition"
echo " 2. Subtraction"
echo " 3. Multiplication"
echo " 4. Division"
echo -n "Enter the option : "
read option
case $option in
1) c=`expr $a + $b` echo "$a + $b =
$c";;
2) c=`expr $a - $b` echo "$a - $b =
$c";;
3) c=`expr $a \* $b` echo "$a * $b =
$c";;
4) c=`expr $a / $b` echo "$a / $b =
$c";;
*) echo "Invalid Option" esac

Output
$ sh calc.sh
Enter the two numbers : 2 4
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter the option : 1 2 + 4 = 6

G) Multiplication Table
# Multiplication table multable.sh clear
echo -n "Which multiplication table? : "
read n
for x in 1 2 3 4 5 6 7 8 9 10 do
p=`expr $x \* $n`
echo -n "$n X $x = $p" sleep 1
done

Output
$ sh multable.sh
Which multiplication table? : 6 6 X 1 = 6
6 X 2 = 12
.....
13

H) Number Reverse
# To reverse a number reverse.sh
echo -n "Enter a number : "
read n rd=0
while [ $n -gt 0 ] do
rem=`expr $n % 10` rd=`expr $rd \* 10 +
$rem` n=`expr $n / 10`
done
echo "Reversed number is $rd"

Output
$ sh reverse.sh
Enter a number : 234 Reversed
number is 432

I) Prime Number
# Prime number prime.sh echo -n "Enter the
number : " read n
i=2
m=`expr $n / 2` until [ $i -gt $m
] do
q=`expr $n % $i` if [ $q -
eq 0 ] then
echo "Not a Prime number" exit
fi
i=`expr $i + 1` done
echo "Prime number"

Output
$ sh prime.sh
Enter the number : 17 Prime number

Result
Thus shell scripts were executed using different programming constructs
30

EXP. NO. 4A FCFS SCHEDULING


Date:

Aim

To schedule snapshot of processes queued according to FCFS scheduling.

Process Scheduling
➢ CPU scheduling is used in multiprogrammed operating systems.
➢ By switching CPU among processes, efficiency of the system can be improved.
➢ Some scheduling algorithms are FCFS, SJF, Priority, Round-Robin, etc.
➢ Gantt chart provides a way of visualizing CPU scheduling and enables to understand better.

First Come First Serve (FCFS)


➢ Process that comes first is processed first
➢ FCFS scheduling is non-preemptive
➢ Not efficient as it results in long average waiting time.
➢ Can result in starvation, if processes at beginning of the queue have long bursts.

Algorithm
1. Define an array of structure process with members pid, btime, wtime & ttime.
2. Get length of the ready queue, i.e., number of process (say n)
3. Obtain btime for each process.
4. The wtime for first process is 0.
5. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
6. Compute average waiting time awat and average turnaround time atur
7. Display the btime, ttime and wtime for each process.
8. Display GANTT chart for the above scheduling
9. Display awat time and atur
10. Stop
31

Program

/* FCFS Scheduling - fcfs.c */ #include

#include<stdio.h>

struct process

{
int pid; int
btime; int
wtime; int ttime;
} p[10];

main()
{
int i,j,k,n,ttur,twat;
float awat,atur;
printf("Enter no. of process : ");
scanf("%d", &n);
for(i=0; i<n; i++)
{
printf("Burst time for process P%d (in ms) : ",(i+1));
scanf("%d", &p[i].btime);
p[i].pid = i+1;
}
p[0].wtime = 0;
for(i=0; i<n; i++)
{
p[i+1].wtime = p[i].wtime + p[i].btime;
p[i].ttime = p[i].wtime + p[i].btime;
}
ttur = twat = 0;
for(i=0; i<n; i++)
{
ttur += p[i].ttime;
twat += p[i].wtime;
}
awat = (float)twat / n;
atur = (float)ttur / n;

printf("\nFCFS Scheduling\n\n");
for(i=0; i<28; i++)
printf("-");
printf("\nProcess B-Time T-Time W-Time\n");
for(i=0; i<28; i++)
printf("-");
for(i=0; i<n; i++)
printf("\nP%d\t%4d\t%3d\t%2d", p[i].pid,p[i].btime,p[i].ttime,p[i].wtime);
printf("\n");
for(i=0; i<28; i++)
printf("-");

printf("\n\nAverage waiting time: %5.2fms", awat);


printf("\nAverage turn around time : %5.2fms\n", atur);

printf("\n\nGANTT Chart\n"); printf("-");


for(i=0; i<(p[n-1].ttime + 2*n); i++)
32

printf("-");
printf("\n");
printf("|"); for(i=0; i<n; i++)
{
k = p[i].btime/2;
for(j=0; j<k; j++)
printf(" ");
printf("P%d",p[i].pid);
for(j=k+1; j<p[i].btime; j++)
printf(" ");
printf("|");
}
printf("\n");
printf("-");
for(i=0; i<(p[n-1].ttime + 2*n); i++)
printf("-");
printf("\n");
printf("0"); for(i=0; i<n; i++)
{
for(j=0; j<p[i].btime; j++)
printf(" ");
printf("%2d",p[i].ttime);
}
}
Output

Enter no. of process : 4


Burst time for process P1 (in ms) : 10 Burst time for process P2
(in ms) : 4 Burst time for process P3 (in ms) : 11 Burst time for
process P4 (in ms) : 6

FCFS Scheduling

Process B-Time T-Time W-Time

P1 10 10 0
P2 4 14 10
P3 11 25 14
P4 6 31 25

Average waiting time : 12.25ms


Average turn around time : 20.00ms

GANTT Chart

| P1 | P2 | P3 | P4 |

0 10 14 25 31

Result

Thus waiting time & turnaround time for processes based on FCFS scheduling was computed
and the average waiting time was determined.
46

Exp.5: Illustrate the inter process communication strategy


5(a) Interprocess Communication using pipe

Aim : To implement inter process communication using pipe command.

Algorithm :
1. Start
2.Create a child and parent using fork()
3.Allow communication between both the process
4.Stop

Program :

#include<stdio.h>
main()
{
int p[2],pid,pid1;
char msg[25],msg1[25];
pipe(p);
pid=fork();
if(pid!=0)
{
sleep(2);
read(p[0],msg1,21);
printf(“%s”,msg1);
}
else
{
pid1=fork();
if(pid1!=0);
{
sleep(1);
read(p[0],msg1,21);
write(p[1],”Grand child says hello”,21);
}
else
write(p[1],”Says hello to grandpa”,29);
}
}
Sample Output;
Says hello to grandpaX@
47

5(b) Interprocess Communication Using Shared Memory

/*parent_child.c */
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(void)
{
int shmid;
char *shmPtr;
int n;
if (fork( ) == 0)
{
sleep(5); /* UUPS */
if( (shmid = shmget(2041, 32, 0)) == -1 )
{
exit(1);
}
shmPtr = shmat(shmid, 0, 0);
if (shmPtr == (char *) -1)
exit(2);
printf ("\nChild Reading.... \n\n");
for (n = 0; n < 26; n++)
putchar(shmPtr[n]);
putchar('\n'); }
else
{
if( (shmid = shmget(2041, 32, 0666 | IPC_CREAT)) == -1 )
{
exit(1);
}
shmPtr = shmat(shmid, 0, 0);
if (shmPtr == (char *) -1)
exit(2);
for (n = 0; n < 26; n++)
shmPtr[n] = 'a' + n;
printf ("Parent Writing .... \n\n") ;
for (n = 0; n < 26; n++)
putchar(shmPtr[n]);
putchar('\n'); wait(NULL);
shmdt(NULL);
if( shmctl(shmid, IPC_RMID, NULL) == -1 )
{
perror("shmctl");
48

exit(-1);
}
}
exit(0);
}

Sample Output:
Parent Writing ....
abcdefghijklmnopqrstuvwxyz

Parent Reading ....


abcdefghijklmnopqrstuvwxyz

Result

Thus the implementation of interprocess communication using share memory has been demonstrated.
49

Exp. No. 6 Implementation mutual exclusion by semaphore


Date:

Aim

To demonstrate the utility of semaphore in synchronization and multithreading.

Semaphore
➢ The POSIX system in Linux has its own built-in semaphore library.
➢ To use it, include semaphore.h.
➢ Compile the code by linking with -lpthread -lrt.
➢ To lock a semaphore or wait, use the sem_wait function.
➢ To release or signal a semaphore, use the sem_post function.
➢ A semaphore is initialised by using sem_init(for processes or threads)
➢ To declare a semaphore, the data type is sem_t.

Algorithm
1. 2 threads are being created, one 2 seconds after the first one.

2. But the first thread will sleep for 4 seconds after acquiring the lock.

3. Thus the second thread will not enter immediately after it is called, it will enter 4 – 2
= 2 secs after it is called.
4. Stop.

Program

/* C program to demonstrate working of Semaphores */

#include <stdio.h>
#include <pthread.h> #include
<semaphore.h> #include <unistd.h>

sem_t mutex;

void* thread(void* arg)


{
//wait sem_wait(&mutex);
printf("\nEntered..\n");

//critical section sleep(4);


//signal
printf("\nJust Exiting...\n");
sem_post(&mutex);
}

int main()
{
sem_init(&mutex, 0, 1); pthread_t t1,t2;
pthread_create(&t1,NULL,thread,NULL); sleep(2);
pthread_create(&t2,NULL,thread,NULL);
pthread_join(t1,NULL); pthread_join(t2,NULL);
sem_destroy(&mutex);
50

return 0;
}

Output

$ gcc sem.c -lpthread

$ ./a.out Entered..
Just Exiting... Entered..
Just Exiting...

Result

Thus semaphore implementation has been demonstrated.


51

Ex.No:7 BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE


Date:

AIM
To implement deadlock avoidance by using Banker’s Algorithm.

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

PROGRAM

#include <stdio.h> #include


<stdio.h>

main()
{
int r[1][10], av[1][10];
int all[10][10], max[10][10], ne[10][10], w[10],safe[10]; int i=0, j=0, k=0, l=0, np=0, nr=0,
count=0, cnt=0;

clrscr();
printf("enter the number of processes in a system");
scanf("%d", &np);
printf("enter the number of resources in a system");
scanf("%d",&nr);
for(i=1; i<=nr; i++)
{
printf("Enter no. of instances of resource R%d " ,i);
scanf("%d", &r[0][i]);
av[0][i] = r[0][i];
}

for(i=1; i<=np; i++) for(j=1; j<=nr;


j++)
all[i][j] = ne[i][j] = max[i][j] = w[i]=0;
printf("Enter the allocation matrix"); for(i=1; i<=np; i++)
{
for(j=1; j<=nr; j++)
{
scanf("%d", &all[i][j]);
av[0][j] = av[0][j] - all[i][j];
}
}

printf("Enter the maximum matrix"); for(i=1; i<=np; i++)


52

{
for(j=1; j<=nr; j++)
{
scanf("%d",&max[i][j]);
}
}

for(i=1; i<=np; i++)


{
for(j=1; j<=nr; j++)
{
ne[i][j] = max[i][j] - all[i][j];
}
}

for(i=1; i<=np; i++)


{
printf("pocess P%d", i); for(j=1; j<=nr; j++)
{
printf("\n allocated %d\t",all[i][j]); printf("maximum %d\t",max[i][j]);
printf("need %d\t",ne[i][j]);
}
printf("\n \n");
}

printf("\nAvailability "); for(i=1; i<=nr; i++)


printf("R%d %d\t", i, av[0][i]); printf("\n ");
printf("\n safe sequence");
for(count=1; count<=np; count++)
{
for(i=1; i<=np; i++)
{
Cnt = 0;
for(j=1; j<=nr; j++)
{
if(ne[i][j] <= av[0][j] && w[i]==0) cnt++;
}
if(cnt == nr)
{
k++;
safe[k] = i; for(l=1; l<=nr; l++)
av[0][l] = av[0][l] + all[i][l]; printf("\n P%d
",safe[k]); printf("\t Availability "); for(l=1; l<=nr; l++)
printf("R%d %d\t", l, av[0][l]); w[i]=1;
}
}
}
getch();
}
53

Output

enter the number of processes in a system 3


enter the number of resources in a system 3

enter no. of instances of resource R1 10 enter no. of instances of


resource R2 7 enter no. of instances of resource R3 7

Enter the allocation matrix 3 2 1


112
412

Enter the maximum matrix 4 4 4


345
524

pocess P1
allocated 3 maximum 4 need 1
allocated 2 maximum 4 need 2
allocated 1 maximum 4 need 3

pocess P2
allocated 1 maximum 3 need 2
allocated 1 maximum 4 need 3
allocated 2 maximum 5 need 3

pocess P3
allocated 4 maximum 5 need 1
allocated 1 maximum 2 need 1
allocated 2 maximum 4 need 2

Availability R1 2 R2 3 R3 2

safe sequence
P3 Availability R1 6 R2 4 R3 4
P1 Availability R1 9 R2 6 R3 5
P2 Availability R1 10 R2 7 R3 7

Result
Thus bankers algorithm for dead lock avoidance was executed successfully.
54

8. Write a C program to implement Deadlock detection Algorithm

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

#include<stdio.h>
void 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: \n");
scanf("%d",&tp);
printf("enter clain matrix: \n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&c[i][j]);
}
}
printf("enter allocation matrix: \n");
for(i=0;i<4;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&p[i][j]);
}
}
printf("enter resource vector: \n");
for(i=0;i<5;i++)
{
scanf("%d",&r[i]);
}
printf("enter availability vector: \n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
temp[i]=a[i];
}
for(i=0;i<4;i++)
{
sum=0;
for(j=0;j<5;j++)
{
sum+=p[i][j];
}
if(sum==0)
{
m[k]=i;
55

k++;
}
}
for(i=0;i<4;i++)
{
for(l=1;l<k;l++)
{
if(i!=m[l])
{
flag=1;
for(j=0;j<5;j++)
{
if(c[i][j]>temp[j])
{
flag=0;
break;
}
}
}
}
if(flag==1)
{
m[k]=i;
k++;
for(j=0;j<5;j++)
temp[j]+=p[i][j];
}
}
printf("deadlock causing processes are: \n");
for(j=0;j<tp;j++)
{
found=0;
for(i=1;i<k;i++)
{
if(j==m[i])
found=1;
}
if(found==0)
printf("%d\t",j);
}
}
56

OUTPUT:
$ vi bankersdetection.c
$ cc bankersdetection.c
$ ./a.out
enter total no of processes:
4
enter clain matrix:
01001
00101
00001
10101
enter allocation matrix:
10110
11000
00010
00000
enter resource vector:
21121
enter availability vector:
00001
deadlock causing processes are:
01

RESULT: Thus the program was executed and verified successfully


57

Ex. No. 9 Threading and Synchronization

Date:

Aim
To demonstrate threading and synchronization using mutex.

Description
• Thread synchronization is defined as a mechanism which ensures that two or more
concurrent processes or threads do not simultaneously execute some particular program
segment known as critical section.
• Processes’ access to critical section is controlled by using synchronization techniques.
• When one thread starts executing the critical section (serialized segment of the program)
the other thread should wait until the first thread finishes.
• If proper synchronization techniques are not applied, it may cause a race condition where the
values of variables may be unpredictable
• A Mutex is a lock that we set before using a shared resource and release after using it.
• When the lock is set, no other thread can access the locked region of code. So this ensures a
synchronized access of shared resources in the code.

Algorithm
1. Create two threads
2. Let the threads share a common resource, say counter
3. Even if thread2 si scheduled to start while thread was not done, access to shared resource
is not done as it is locked by mutex
4. Once thread1 completes, thread2 starts execution
5. Stop

Program

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

pthread_t tid[2];
int counter;
pthread_mutex_t lock;

void* trythis(void *arg)


{
pthread_mutex_lock(&lock);

unsigned long i = 0;
counter += 1;
printf("\n Job %d has started\n", counter);

for(i=0; i<(0xFFFFFFFF);i++);
58

printf("\n Job %d has finished\n", counter);

pthread_mutex_unlock(&lock);

return NULL;
}

main()
{
int i = 0;
int error;

if (pthread_mutex_init(&lock, NULL) != 0)
{
printf("\n mutex init has failed\n");
return 1;
}

while(i < 2)
{
err = pthread_create(&(tid[i]), NULL, &trythis, NULL);
if (error != 0)
printf("\nThreadcan'tbecreated:[%s]", strerror(error));
i++;
}

pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
pthread_mutex_destroy(&lock);

return 0;
}

Output

$ gcc filename.c -lpthread

$ ./a.out
Job 1 started
Job 1 finished
Job 2 started
Job 2 finished

Result
Thus concurrent threads were synchronized using mutex lock.
59

Ex. No. 10 Paging Technique


Date:

Aim
To determine physical address of a given page using page table.

Algorithm
1. Get process size
2. Compte no. of pages available and display it
3. Get relative address
4. Determine the corresponding page
5. Display page table
6. Display the physical address

Program

#include <stdio.h> #include


<math.h>

main()
{
int size, m, n, pgno, pagetable[3]={5,6,7}, i, j, frameno; double m1;
int ra=0, ofs;

printf("Enter process size (in KB of max 12KB):"); scanf("%d", &size);


m1 = size / 4; n =
ceil(m1);
printf("Total No. of pages: %d", n); printf("\nEnter relative address (in hexa) \n");
scanf("%d", &ra);

pgno = ra / 1000; ofs = ra %


1000;
printf("page no=%d\n", pgno); printf("page table");
for(i=0;i<n;i++)
printf("\n %d [%d]", i, pagetable[i]); frameno = pagetable[pgno];
printf("\nPhysical address: %d%d", frameno, ofs);

}
60

Output

Enter process size (in KB of max 12KB):12


Total No. of pages: 3
Enter relative address (in hexa): 2643
page no=2 page
table
0 [5]
1 [6]
2 [7]
Physical address : 7643

Result
Thus physical address for the given logical address is determing using Paging
technique.
61

Memory Allocation Technique


Exp: 11 a First Fit Allocation
Date:

Aim

To allocate memory requirements for processes using first fit allocation.

Memory Management
➢ The first-fit, best-fit, or worst-fit strategy is used to select a free hole from the set of available
holes.

First fit
➢ Allocate the first hole that is big enough.
➢ Searching starts from the beginning of set of holes.

Algorithm
1. Declare structures hole and process to hold information about set of holes and processes
respectively.
2. Get number of holes, say nh.
3. Get the size of each hole
4. Get number of processes, say np.
5. Get the memory requirements for each process.
6. Allocate processes to holes, by examining each hole as follows:
a. If hole size > process size then
i. Mark process as allocated to that hole.
ii. Decrement hole size by process size.
b. Otherwise check the next from the set of hole
7. Print the list of process and their allocated holes or unallocated status.
8. Print the list of holes, their actual and current availability.
9. Stop

Program

/* First fit allocation - ffit.c */ #include <stdio.h>

struct process
{
int size; int flag;
int holeid;
} p[10];
struct hole
{
int size;
62

int actual;
} h[10];

main()
{
int i, np, nh, j;

printf("Enter the number of Holes : "); scanf("%d", &nh);


for(i=0; i<nh; i++)
{
printf("Enter size for hole H%d : ",i); scanf("%d", &h[i].size);
h[i].actual = h[i].size;
}

printf("\nEnter number of process : " );


scanf("%d",&np);
for(i=0;i<np;i++)
{
printf("enter the size of process P%d : ",i);
scanf("%d", &p[i].size);
p[i].flag = 0;
}

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


{
for(j=0; j<nh; j++)
{
if(p[i].flag != 1)
{
if(p[i].size <= h[j].size)
{
p[i].flag = 1; p[i].holeid = j;
h[j].size -= p[i].size;
}
}
}
}

printf("\n\tFirst fit\n");
printf("\nProcess\tPSize\tHole"); for(i=0; i<np; i++)
{
if(p[i].flag != 1)
printf("\nP%d\t%d\tNot allocated", i, p[i].size);
else
printf("\nP%d\t%d\tH%d", i, p[i].size, p[i].holeid);
}
printf("\n\nHole\tActual\tAvailable"); for(i=0; i<nh ;i++)
printf("\nH%d\t%d\t%d", i, h[i].actual, h[i].size); printf("\n");
}
63

Output
Enter the numb er of Holes : 5
Enter size for hole H0 : 100
Enter size for hole H1 : 500
Enter size for hole H2 : 200
Enter size for Enter hole H3 : 300
size for hole H4 : 600

Enter number o f process : 4


enter the size of process P0 : 212
enter the size of process P1 : 417
enter the size of process P2 : 112
enter the size of process P3 : 426

First fit

Process PSize Hole


P0 212 H1
P1 417 H4
P2 112 H1
P3 426 Not allocated

Hole Actual Available


H0 100 100
H1 500 176
H2 200 200
H3 300 300
H4 600 183

Result

Thus processes were allocated memory using first fit method.

You might also like