OSL-Lab Manual-2022-23-Sem-1
OSL-Lab Manual-2022-23-Sem-1
Lab
Examination
Teaching Scheme
Scheme
Practical : 4 Hrs. / Week Practical 25 Marks
Term Work 25 Marks
MISSION
Author
Signature
Document History
Course Objectives:
1. To introduce and learn Linux commands required for administration.
2. To learn shell programming concepts and applications.
3. To demonstrate the functioning of OS basic building blocks like processes, threads under the LINUX.
4. To demonstrate the functioning of OS concepts in user space like concurrency control (process
synchronization, mutual exclusion), CPU Scheduling, Memory Management and Disk Scheduling in LINUX.
5. To demonstrate the functioning of Inter Process Communication under LINUX.
6. To study the functioning of OS concepts in kernel space like embedding the system call in any LINUX
kernel.
Course Outcomes:
On completion of the course, students will be able to– CO1: Apply the basics of Linux commands.
CO2: Build shell scripts for various applications.
CO3: Implement basic building blocks like processes, threads under the Linux.
CO4: Develop various system programs for the functioning of OS concepts in user space like concurrency
control, CPU Scheduling, Memory Management and Disk Scheduling in Linux.
CO5: Develop system programs for Inter Process Communication in Linux.
Guidelines for Instructor's Manual
1. The faculty member should prepare the laboratory manual for all the experiments and it shouldbe made
available to students and laboratory instructor/Assistant.
1. Student should submit term work in the form of handwritten journal based on specified list of
assignments.
2. Practical Examination will be based on the term work.
3. Candidate is expected to know the theory involved in the experiment.
Department of Information Technology Page 6 of 92
4. The practical examination should be conducted if and only if the journal of the candidate is complete in
all aspects.
1. Examiners will assess the term work based on performance of students considering the parameters
such as timely conduction of practical assignment, methodology adopted for implementation of practical
assignment, timely submission of assignment in the form of handwritten write-up along with results of
implemented assignment, attendance etc.
2. Examiners will judge the understanding of the practical performed in the examination by asking some
questions related to the theory & implementation of the experiments he/she has carried out.
3. Appropriate knowledge of usage of software and hardware related to respective laboratory should be
checked by the concerned faculty member.
Assignment No. 2:
Process control system calls: The demonstration of FORK, EXECVE and WAIT system calls along with zombie
and orphan states.
A. Implement the C program in which main program accepts the integers to be sorted. Main program uses
the FORK system call to create a new process called a child process. Parent process sorts the integers using
sorting algorithm and waits for child process using WAIT system call to sort the integers using any sorting
algorithm. Also demonstrate zombie and orphan states.
B. Implement the C program in which main program accepts an array. Main program uses the FORK system
call to create a new process called a child process. Parent process sorts an array and passes the sorted array
to child process through the command line arguments of EXECVE system call. The child process uses EXECVE
system call to load new program which display array in reverse order.
Assignment No. 5:
Implement the C program for Deadlock Avoidance Algorithm: Bankers Algorithm.
Assignment No. 6:
Implement the C program for Page Replacement Algorithms: FCFS, LRU, and Optimal for frame size as
minimum three.
Assignment No. 7:
Inter process communication in Linux using following.
A. FIFOS: Full duplex communication between two independent processes. First process accepts sentences
and writes on one pipe to be read by second process and second process counts number of characters,
number of words and number of lines in accepted sentences, writes this output in a text file and writes the
contents of the file on second pipe to be read by first process and displays on standard output.
B. Inter-process Communication using Shared Memory using System V. Application to demonstrate: Client
and Server Programs in which server process creates a shared memory segment and writes the message to
the shared memory segment. Client process reads the message from the shared memory segment and
displays it to the screen.
Assignment No. 8: Implement the C program for Disk Scheduling Algorithms: SSTF, SCAN, C-Look considering
the initial head position moving away from the spindle.
Study Assignment: Implement a new system call in the kernel space, add this new system call in the Linux
kernel by the compilation of this kernel (any kernel source, any architecture and any Linux kernel
distribution) and demonstrate the use of this embedded system call using C program in user space.
Reference Books:
1. Das, Sumitabha, UNIX Concepts and Applications, TMH, ISBN-10: 0070635463, ISBN-13: 978-
0070635463, 4th Edition.
2. Kay Robbins and Steve Robbins, UNIX Systems Programming, Prentice Hall, ISBN-13: 978-
0134424071, ISBN-10: 0134424077, 2nd Edition.
3. Mendel Cooper, Advanced Shell Scripting Guide, Linux Documentation Project, Public domain.
4. Yashwant Kanetkar, UNIX Shell Programming, BPB Publication.
6.
Implement the C program for Page Replacement Algorithms:
FCFS, LRU, and Optimal for frame size as minimum three.
6.
Implement the C program for Page Replacement Algorithms:
FCFS, LRU, and Optimal for frame size as minimum three.
OBJECTIVE:
To study
1. Basic Linux commands
2. Shell script
THEORY:
Linux Commands
The Linux command is a utility of the Linux operating system. All basic and
advanced tasks can be done by executing commands. The commands are
executed on the Linux terminal. The terminal is a command-line interface to
interact with the system, which is similar to the command prompt in the
Windows OS. Commands in Linux are case-sensitive
Basic Linux Commands
mkdir Command
The mkdir command is used to create a new directory under any directory
Syntax:
mkdir <directory name>
rmdir Command
Syntax:
cd Command
touch Command
The touch command is used to create empty files. We can create multiple
empty files by executing it once.
Syntax:
touch <file name>
touch <file1> <file2>
cat Command
Syntax:
rm Command
Syntax:
rm <file name>
ls Command
Syntax:
ls
cat Command
The cat command is also used as a filter. To filter a file, it is used inside
pipes.
Syntax:
grep Command
The grep is the most powerful and used filter in a Linux system. The 'grep'
stands for "global regular expression print." It is useful for searching the
content from a file. Generally, it is used with the pipe.
Syntax:
sed command
The sed command is also known as stream editor. It is used to edit files
using a regular expression. It does not permanently edit files; instead, the
edited content remains only on display. It does not affect the actual file.
Syntax:
sort Command
Syntax:
cal Command
Syntax:
cal<
read command
The read command is used to read from a file descriptor. This command
read up the total number of bytes from the specified file descriptor into the
buffer. If the number or count is zero then this command may detect the
errors. But on success, it returns the number of bytes read. Zero indicates
the end of the file. If some errors found then it returns -1
Syntax:
read
echo command
Syntax:
test command
Syntax:
test EXPRESSION
[ EXPRESSION ]
` Back quote
`Back quote` - To execute command
Example:
$ echo "Today is date"
Can't print message with today's date.
$ echo "Today is `date`".
Rules for Naming variable name (Both UDV and System Variable)
(1) Variable name must begin with Alphanumeric character or underscore
character (_), followed by one or more Alphanumeric character. For e.g. Valid
shell variable are as follows
HOME
SYSTEM_VERSION
(2) Don't put spaces on either side of the equal sign when assigning value to
variable. For e.g. In following variable declaration there will be no error
Variables in Shell
To process our data/information, data must be kept in computers RAM
memory. RAM memory is divided into small locations, and each location had
unique number called memory location/address, which is used to hold our data.
Programmer can give a unique name to this memory location/address called
memory variable or variable (Its a named storage location that may take different
values, but only one at a time).
In Linux (Shell), there are two types of variable:
(1) System variables - Created and maintained by Linux itself. This type of
variable defined in CAPITAL LETTERS.
(2) User defined variables (UDV) - Created and maintained by user. This type of
variable defined in lower letters.
You can see system variables by giving command like $ set, some of the
important System variables are:
Operator Meaning
Meaning
Operator Meaning
expression1 -
Logical AND
a expression2
expression1 -
Logical OR
o expression2
if condition
if condition which is used for decision making in shell script, If given
condition is true then command1 is executed.
Syntax:
if condition
then
command1 if condition is true or if exit status
of condition is 0 (zero)
…
…
fi
Condition is defined as:
“Condition is nothing but comparison between two values.”
For compression you can use test or [ expr ] statements or even exist status
can be also used.
Loops in Shell Scripts
Bash supports:
1) for loop
2) while loop
while :
The syntax of the while is:
Conclusion: Thus in shell script we can write series of commands and execute
as a single program.
Process control system calls: The demonstration of FORK, EXECVE and WAIT
system calls along with zombie and orphan states.
A. Implement the C program in which main program accepts the integers to
be sorted. Main program uses the FORK system call to create a new
process called a child process. Parent process sorts the integers using
sorting algorithm and waits for child process using WAIT system call to
sort the integers using any sorting algorithm. Also, demonstrate zombie
and orphan states. Write a program to implement an address book with
options given below: a) Create address book. b) View address book. c)
Insert a record. d) Delete a record. e) Modify a record. f) Exit
OBJECTIVE:
To study
Process control
THEORY:
Process
A process is the basic active entity in most operating-system models. A process
is a program in execution in memory or in other words, an instance of a program
in memory. Any program executed creates a process. A program can be a
command, a shell script, or any binary executable or any application.
Creating Process
Two common techniques are used for creating a new process.
1. using system() function
2. using fork() system calls
1. system () function
The system function in the standard C library provides an easy way to execute a
command from within a program, much as if the command had been typed into
a shell. In fact, system creates a subprocess running the standard Bourne shell
(/bin/sh) and hands the command to that shell for execution.
The system function returns the exit status of the shell command. If the shell
itself cannot be run, system returns 127; if another error occurs, system returns
–1.
2. fork system call
A process can create a new process by calling fork. The calling process becomes
the parent, and the created process is called the child. The fork function copies
the parent's memory image so that the new process receives a copy of the address
space of the parent. Both processes continue at the instruction after the fork
statement (executing in their respective memory images).
Synopsis
#include <unistd.h>
pid_t fork(void);
Status values
The status argument of wait is a pointer to an integer variable. If it is not NULL,
this function stores the return status of the child in this location. The child
returns its status by calling exit, _exit or return from main.
A zero return value indicates EXIT_SUCCESS; any other value indicates
EXIT_FAILURE.
POSIX specifies six macros for testing the child's return status. Each takes the
status value returned by a child to wait as a parameter. Following are the two
such macros:
Synopsis
#include <sys/wait.h>
WIFEXITED(intstat_val)
WEXITSTATUS(intstat_val)
Department of Information Technology Page 28 of 92
Exec system call
Used for new program execution within the existing process. The fork function
creates a copy of the calling process, but many applications require the child
process to execute code that is different from that of the parent. The exec family
of functions provides a facility for overlaying the process image of the calling
process with a new image. The traditional way to use the fork–exec combination
is for the child to execute (with an exec function) the new program while the
parent continues to execute the original code. The exec system call is used after
a fork system call by one of the two processes to replace the memory space with
a new program. The exec system call loads a binary file into memory (destroying
image of the program containing the exec system call) and go their separate ways.
Within the exec family, there are functions that vary slightly in their capabilities.
Synopsis
#include <unistd.h>
extern char **environ;
Exec family
1. intexecl(const char *path, const char *arg0, ... /*, char *(0) */);
2. intexecle (const char *path, const char *arg0, ... /*, char *(0), char
*constenvp[] */);
3. intexeclp (const char *file, const char *arg0, ... /*, char *(0) */);
execvp()
It does same job expect that it will use environment variable PATH to
determine which executable to process. Thus a fully qualified path name
would not have to be used.
e.g. execvp("ls", argv);
3. execve( )
It executes the program pointed to by filename.
intexecve(const char *filename, char *constargv[ ], char *constenvp[
]);
Filename must be either a binary executable, or a script starting with a
line of the form: argv is an array of argument strings passed to the new
program. By convention, the first of these strings should contain the
filename associated with the file being executed. envp is an array of
strings, conventionally of the form key=value, which are passed as
environment to the new program. Both argv and envp must be terminated
by a NULL pointer. The argument vector and environment can be accessed
by the called program's main function, when it is defined as:
Process Termination
Normally, a process terminates in one of two ways. Either the executing program
calls the exit function, or the program’s main function returns. Each process has
an exit code: a number that the process returns to its parent. The exit code is
the argument passed to the exit function, or the value returned from main.
Zombie Processes
If a child process terminates while its parent is calling a wait function, the child
process vanishes and its termination status is passed to its parent via the wait
call. But what happens, when a child process terminates and the parent is not
calling wait? Does it simply vanish? No, because then information about its
termination—such as whether it exited normally and, if so, what its exit status
is—would be lost. Instead, when a child process terminates, it becomes a zombie
process.
A zombie process is a process that has terminated but has not been cleaned up
yet. It is the responsibility of the parent process to clean up its zombie children.
The wait functions do this, too, so it’s not necessary to track whether your child
process is still executing before waiting for it. Suppose, for instance, that a
program forks a child process, performs some other computations, and then calls
wait. If the child process has not terminated at that point, the parent process
will block in the wait call until the child process finishes. If the child process
finishes before the parent process calls wait, the child process becomes a zombie.
When the parent process calls wait, the zombie child’s termination status is
extracted, the child process is deleted, and the wait call returns immediately.
Input
1. An integer array with specified size.
2. An integer array with specified size and number to search.
Output
1. Sorted array.
2. Status of number to be searched.
FAQS
Is Orphan process different from a Zombie process?
Are Orphan processes harmful for system?
Is it bad to have Zombie processes on your system?
How to find an Orphan Process?
How to find a Zombie Process?
What is common shared data between parent and child process?
What are the contents of Process Control Block?
Example 1
Printing the Process ID
#include <stdio.h>
#include <unistd.h>
int main()
{
printf(“The process ID is %d\n”, (int) getpid());
printf(“The parent process ID is %d\n”, (int) getppid());
return 0;
}
Example 2
Using the system call
#include <stdlib.h>
int main()
{
intreturn_value;
return_value=system(“ls –l /”);
return return_value;
}
Example 3
Using fork to duplicate a program’s process
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_tchild_pid;
printf(“The main program process ID is %d\n”, (int) getpid());
child_pid=fork();
if(child_pid!=0)
{
printf(“This is the parent process ID, with id %d\n”, (int) getpid());
printf(“The child process ID is %d\n”, (int) child_pid);
}
else
printf(“This is the child process ID, with id %d\n”, (int) getpid());
return 0;
}
Example 4
Determining the exit status of a child
Department of Information Technology Page 34 of 92
#include <stdio.h> #include <sys/types.h> #include <sys/wait.h>
void show_return_status(void)
{
pid_tchildpid;
int status;
childpid = wait(&status); if (childpid == -1)
perror("Failed to wait for child");
else if (WIFEXITED(status))
printf("Child %ld terminated with return status %d\n", (long)childpid,
WEXITSTATUS(status));
}
Example 5
A program that creates a child process to run ls -l
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_tchildpid;
childpid = fork();
if (childpid == -1) {
perror("Failed to fork");
return 1;
}
if (childpid == 0) {
/* child code */
execl("/bin/ls", "ls", "-l", NULL);
perror("Child failed to exec ls"); return 1;
}
if (childpid != wait(NULL)) {
/* parent code */
perror("Parent failed to wait due to signal or error"); return 1;
}
return 0;
}
Example 6
Example 8
Demo of multi-process application using fork () system call
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
void do_child_proc(intpfd[2]);
void do_parent_proc(intpfd[2]);
int main()
{
intpfd[2];
intret_val,nread;
pid_tpid;
ret_val=pipe(pfd);
if(ret_val==-1)
{
perror(“pipe error\n”);
exit(ret_val);
}
pid=fork();
switch(pid)
{
case -1:
printf(“Fork error\n”);
exit(pid);
case 0:
do_child_proc(pfd);
exit(0);
default:
do_parent_proc(pfd);
exit(pid);
}
wait(NULL);
return 0;
}
Department of Information Technology Page 37 of 92
void do_child_proc(intpfd[2])
{
intnread;
char *buf=NULL;
printf(“5\n”);
close(pfd[1]);
while(nread=(read(pfd[0],buf,size))!=0)
printf(“Child Read=%s\n”,buf);
close(pfd[0]);
exit(0);
}
void do_parent_proc(intpfd[2])
{
char ch;
char *buf=NULL;
close(pfd[0]);
while(ch=getchar()!=’\n’) {
printf(“7\n”);
*buf=ch;
buff+;
}
*buf=’\0’;
write(pfd[1],buf,strlen(buf)+1);
close(pfd[1]);
}
Implement the C program for CPU Scheduling Algorithms: Shortest Job First
(Preemptive) and Round Robin with different arrival time.
OBJECTIVE:
To study
• Preemptive and Non-Preemptive CPU scheduling
• Application and use of CPU scheduling Algorithm
THEORY:
Shortest Job First (Preemptive)
What is Shortest Job First?
This is an approach which considers the next CPU burst. Each process possess
its next CPU burst. When CPU is available, the process having the smallest next
CPU burst is allocated CPU.
It may happen that two or more processes have the same next CPU burst. Then
which process to allocate will be decided as per FCFS scheduling.
Shortest job first(SJF) is a scheduling algorithm, that is used to schedule
processes in an operating system. It is a very important topic in Scheduling when
compared to round-robin and FCFS Scheduling.
There are two types of SJF
Pre-emptive SJF
Non-Preemptive SJF
These algorithms schedule processes in the order in which the shortest job is
done first. It has a minimum average waiting time.
1. BURST Time
Advantages
This algorithm is simple to implement.
Does not depend on any priority of the process. The smallest burst time is
the higher priority consideration.
It provides good CPU utilization than FCFS (First Come First Search).
Waiting time and turnaround time of each process is reduced, reducing
the average waiting time and turn around the time of the system as
compared to FCFS.
Disadvantages
Waiting time of some processes still high due to the long burst time of the
processes, in case of non-preemptive scheduling.
In the case of non-preemptive scheduling, it may act as a uni-processing
operating system.
In the case of preemptive scheduling, context switch is required.
And in preemptive scheduling, turnaround time may get increased.
Department of Information Technology Page 41 of 92
Preemptive SJF Example:
Code:
#include <stdio.h>
int main()
{
int arrival_time[10], burst_time[10], temp[10];
int i, smallest, count = 0, time, limit;
double wait_time = 0, turnaround_time = 0, end;
float average_waiting_time, average_turnaround_time;
printf("nEnter the Total Number of Processes:t");
scanf("%d", &limit);
printf("nEnter Details of %d Processesn", limit);
for(i = 0; i < limit; i++)
{
printf("nEnter Arrival Time:t");
scanf("%d", &arrival_time[i]);
printf("Enter Burst Time:t");
scanf("%d", &burst_time[i]);
temp[i] = burst_time[i];
}
burst_time[9] = 9999;
for(time = 0; count != limit; time++)
{
smallest = 9;
for(i = 0; i < limit; i++)
Output
void main()
{
// initlialize the variable name
int i, NOP, sum=0,count=0, y, quant, wt=0, tat=0, at[10], bt[10],
temp[10];
float avg_wt, avg_tat;
printf(" Total number of process in the system: ");
scanf("%d", &NOP);
y = NOP; // Assign the number of process to variable y
Output:
Thread Synchronization
A. Thread synchronization using counting semaphores. Application to
demonstrate: producer- consumer problem with counting semaphores and
mutex.
OBJECTIVE:
To study
• Semaphores
• Mutex
• Producer-Consumer Problem
• Reader- Writer problem
THEORY:
Semaphores:
Semaphore is an integer value used for signaling among processes. Only three
operations may be performed on a semaphore, all of which are atomic: initialize,
decrement, and increment.
The decrement operation may result in the blocking of a process, and the
increment operation may result in the unblocking of a process. It is known as a
counting semaphore or a general semaphore. Semaphores are the OS tools for
synchronization.
Two types:
1. Binary Semaphore.
2. Counting Semaphore
Value of semaphore
Positive
Indicates number of processes that can issue wait & immediately continue
to execute.
Zero
By initialization or because number of processes equal to initial semaphore
value have issued a wait Next process to issue a wait is blocked.
Negative
Indicates number of processes waiting to be unblocked
Each signal unblocks one waiting process.
Figure illustrates the structure of buffer b. The producer can generate items and
store them in the buffer at its own pace. Each time, an index (in) into the buffer
is incremented. The consumer proceeds in a similar fashion but must make sure
that it does not attempt to read from an empty buffer. Hence, the
Semaphore functions:
1. sem_init()
Department of Information Technology Page 56 of 92
It initializes the unnamed semaphore at the address pointed to by sem.
The value argument specifies the initial value for the semaphore.
int sem_init(sem_t *sem, int pshared, unsigned int value);
2. sem_wait()
It decrements (locks) the semaphore pointed to by sem. If the semaphore's
value is greater than zero, then the decrement proceeds, and the function
returns, immediately. If the semaphore currently has the value zero, then the
call blocks until it becomes possible to perform the decrement.
int sem_wait(sem_t *sem);
3. sem_post()
It increments (unlocks) the semaphore pointed to by sem. If the semaphore's
value consequently becomes greater than zero, then another process or
thread blocked in a sem_wait(3) call will be woken up and proceed to lock the
semaphore.
int sem_post(sem_t *sem);
1. sem_unlink
It removes the named semaphore referred to by name. The semaphore name
is removed immediately. The semaphore is destroyed once all other processes
that have the semaphore open close it.
int sem_unlink(const char *name)
All the above functions returns
0 : Success
-1 : Error
Mutex
Mutexes are a method used to be sure two threads, including the parent
thread, do not attempt to access shared resource at the same time. A mutex
lock allows only one thread to enter the part that's locked and the lock is not
shared with any other processes.
1. pthread_mutex_init()
Department of Information Technology Page 57 of 92
The function shall initialize the mutex referenced by mutex with attributes
specified by attr. If attr is NULL, the default mutex attributes are used; the
effect shall be the same as passing the address of a default mutex attributes
object. Upon successful initialization, the state of the mutex becomes
initialized and unlocked.
int pthread_mutex_init(pthread_mutex_t *restrict mutex, cons
pthread_mutexattr_t *restrict attr);
2. pthread_mutex_lock()
The mutex object referenced by mutex shall be locked by calling
pthread_mutex_lock(). If the mutex is already locked, the calling thread shall
block until the mutex becomes available. This operation shall return with the
mutex object referenced by mutex in the locked state with the calling thread
as its owner.
int pthread_mutex_lock(pthread_mutex_t * mutex);
3. pthread_mutex_unlock()
The function shall release the mutex object referenced by mutex. The manner
in which a mutex is released is dependent upon the mutex's type attribute. If
there are threads blocked on the mutex object referenced by mutex when
pthread_mutex_unlock() is called, resulting in the mutex becoming available,
the scheduling policy shall determine which thread shall acquire the mutex.
int pthread_mutex_unlock(pthread_mutex_t * mutex);
4. pthread_mutex_destroy()
The function shall destroy the mutex object referenced by mutex; the mutex
object becomes, in effect, uninitialized. A destroyed mutex object can be
reinitialized using pthread_mutex_init(); the results of otherwise referencing
the object after it has been destroyed are undefined.
int pthread_mutex_destroy(pthread_mutex_t *mutex);
FAQ
1. Explain the concept of semaphore.
2. Explain wait and signal functions associated with semaphores.
3. What do binary and counting semaphores mean?
4.
OBJECTIVE: To Study
Deadlock
THEORY:
What is Deadlock?
A set of processes is deadlocked if each process in the set is waiting for an event
that only another process in the set can cause. Because all the processes are
waiting, none of them will ever cause any of the events that could wake up any
of the other members of the set, and all the processes continue to wait forever.
For this model, we assume that processes have only a single thread and that
there are no interrupts possible to wake up a blocked process. The no interrupts
condition is needed to prevent an otherwise deadlocked process from being
awake.
Available:
It is a 1-d array of size ‘m’ indicating the number of available resources of
each type.
Max:
It is a 2-d array of size ‘n*m’ that defines the maximum demand of each
process in a system.
Allocation:
It is a 2-d array of size ‘n*m’ that defines the number of resources of each
type currently allocated to each process.
Allocation[ i, j ] = k means process Pi is currently allocated ‘k’ instances of
resource type Rj
Need:
It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of
each process.
Need [ i, j ] = k means process Pi currently need ‘k’ instances of resource
type Rj
Need [ i, j ] = Max [ i, j ] – Allocation [ i, j ]
Safety Algorithm
The algorithm for finding out whether or not a system is in a safe state can be
described as follows:
Resource-Request Algorithm
Let Requesti be the request array for process P i. Requesti [j] = k means process
Pi wants k instances of resource type R j. When a request for resources is
made by process Pi, the following actions are taken:
FAQ:
1. What is dead lock?
2. What are the necessary and sufficient conditions to occur deadlock?
3. What is deadlock avoidance and deadlock prevention techniques?
Implement the C program for Page Replacement Algorithms: FCFS, LRU, and
Optimal for frame size as minimum three.
OBJECTIVE:
To study
Page Replacement
THEORY:
Page Replacement
Page Fault – It is basically a memory error, and it occurs when the current
programs attempt to access the memory page for mapping into virtual address
space, but it is unable to load into the physical memory then this is referred to
as Page fault.
A page fault happens when a running program accesses a memory page that is
mapped into the virtual address space, but not loaded in physical memory.
Since actual physical memory is much smaller than virtual memory, page faults
happen. In case of page fault, Operating System might have to replace one of the
existing pages with the newly needed page. Different page replacement
algorithms suggest different ways to decide which page to replace. The target for
all algorithms is to reduce the number of page faults.
Paging
Segmentation
Paging
Paging is a process of reading data from, and writing data to, the secondary
storage. It is a memory management scheme that is used to retrieve processes
from the secondary memory in the form of pages and store them in the primary
memory. The main objective of paging is to divide each process in the form of
pages of fixed size. These pages are stored in the main memory in frames. Pages
of a process are only brought from the secondary memory to the main memory
when they are needed.
In such a case, the OS has to bring the page from the secondary storage into the
main memory. This may cause some pages in the main memory to be replaced
due to limited storage. A Page Replacement Algorithm is required to decide which
page needs to be replaced.
Page Replacement Algorithm decides which page to remove, also called swap out
when a new page needs to be loaded into the main memory.
When the page that was selected for replacement was paged out, and referenced
again, it has to read in from disk, and this requires for I/O completion. This
process determines the quality of the page replacement algorithm: the lesser the
time waiting for page-ins, the better is the algorithm.
1. First of all, find the location of the desired page on the disk.
2. Find a free Frame: a) If there is a free frame, then use it. b) If there is no
free frame then make use of the page-replacement algorithm in order to
select the victim frame. c) Then after that write the victim frame to the disk
and then make the changes in the page table and frame table accordingly.
3. After that read the desired page into the newly freed frame and then
change the page and frame tables.
4. Restart the process.
This algorithm helps to decide which pages must be swapped out from the main
memory in order to create a room for the incoming page. This Algorithm wants
the lowest page-fault rate.
This algorithm is implemented by keeping the track of all the pages in the
queue.
As new pages are requested and are swapped in, they are added to the tail
of a queue and the page which is at the head becomes the victim.
This is not an effective way of page replacement but it can be used for
small systems.
Advantages
Disadvantages
This algorithm does not make the use of the frequency of last used time
rather it just replaces the Oldest Page.
ALGORITHM
4. Check the need of replacement from old page to new page in memory
OBJECTIVE:
To study
Communication (interface) between processes.
THEORY:
A FIFO (First In First Out) is a one-way flow of data. FIFOs have a name, so
unrelated processes can share the FIFO. FIFO is a named pipe. Any process can
open or close the FIFO. FIFOs are also called named pipes.
Properties:
1. A read gets as much data as it requests or as much data as the FIFO has,
whichever is less.
2. A write to a FIFO is atomic, as long as the write does not exceed the
capacity of the FIFO.
3. Two processes must open FIFO; one opens it as reader on one end, the
other opens it as sender on the other end. The first/earlier opener has to
wait until the second/later opener to come. This is somewhat like a hand
shaking.
Creating a FIFO
A FIFO is created by the mkfifo function. Specify the path to the FIFO on the
command line. For example, create a FIFO in /tmp/fifo by invoking this:
#include <sys/types.h>
#include <sys/stat.h>
pathname: a UNIX pathname (path and filename). The name of the FIFO
mode: the file permission bits. It specifies the pipe’s owner, group, and world
permissions, and a pipe must have a reader and a writer, the permissions must
include both read and write permissions.
If the pipe cannot be created (for instance, if a file with that name already exists),
mkfifo returns –1.
Access a FIFO just like an ordinary file. To communicate through a FIFO, one
program must open it for writing, and another program must open it for reading.
Either low-level I/O functions like open, write, read, close or C library I/O
functions (fopen, fprintf, fscanf, fclose, and soon) may be used.
For example, to write a buffer of data to a FIFO using low-level I/O routines, you
could use this code:
close (fd);
To read a string from the FIFO using C library I/O functions, you could use
this code:
fclose (fifo);
A FIFO can have multiple readers or multiple writers. Bytes from each writer are
written atomically up to a maximum size of PIPE_BUF (4KB on Linux). Chunks
from simultaneous writers can be interleaved. Similar rules apply to
simultaneous reads.
Let us look at a few details of the system calls related to shared memory.
#include <sys/ipc.h>
#include <sys/shm.h>
The above system call creates or allocates a System V shared memory segment.
The arguments that need to be passed are as follows −
The first argument, key, recognizes the shared memory segment. The key can
be either an arbitrary value or one that can be derived from the library function
ftok(). The key can also be IPC_PRIVATE, means, running processes as server
and client (parent and child relationship) i.e., inter-related process
communiation. If the client wants to use shared memory with this key, then it
must be a child process of the server. Also, the child process needs to be created
after the parent has obtained a shared memory.
The second argument, size, is the size of the shared memory segment rounded
to multiple of PAGE_SIZE.
The third argument, shmflg, specifies the required shared memory flag/s such
as IPC_CREAT (creating new segment) or IPC_EXCL (Used with IPC_CREAT to
create new segment and the call fails, if the segment already exists). Need to pass
the permissions as well.
This call would return a valid shared memory identifier (used for further calls of
shared memory) on success and -1 in case of failure. To know the cause of
failure, check with errno variable or perror() function.
#include <sys/shm.h>
The above system call performs shared memory operation for System V shared
memory segment i.e., attaching a shared memory segment to the address space
of the calling process. The arguments that need to be passed are as follows −
shmid is the identifier of the shared memory segment. This id is the shared
memory identifier, which is the return value of shmget() system call.
This call would return the address of attached shared memory segment on
success and -1 in case of failure. To know the cause of failure, check with errno
variable or perror() function.
#include <sys/types.h>
#include <sys/shm.h>
This call would return 0 on success and -1 in case of failure. To know the cause
of failure, check with errno variable or perror() function.
#include <sys/ipc.h>
#include <sys/shm.h>
The above system call performs control operation for a System V shared memory
segment. The following arguments needs to be passed −
The first argument, shmid, is the identifier of the shared memory segment. This
id is the shared memory identifier, which is the return value of shmget() system
call.
The second argument, cmd, is the command to perform the required control
operation on the shared memory segment.
Create two processes, one is for writing into the shared memory
(shm_write.c) and another is for reading from the shared memory
(shm_read.c)
The program performs writing into the shared memory by write process
(shm_write.c) and reading from the shared memory by reading process
(shm_read.c)
The write process writes 5 times the Alphabets from ‘A’ to ‘E’ each of 1023
bytes into the shared memory. Last byte signifies the end of buffer
Read process would read from the shared memory and write to the
standard output
Reading process performs reading from the shared memory and displays
on the output until it gets indication of write process completion (complete
variable in struct shmseg)
Performs reading and writing process for a few times for simplication and
also in order to avoid infinite loops and complicating the program
Code for write process (Writing into Shared Memory – File: shm_write.c)
/* Filename: shm_write.c */
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
struct shmseg {
int cnt;
int complete;
char buf[BUF_SIZE];
};
Department of Information Technology Page 82 of 92
int fill_buffer(char * bufptr, int size);
if (shmdt(shmp) == -1) {
perror("shmdt");
return 1;
}
Code for read process (Reading from the Shared Memory and writing to the
standard output – File: shm_read.c)
/* Filename: shm_read.c */
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
CONCLUSION:
OBJECTIVE:
This assignment covers the UNIX process control commonly called for process
creation, program execution and process termination. Also covers process model,
including process creation, process destruction, zombie and orphan processes.
THEORY:
There are many Disk Scheduling Algorithms but before discussing them let’s
have a quick look at some of the important terms:
Seek Time: Seek time is the time taken to locate the disk arm to a
specified track where the data is to be read or write. So the disk
scheduling algorithm that gives minimum average seek time is better.
Rotational Latency: Rotational Latency is the time taken by the desired
sector of disk to rotate into a position so that it can access the read/write
Department of Information Technology Page 86 of 92
heads. So the disk scheduling algorithm that gives minimum rotational
latency is better.
Transfer Time: Transfer time is the time to transfer the data. It depends
on the rotating speed of the disk and number of bytes to be transferred.
Disk Access Time: Disk Access Time is:
FCFS:
FCFS is the simplest of all the Disk Scheduling Algorithms. In FCFS, the
requests are addressed in the order they arrive in the disk queue. Let us
understand this with the help of an example.
Example:
Suppose the order of request is- (82,170,43,140,24,16,190)
And current position of Read/Write head is : 50
SSTF: In SSTF (Shortest Seek Time First), requests having shortest seek time
are executed first. So, the seek time of every request is calculated in advance in
the queue and then they are scheduled according to their calculated seek time.
As a result, the request near the disk arm will get executed first. SSTF is certainly
an improvement over FCFS as it decreases the average response time and
increases the throughput of system. Let us understand this with the help of an
example.
Example:
Suppose the order of request is- (82,170,43,140,24,16,190)
And current position of Read/Write head is : 50
=(50-43)+(43-24)+(24-16)+(82-16)+(140-82)+(170-40)+(190-170) =208
Advantages:
SCAN: In SCAN algorithm the disk arm moves into a particular direction and
services the requests coming in its path and after reaching the end of disk, it
reverses its direction and again services the request arriving in its path. So,
this algorithm works as an elevator and hence also known as elevator
algorithm. As a result, the requests at the midrange are serviced more and
those arriving behind the disk arm will have to wait.
Example:
So, the seek time is calculated as: = (190-50) + (190-16) + (43-16) =34