LAB MANUAL - OS - 2021 Regulation Final
LAB MANUAL - OS - 2021 Regulation Final
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 /]$
$ rmdir filter
$ ls
list.sh regexpr shellscripts
$ cat greet
hi ece-a
wishing u the best
$ 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
$ ls -l list.sh
-rw-rw-r-- 1 vijai vijai 30 Apr 4 13:58 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
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.
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
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
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
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
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
Aim
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.
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
#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("-");
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
FCFS Scheduling
P1 10 10 0
P2 4 14 10
P3 11 25 14
P4 6 31 25
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
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
/*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
Result
Thus the implementation of interprocess communication using share memory has been demonstrated.
49
Aim
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
#include <stdio.h>
#include <pthread.h> #include
<semaphore.h> #include <unistd.h>
sem_t 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
$ ./a.out Entered..
Just Exiting... Entered..
Just Exiting...
Result
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
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(j=1; j<=nr; j++)
{
scanf("%d",&max[i][j]);
}
}
Output
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
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
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;
unsigned long i = 0;
counter += 1;
printf("\n Job %d has started\n", counter);
for(i=0; i<(0xFFFFFFFF);i++);
58
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
$ ./a.out
Job 1 started
Job 1 finished
Job 2 started
Job 2 finished
Result
Thus concurrent threads were synchronized using mutex lock.
59
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
main()
{
int size, m, n, pgno, pagetable[3]={5,6,7}, i, j, frameno; double m1;
int ra=0, ofs;
}
60
Output
Result
Thus physical address for the given logical address is determing using Paging
technique.
61
Aim
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
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("\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
First fit
Result