Os Lab Manual
Os Lab Manual
OPERATING SYSTEMS
LAB MANUAL
Prepared by
Dr. A.RAMAMURTHY
Professor
BHIMAVARAM-534202
(Approved by AICTE, New Delhi , ,Accredited by NAAC & Affiliated to JNTUK, Kakinada)
DNR COLLEGE OF ENGINEERING & TECHNOLOGY
(Permanently Affiliated to JNTUK, Kakinada,Accredited by NAAC , Approved by AICTE New Delhi)
2. Write a C program that makes a copy of a file using standard I/O, and system calls
3. Write a C program to emulate the UNIX ls –l command.
4. Write a C program that illustrates how to execute two commands concurrently
With a command pipe. Ex: - ls –l | sort
5) Simulate the following CPU scheduling algorithms: (a) Round Robin (b) SJF (c) FCFS (d) Priority
6) Multiprogramming-Memory management-Implementation of fork (), wait (), exec() and exit (),
System calls
7) Simulate the following: a) Multiprogramming with a fixed number of tasks (MFT) b)
Multiprogramming with a variable number of tasks (MVT)
8) Simulate Bankers Algorithm for Dead Lock Avoidance
9) Simulate Bankers Algorithm for Dead Lock Prevention
10) Simulate the following page replacement algorithms: a) FIFO b) LRU c) LFU
11) Simulate the following File allocation strategies (a) Sequenced (b) Indexed (c) Linked
12) Write a C program that illustrates two processes communicating using sharedmemory
13)Write a C program to simulate producer and consumer problem usingsemaphores
14)Write C program to create a thread using pthreads library and let it run its function.
15)Write a C program to illustrate concurrent execution of threads using pthreads library.
ADDITIONAL PROGRAMS
1. Write C programs that simulate the following UNIX command
a) mv b)cp (use system calls)
2. Write a C program that takes one or more file or directory names as command line input and reports
the following information on the file:
Laboratory – CO mapping
AY: 2020-21
C217. 2
4. Write a C program to emulate the UNIX ls –l command
Simulate the following CPU scheduling algorithms
5. a) Round Robin b) SJF c) FCFS d) Priority 217.1
PO / Related
PSO1
PSO2
PO10
PO11
PO12
PO1
PO2
PO3
PO4
PO5
PO6
PO7
PO8
PO9
CO Experiments
C217.1 1,3,5 3 2 - 2 - - - - 2 - 2 - 2 2
C217.2 2,4,13 3 2 2 2 - - - - 2 - 2 - 2 2
C217.3 6,7,14 3 2 2 2 - - - - 2 - 2 - 2 2
C217.4 8,9,10 3 2 2 - - - - - 2 - 2 - 2 2
C217.5 11,12,15 2 2 - 2 2 - - - 2 - 2 - 2 2
C217 - 2.6 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0
EXERCISE-1
1. a) Study of Unix/Linux general purpose utility command list
man, who, cat, cd, cp, ps, ls, mv, rm, mkdir, rmdir, echo, more, date, time, kill, history, chmod,
chown, finger, pwd, cal, logout, shutdown.
(i)man
Short for "manual," man allows a user to format and display the user manual built into Linux
distributions, which documents commands and other aspects of the system.
Syntax
man [option(s)] keyword(s)
WWW.VIDYARTHIPLUS.COM
Example
man ls
(ii)who:
identifies the users currently logged in
The "who" command lets you display the users that are currently logged into your UNIX computer
system. The following information is displayed: login name, workstation name, date
and time of login. Entering who am i or who am I displays your login name, workstation name,
date and time you logged in.
Synopsys
who [OPTION]... [ FILE | ARG1 ARG2 ]
Example
who am i
(iii) cat:
concatenate or display files
Synopsys
cat [- q] [- s] [- S] [- u] [- n[- b]] [- v [- [- t] ] [- | File ... ]
The cat command reads each File parameter in sequence and writes it to standard output. If you
do not specify a file name, the cat command reads from standard input. You can also specify a
file name of – (minus) for standard input.
Exit Status
This command returns the following exit values:
0 All input files were output successfully.
>0 An error occurred.
Examples
1. To display a file at the workstation, enter:
cat notes
2. To concatenate several files, enter:
cat section1.1 section1.2 section1.3 >section1
3. To suppress error messages about files that do not exist, enter:
cat -q section2.1 section2.2 section2.3 >section2
4. To append one file to the end of another, enter:
cat section1.4 >>section1
The >> appends a copy of section1.4 to the end of section1. If
you want to replace the file, use the >.YARTHIPLUS.COM
5. To add text to the end of a file, enter:
cat >>notes
Get milk on the way home
Ctrl-D
6. To concatenate several files with text entered from the keyboard,
cat section3.1 - section3.3 >section3
7. To concatenate several files with output from another command,
li | cat section4.1 - >section4
(iv) cd:
The cd command, which stands for "change directory", changes the shell's current working
directory.
Syntax
cd directory
Example
cd new
(v) cp:
(vi) ps:
Report a snapshot of the current processes.
Syatax:
ps [options]
(vii) ls
List directory contents
Syntax:
ls [option]
(viii) mv
Move or rename files
Syantax
mv [option] soure dest
Example:
mv file1 file2
(ix) rm
Remove files or directories
Syantax:
rm [option] filename
Example
rm file1
cat file1
cat: file1:No such file or directory.
(x) mkdir
Make directories
Syantax
mkdir [option] directoryname
Example:
mkdir cse
cd cse
~/cse$_
(xi) rmdir
Remove empty directories
Syntax:
rmdir [option] directoryname
Example:
rmdir cse
cd cse
bash:cd:cse: No such file or directory
(xii) echo
Display a line of text
Syntax:
echo [short_option] String
Example
echo “This is CSE World”
This is CSE World
(xiii) more
File perusal filter or crt viewing
Syntax:
more [-difpcsu] [-num] [+/pattern] [+linenumber]
Example
cat file1
BVCITS
This is CSE class
more +2 file1
This is CSE class
(xiv) date
Print or set the system date or time.
Syntax:
date [option] [format]
Example
date
Mon Jan 1 00:30:20 PST 2001
(xv) time
Run programs and summarize system resource usage.
Syntax:
time [format] [file]
(xvi) kill
Send a signal to a process
Syntax:
kill [-signal | -s signal] pid…
Example
Kill -1
(xvii) history
GNU history library.
Example:
history
vi 4ex.sh
sh 4b.sh
man cat…
(xviii) chmod
Change file mode
Syntax:
chmod [option] mode file
Example
Chmod 652 file1
-rw-r-x-w- bvcits bvcits 21 2001-01-01 00:37 file1
(xix) chown
Change the file owner and group
Syntax:
chown [option] [owner] [:[group]] file
Example
chown cse bvc
(xx) finger
The finger display information about the system user
Syntax:
Finger [-l] [-m] [-p] [-s] [username]
Example
finger abc
login:abc name:(null)
directory: /home/abc shell: /bin/bash
on since Mon Nov 1 18:45 (IST)
(xxi) pwd
Print name of the current working directory
Syntax:
pwd [option]
Example
pwd
/home/bvcits
(xxii)cal
Cal, ncal- displays a calendar and the date of easter
Syntax:
cal [-a number] [-b numer] [[mont] year]
Example
June 2018
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
(xxiii) logout
Syntax:
#include<utmp.h>
Void login(const struct utmp *ut);
Int logout(const char *utline);
Link with –lutil
(xxiv) shutdown
Bring the system down
Syntax:
Shutdown [option] time[message]
b) Study of vi editor.
How to Use the vi Editor
The vi editor is available on almost all Unix systems. vi can be used from any type of terminal
because it does not depend on arrow keys and function keys--it uses the standard alphabetic keys
for commands.
vi (pronounced "vee-eye") is short for "vi"sual editor. It displays a window into the file being
edited that shows 24 lines of text. vi is a text editor, not a "what you see is what you get" word
processor. vi lets you add, change, and delete text, but does not provide such formatting
capabilities as centering lines or indenting paragraphs.
This help note explains the basics of vi:WWW.VIDYARTHIPLUS.COM
opening and closing a file
moving around in a file
elementary editing
===== Starting vi =====
You may use vi to open an already existing file by typing
vi filename
where "filename" is the name of the existing file. If the file is not in your current directory, you
must use the full pathname.
Or you may create a new file by typing vi newname
where "newname" is the name you wish to give the new file.
To open a new file called "testvi," enter vi testvi
On-screen, you will see blank lines, each with a tilde (~) at the left, and a line at the bottom
giving the name and status of the new file:
~
~
"testvi" [New file]
===== vi Modes =====
vi has two modes:
command mode
insert mode
In command mode, the letters of the keyboard perform editing functions (like moving the cursor,
deleting text, etc.). To enter command mode, press the escape &<Esc> key.
In insert mode, the letters you type form words and sentences. Unlike many word processors, vi
starts up in command mode.
===== Entering Text =====
In order to begin entering text in this empty file, you must change from command mode to insert
mode. To do this, type ‘i'
Nothing appears to change, but you are now in insert mode and can begin typing text. In
general, vi's commands do not display on the screen and do not require the Return key to be
pressed.
Type a few short lines and press &<Return> at the end of each line. If you type a long line, you
will notice the vi does not word wrap, it merely breaks the line unceremoniously at the edge of
the screen. If you make a mistake, pressing <Backspace> or <Delete> may remove the error,
depending on your terminal type.
===== Moving the Cursor =====
To move the cursor to another position, you must be in command mode. If you have just
finished typing text, you are still in insert mode. Go back to command mode by pressing <Esc>.
If you are not sure which mode you are in, press <Esc> once or twice until you hear a beep.
When you hear the beep, you are in command mode.
The cursor is controlled with four keys: h, j, k, l.
Key Cursor Movement
h left one space
j down one line
k up one line
l right one space
When you have gone as far as possible in one direction, the cursor stops moving and you hear a
beep. For example, you cannot use l to move right and wrap around to the next line, you must
use j to move down a line. See the section entitled "Moving Around in a File" for ways to move
more quickly through a file.
Basic Editing
Editing commands require that you be command mode. Many of the editing commands have a
different function depending on whether they are typed as upper- or lowercase. Often, editing
commands can be preceded by a number to indicate a repetition of the command.
Deleting Characters
To delete a character from a file, move the cursor until it is on the incorrect letter, then type ‘x’
The character under the cursor disappears. To remove four characters (the one under the cursor
and the next three) type 4x
To delete the character before the cursor, type X (uppercase)
Deleting Words
To delete a word, move the cursor to the first letter of the word, and type dw
This command deletes the word and the space following it. To delete three words type 3dw
Deleting Lines
To delete a whole line, type dd
The cursor does not have to be at the beginning of the line. Typing dd deletes the entire line
containing the cursor and places the cursor at the start of the next line. To delete two lines, type
2dd. To delete from the cursor position to the end of the line, type D (uppercase)
Replacing Characters
To replace one character with another:WWW.VIDYARTHIPLUS.COM
1. Move the cursor to the character to be replaced.
2. Type r
3. Type the replacement character.
The new character will appear, and you will still be in command mode.
Replacing Words
To replace one word with another, move to the start of the incorrect word and type cw
The last letter of the word to be replaced will turn into a $. You are now in insert mode and may
type the replacement. The new text does not need to be the same length as the original.
Press <Esc> to get back to command mode. To replace three words, type 3cw
Replacing Lines
To change text from the cursor position to the end of the line:
1. Type C (uppercase).
2. Type the replacement text.
3. Press <Esc>.
Inserting Text
To insert text in a line:
1. Position the cursor where the new text should go.
2. Type i
3. Enter the new text. The text is inserted BEFORE the cursor.
4. Press <Esc> to get back to command mode.
Appending Text
To add text to the end of a line:
1. Position the cursor on the last letter of the line.
2. Type a
3. Enter the new text. This adds text AFTER the cursor.
4. Press <Esc> to get back to command mode.
Opening a Blank Line
To insert a blank line below the current line, type o (lowercase)
To insert a blank line above the current line, type O (uppercase)
Joining Lines
To join two lines together:
1. Put the cursor on the first line to be joined.
2. Type J
To join three lines together:
1. Put the cursor on the first line to be joined.
2. Type 3J
===== Undoing =====
To undo your most recent edit, type uWWW.VIDYARTHIPLUS.COM
To undo all the edits on a single line, type U (uppercase)
Undoing all edits on a single line only works as long as the cursor stays on that line. Once you
move the cursor off a line, you cannot use U to restore the line.
===== Moving Around in a File =====
There are shortcuts to move more quickly though a file. All these work in command mode.
Key Movement
w forward word by word
b backward word by word
$ to end of line
0 (zero) to beginning of line
H to top line of screen
M to middle line of screen
L to last line of screen
G to last line of file
1G to first line of file
<Control>f scroll forward one screen
<Control>b scroll backward one screen
<Control>d scroll down one-half screen
<Control>u scroll up one-half screen
===== Moving by Searching =====
To move quickly by searching for text, while in command mode:
1. Type / (slash).
2. Enter the text to search for.
3. Press <Return>.
The cursor moves to the first occurrence of that text.
To repeat the search in a forward direction, type n
To repeat the search in a backward direction, type N
===== Closing and Saving a File =====
With vi, you edit a copy of the file, rather than the original file. Changes are made to the original
only when you save your edits.
To save the file and quit vi, type ZZWWW.VIDYARTHIPLUS.COM
The vi editor is built on an earlier Unix text editor called ex. ex commands can be used within
vi. ex commands begin with a : (colon) and end with a <Return>. The command is displayed on
the status line as you type. Some ex commands are useful when saving and closing files.
To save the edits you have made, but leave vi running and your file open:
1. Press <Esc>.
2. Type :w
3. Press <Return>.
To quit vi, and discard any changes your have made since last saving:
1. Press <Esc>.
2. Type :q!
3. Press <Return>.
c) Study of Bash shell, Bourne shell and C shell in Unix/Linux operating system.
Types of Shells in Linux
In addition to graphical user interfaces like Gnome, KDE and MATE, the Linux operating
system also offers several shells. These command-line interfaces provide powerful environments
for software development and system maintenance. Though shells have many commands in
common, each type has unique features. Over time, individual programmers come to prefer one
type of shell over another; some develop new, enhanced shells based on previous ones. UNIX
also has an ecosystem of different shells; Linux carries this practice into the open-source
software arena.
The Bourne shell
The Bourne shell, called "sh," is one of the original shells, developed for Unix computers by
Stephen Bourne at AT&T's Bell Labs in 1977. Its long history of use means many software
developers are familiar with it. It offers features such as input and output redirection, shell
scripting with string and integer variables, and condition testing and looping.
The Bash shell
The popularity of sh motivated programmers to develop a shell that was compatible with it, but
with several enhancements. Linux systems still offer the sh shell, but "bash" -- the "Bourne-again
Shell," based on sh -- has become the new default standard. One attractive feature of bash is its
ability to run sh shell scripts unchanged. Shell scripts are complex sets of commands that
automate programming and maintenance chores; being able to reuse these scripts saves
programmers time. Conveniences not present with the original Bourne shell include command
completion and a command history.WWW.VIDYARTHIPLUS.COM
C Shell
Developers have written large parts of the Linux operating system in the C and C++ languages.
Using C syntax as a model, Bill Joy at Berkeley University developed the "C-shell," csh, in
1978. Ken Greer, working at Carnegie-Mellon University, took csh concepts a step forward with
a new shell, tcsh, which Linux systems now offer. Tcsh fixed problems in csh and added
command completion, in which the shell makes educated "guesses" as you type, based on your
system's directory structure and files. Tcsh does not run bash scripts, as the two have substantial
differences.
The Korn shell
David Korn developed the Korn shell, or ksh, about the time tcsh was introduced. Ksh is
compatible with sh and bash. Ksh improves on the Bourne shell by adding floating-point
arithmetic, job control, and command aliasing and command completion. AT&T held proprietary
rights to ksh until 2000, when it became open source.
A UNIX filesystem is a collection of files and directories that has the following properties −
It has a root directory (/) that contains other files and directories.
Each file or directory is uniquely identified by its name, the directory in which it resides,
and a unique identifier, typically called an inode.WWW.VIDYARTHIPLUS.COM
By convention, the root directory has an inode number of 2 and the lost+found directory
has an inode number of 3. Inode numbers 0 and 1 are not used. File inode numbers can
be seen by specifying the -i option to ls command.
It is self contained. There are no dependencies between one filesystem and any other.
The directories have specific purposes and generally hold the same types of information for
easily locating files. Following are the directories that exist on the major versions of Unix −
Directory Description
/ This is the root directory which should contain only the
directories needed at the top level of the file structure.
/bin This is where the executable files are located. They are
available to all user.
/dev These are device drivers.
/etc Supervisor directory commands, configuration files, disk
configuration files, valid user lists, groups, ethernet,
hosts, where to send critical messages
/lib Contains shared library files and sometimes other kernel
related files.
/boot Contains files for booting the system.
/home Contains the home directory for users and other accounts.
/mnt Used to mount other temporary file systems, such as
cdrom and floppy for the CDROM drive and floppy
diskette drive, respectively
/proc Contains all processes marked as a file by process
number or other information that is dynamic to the
system.
/tmp Holds temporary files used between system boots
/usr Used for miscellaneous purposes, or can be used by
many users. Includes administrative commands, shared
files, library files, and others
/var Typically contains variable length files such as log and
print files and any other type of file that may contain a
variable amount of data
/sbin Contains binary (executable) files, usually for system
administration. For example fdisk and ifconfig utlities.
/kernel Contains kernel files
Program:
#include<fcntl.h>
#include<unistd.h>
int main(int argc, char **argv)
{
int n,size,fd1,fd2;
char c;
fd1 = open(argv[1],O_RDONLY);
fd2 = open(argv[2],O_WRONLY);
size = lseek(fd1, -1, SEEK_END);
n = lseek(fd1, 0, SEEK_SET);
while(n++ < size)
{
read(fd1, &c,1);
write(fd2, &c,1);
}
}
EXERCISE-3
Program:
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>YARTHIPLUS.COM
#include <sys/types.h>
#include <stdlib.h>
int main()
{
int pid;
pid = fork();
if(pid<0)
{
printf(“\n Child process creation failed”);
exit(-1);
}
else if(pid == 0)
{
execlp(“/bin/ls”, “ls”, ‘-l”, NULL);
}
else
{
wait(NULL);
printf(“\n child process completed”);
exit(0);
}
}
EXERCISE-4
4. Write a C program that illustrates how to execute two commands concurrently with a
command pipe.
Program:
#include<stdio.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
int fd[2],pid,k;
WWW.VIDYARTHIPLUS.COM
k=pipe(fd);
if(k==-1)
{
perror("pipe");
exit(1);
}
pid=fork();
if(pid==0)
{
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp(argv[1],argv[1],NULL);
perror("execl");
}
else
{
wait(2);
close(fd[1]);
dup2(fd[0],0);
close(fd[0]);
execlp(argv[2],argv[2],NULL);
perror("execl");
}
}
EXERCISE-5
a)ROUND ROBIN:
DESCRIPTION:
Once a process is executed for a given time period, it is preempted and other process
executes for a given time period.
Context switching is used to save states of preempted processes.
PROGRAM:
CHR
/* C Program to implement Round Robin CPU Scheduling Algorithm */
K
#include<stdio
.h> int main()
{
int count,j,n,time,remain,flag=0,time_quantum;
int
wait_time=0,turnaround_time=0,at[10],bt[10],rt[
10]; printf("Enter Total Process:\t ");
scanf("%d",&
n); remain=n;
for(count=0;count<n;count++)
{
printf("Enter Arrival Time and Burst Time for Process Process Number %d :",count+1);
scanf("%d",&at[count]);
scanf("%d",&bt[count]);
rt[count]=bt[count];
}
printf("Enter Time Quantum:\t");
scanf("%d",&time_quantum); printf("\n\
nProcess\t|Turnaround Time|Waiting Time\n\n");
for(time=0,count=0;remain!=0;)
{
if(rt[count]<=time_quantum && rt[count]>0)
{
time+=rt[cou
nt];
rt[count]=0;
flag=1;
}
else if(rt[count]>0)
{
rt[count]-=time_quantum;
time+=time_quantum;
}
if(rt[count]==0 && flag==1)
{
remain--;
printf("P[%d]\t|\t%d\t|\t%d\n",count+1,time-at[count],time-
at[count]-bt[count]); wait_time+=time-at[count]-bt[count];
turnaround_time+=time-
at[count]; flag=0;
}
if(count==n
-1)
count=0;
else
if(at[count+1]<=tim
e) count++;
else
count=0;
}
printf("\nAverage Waiting Time= %f\
n",wait_time*1.0/n); printf("Avg Turnaround Time
= %f",turnaround_time*1.0/n);
return 0;
}
b) SJF:
DESCRIPTION:
Impossible to implement in interactive systems where required CPU time is not known.
The processer should know in advance how much time process will take.
PROGRAM:
CHR
/* C Program to implement SJF CPU Scheduling Algorithm */
#include<stdio
K
.h> void
main()
{
int
bt[20],p[20],wt[20],tat[20],i,j,n,total=0,pos,t
emp; float avg_wt,avg_tat;
printf("Enter number of
process:"); scanf("%d",&n);
printf("\nEnter Burst
Time:\n"); for(i=0;i<n;i+
+)
{
printf("p%d:",i+1);
scanf("%d",&bt
[i]); p[i]=i+1;
}
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(bt[j]<bt[pos]
) pos=j;
}
temp=bt[i];
bt[i]=bt[po
s];
bt[pos]=te
mp;
temp=p[i];
p[i]=p[pos]
;
p[pos]=tem
p;
CHR
}
wt[0]=
0;
for(i=1;i<n;i++)
K
{
wt[i]=0;
for(j=0;j<i;j
++) wt[i]
+=bt[j];
total+=wt[i];
}
avg_wt=(float)total
/n; total=0;
printf("\nProcess\t Burst Time \tWaiting Time\
tTurnaround Time"); for(i=0;i<n;i++)
{
tat[i]=bt[i]
+wt[i];
total+=tat[i];
printf("\np%d\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
avg_tat=(float)total/n;
printf("\n\nAverage Waiting Time=
%f",avg_wt); printf("\nAverage
Turnaround Time=%f\n",avg_tat);
}
c) FCFS:
DESCRIPTION:
PROGRAM:
#include<stdio
.h> main()
{
int n,a[10],b[10],t[10],w[10],g[10],i,m;
float
att=0,awt=0;
for(i=0;i<10;i++)
{
K
scanf("%d",&b[i]); printf("\
nenter the arrival times");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
g[0]=0;
for(i=0;i<10;i+
+) g[i+1]=g[i]
+b[i];
for(i=0;i<n;i+
+)
{
w[i]=g[i]-a[i];
t[i]=g[i+1]-
a[i];
awt=awt+w[
i];
att=att+t[i];
awt
=awt/n;
att=att/n;
printf("\n\tprocess\twaiting time\tturn arround
time\n"); for(i=0;i<n;i++)
{
printf("\tp%d\t\t%d\t\t%d\n",i,w[i],t[i]);
d)PRIORITY:
DESCRIPTION:
Processes with same priority are executed on first come first served basis.
CHR
Priority can be decided based on memory requirements, time requirements or any other
resource requirement.
PROGRAM:
int main()
int
bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_t
at; printf("Enter Total Number of Process:");
scanf("%d",&n);
printf("\nP[%d]\
n",i+1);
printf("Burst
Time:");
scanf("%d",&bt[i]);
printf("Priority:");
scanf("%d",&pr[i])
; p[i]=i+1;
}
for(i=0;i<n;i++)
pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[po
s]) pos=j;
}
temp=pr[i];
pr[i]=pr[po
s];
CHR
K
pr[pos]=te
mp;
temp=bt[i];
bt[i]=bt[po
s];
bt[pos]=te
mp;
temp=p[i];
p[i]=p[pos
];
p[pos]=te
mp;
}
wt[0]=
0;
for(i=1;i<n;i++)
wt[i]=0;
for(j=0;j<i;j
++) wt[i]
+=bt[j];
total+=wt[i];
avg_wt=total
/n; total=0;
printf("\nProcess\t Burst Time \tWaiting Time\
tTurnaround Time"); for(i=0;i<n;i++)
{
tat[i]=bt[i]
+wt[i];
total+=tat[i];
printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
CHR
}
avg_tat=total/n;
K
%d",avg_wt); printf("\nAverage
Turnaround Time=%d\n",avg_tat); return 0;
OUTPUT:
P[1]
Burst
Time: 6
Priority:3
P[2]
Burst
Time: 2
Priority:2
P[3]
Burst Time:
14
Priority:1
P[4]
Burst
Time: 6
Priority:4
CHR
Time
P[3] 14 0 14
P[2] 2 14 16
P[1] 6 16 22
K
P[4] 6 22 28
Average Waiting
Time=13 Average
Turnaround Time=20
EXERCISE-6
DESCRIPTION:
FORK():
Fork system call use for creates a new process, which is called child process, which runs
concurrently with process (which process called system call fork) and this process is called
parent process. After a new child process created, both processes will execute the next
instruction following the fork() system call. A child process uses the same pc(program counter),
same CPU registers, same open files which use in the parent process.
EXEC():
CHR
The exec family of functions replaces the current running process with a new process. It can be
used to run a C program by using another C program. It comes under the header file unistd.h.
There are many members in the exec family which are shown below with examples.
execvp : Using this command, the created child process does not have to run the same
program as the parent process does. The exec type system calls allow a process to run any
program files, which include a binary executable or a shell script .
Syntax:
file: points to the file name associated with the file being executed.
execv : This is very similar to execvp() function in terms of syntax as well. The syntax of
execv() is as shown below:
Syntax:
int execlp(const char *file, const char *arg,.../* (char *) NULL */);
int execl(const char *path, const char *arg,.../* (char *) NULL */);
execvpe and execle : These two also serve the same purpose but the syntax of them are a
bit different from all the above members of exec family. The synatxes of both of them are
shown below :
Syntax:
Syntax:
int execle(const char *path, const char *arg, .../*, (char *) NULL,
WAIT() :
CHR
K
A call to wait() blocks the calling process until one of its child processes exits or a signal is
received. After child process terminates, parent continues its execution after wait system call
instruction.
Child process may terminate due to any of these:
It calls exit();
It receives a signal (from the OS or another process) whose default action is to terminate.
EXIT():
It terminates the calling process without executing the rest code which is after the exit()
function.
FORK():
PROGRAM:
#include <stdio.h>
#include
<sys/types.h>
CHR
K
#include
<unistd.h> void
forkexample()
{
if (fork() == 0)
else
}
int main()
forkexample
(); return 0;
}
OUTPUT:
EXEC():
PROGRAM:
#include <stdio.h>
#include
CHR
<sys/types.h>
#include
<unistd.h>
#include
<stdlib.h>
K
#include <errno.h>
#include
<sys/wait.h> int
main()
{
pid_t pid;
int ret = 1;
int status;
pid =
fork(); if
(pid == -
1)
{
printf("can't fork, error
occured\n");
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
else{
if (WIFEXITED(status) && !
WEXITSTATUS(status)) printf("program
execution successfull\n");
else if (WIFEXITED(status) && WEXITSTATUS(status))
CHR
if (WEXITSTATUS(status) == 127)
printf("execv failed\n");
else K
printf("program terminated
normally," " but returned a non-
zero status\n");
}
else
printf("program didn't terminate normally\n");
else
printf("waitpid() failed\n");
exit(0);
}
return 0;
WAIT() :
PROGRAM:
CHR
/* C Program to implement Wait() system calls */
#include<stdio.h>
K
#include<stdlib.h>
#include<sys/wait.
h>
#include<unistd.h
>
int main()
pid_t cpid;
if (fork()== 0)
exit(0
); else
cpid = wait(NULL);
EXIT():
PROGRAM:
#include
<stdio.h>
#include
<stdlib.h> int
main(void)
{
CHR
printf("STAR
T"); exit(0);
printf("End of program");
}
EXERCISE-7
DESCRIPTION:
MFT : Multiprogramming with a Fixed number of Tasks is one of the old memory management
techniques in which the memory is partitioned into fixed size partitions and each job is assigned to a
partition. The memory assigned to a partition does not change.
MVT : Multiprogramming with a Variable number of Tasks is the memory management technique
CHR
in which each job gets just the amount of memory it needs. That is, the partitioning of memory is
dynamic and changes as jobs enter and leave the system. MVT is a more ``efficient'' user of
resources. MFT suffers with the problem of internal fragmentation and MVT suffers with external
fragmentation.
PROGRAM
#include<stdio.
h>
#include<conio
K
/* C Program to implement Multiprogramming with a fixed number of tasks (MFT)*/
.h> main()
{
{
printf("Enter memory required for process %d (in
Bytes)-- ",i+1); scanf("%d",&mp[i]);
}
CHR
for(i=0;i<n && p<nob;i++)
printf("\n %d\t\t
K
%d",i+1,mp[i]); if(mp[i] >
bs)
printf("\t\tNO\t\
t---"); else
{
printf("\t\tYES\t%d",bs-
mp[i]); tif = tif + bs-
mp[i];
p++;
if(i<n)
PROGRAM:
#include<stdio.h>
#include<conio
.h> main()
{
int ms,mp[10],i,
temp,n=0; char ch =
'y';
clrscr();
CHR
if(mp[i]<=temp)
K
%d ",i+1); temp = temp - mp[i];
}
else
printf("\nMemory is
Full"); break;
}
DESCRIPTION:
The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests for
safety by simulating the allocation for predetermined maximum possible amounts of all resources,
then makes an “s-state” check to test for possible activities, before deciding whether allocation
should be allowed to continue.
Following Data structures are used to implement the Banker’s Algorithm:
Let ‘n’ be the number of processes in the system and ‘m’ be the number of resources types.
Available :
It is a 1-d array of size ‘m’ indicating the number of available resources of each type.
CHR
Available[ j ] = k means there are ‘k’ instances of
resource type Rj Max :
It is a 2-d array of size ‘n*m’ that defines the maximum demand of each process in a system.
Max[ i, j ] = k means process Pi may request at most ‘k’ instances of resource type Rj.
Allocation :
K
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.
PROGRAM:
#include <stdlib.h>
int main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10];
count = 0;
scanf("%d", &p);
CHR
completed[i] = 0;
K
scanf("%d", &r);
scanf("%d", &Max[i][j]);
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
scanf("%d", &avail[i]);
CHR
do
{
K
for( j = 0; j < r; j++)
printf("\t\t");
printf("\n");
process = -1;
for(i = 0; i < p; i++)
{
process = i ;
process = -1;
break;
CHR
if(process != -1)
break;
if(process != -1)
{
K
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1;
count++;
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
}
}
if(count == p)
printf(">\n");
else
}
CHR
K
EXERCISE-9
DESCRIPTION: We can prevent Deadlock by eliminating any of the above four condition.
CHR
Eliminate Circular Wait: Each resource will be assigned with a numerical number. A
process can request for the resources only in increasing order of numbering.
PROGRAM:
#include<stdio.h
> void main()
K
/* C Program to implement Dead Lock Prevention using Banker’s algorithm */
int max[10][10],a1[10][10],av[10],i,j,k,m,n,ne[10]
[10],flag=0; printf("\nEnter the matrix dimensions:");
scanf("%d%d",&m,&n);
for(j=0;j<n;j++)
scanf("%d",&max[i][j]);
for(j=0;j<n;j++)
scanf("%d",&a1[i][j]);
CHR
}
}
K
printf("\n The need matrix:\
n"); for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
ne[i][j]=max[i][j]-a1[i][j];
printf("\t%d",ne[i][j]);
printf("\n");
scanf("%d",&av[i]);
for(j=0;j<n;j++)
printf("\t%d",max[i][j]);
CHR
}
printf("\n");
K
}
for(j=0;j<n;j++)
{
printf("\t%d",a1[i][j]);
printf("\n");
printf("%d\t",av[i]);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
{
CHR
if(av[i]>=ne[i][j])
flag=1;
else
K
flag=0;
}
if(flag==0)
printf("\n Unsafe
state"); else
}
EXERCISE-10
DESCRIPTION:
a) FIFO :
This is the simplest page replacement algorithm. In this algorithm, operating system
keeps track of all pages in the memory in a queue, oldest page is in the front of the queue. When a
page needs to be replaced page in the front of the queue is selected for removal.
PROGRAM:
CHR
K
/* C Program to implement FIFO Page Replacement algorithms */
int
i,j,n,a[50],frame[10],no,k,avail,count=0;
printf("\n ENTER THE NUMBER OF
PAGES:\n");
scanf("%d",&n);
for(i=1;i<=n;i+
+)
scanf("%d",&a[
i]);
printf("\n ENTER THE NUMBER OF FRAMES :");
scanf("%d",&n
o);
for(i=0;i<no;i
++)
frame[i]=
-1; j=0;
printf("\tref string\t page
frames\n"); for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
frame[j]=a[i];
CHR
j=(j+1)%no;
count++;
for(k=0;k<no;k
++)
printf("%d\t",frame[k]);
}
}
K
printf("\n");
printf("Page Fault Is
%d",count); return 0;
}
b)LRU:
On a page fault, the frame that was least recently used in replaced.
PROGRAM:
#include<stdio
.h> main()
{
int
q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20]
; printf("Enter no of pages:");
scanf("%d",&n);
CHR
printf("Enter the reference
string:"); for(i=0;i<n;i++)
scanf("%d",&p[i]);
printf("Enter no of
K
frames:");
scanf("%d",&f);
q[k]=p[k]; printf("\n\t
%d\n",q[k]); c++;
k++;
for(i=1;i<n;i++)
c1=0;
for(j=0;j<f;j++)
if(p[i]!
=q[j]) c1+
+;
}if(c1==f)
c++;
if(k<f)
q[k]=p[i
]; k++;
for(j=0;j<k;j+
+) printf("\t
%d",q[j]);
printf("\n");
}
else
CHR
for(r=0;r<f;r++)
c2[r]=0;
K for(j=i-1;j<n;j--)
if(q[r]!
=p[j])
c2[r]++;
else
brea
k;
}
for(r=0;r<f;r
++)
b[r]=c2[r];
for(r=0;r<f;r
++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
t=b[r];
b[r]=b[j
];
b[j]=t;
}
for(r=0;r<f;r++)
if(c2[r]==b[0])
q[r]=p[i];
printf("\t
%d",q[r]);
CHR
}
printf("\n");
}
}
K
printf("\nThe no of page faults is %d",c);
}
c) LFU:
Pages with a current copy on disk are first choice for pages to be removed when more
memory is needed. To facilitate Page Replacement Algorithms, a table of valid or invalid bits (also
called dirty bits) is maintained.
PROGRAM:
CHR
/* C Program to implement LFU Page Replacement algorithms */
#include<stdio.h>
#include<conio.h>
int fr[3];
K
void main()
void display();
int p[12]={2,3,2,1,5,2,4,5,3,2,5,2},i,j,fs[3];
int index,k,l,flag1=0,flag2=0,pf=0,frsize=3;
clrscr();
for(i=0;i<3;i++)
fr[i]=-1;
for(j=0;j<12;j++)
flag1=0,flag2=0;
for(i=0;i<3;i++)
{
if(fr[i]==p[j])
flag1=1;
flag2=1;
break;
CHR
}
if(flag1==0)
for(i=0;i<3;i++)
K
{
if(fr[i]==-1)
fr[i]=p[j];
flag2=1;
break;
}
if(flag2==0)
for(i=0;i<3;i++)
fs[i]=0;
for(k=j-1,l=1;l<=frsize-1;l++,k--)
for(i=0;i<3;i++)
if(fr[i]==p[k])
fs[i]=1;
for(i=0;i<3;i++)
if(fs[i]==0)
CHR
index=i;
fr[index]=p[j];
pf++;
}
K
display();
getch();
void display()
int i;
printf("\n");
for(i=0;i<3;i++)
printf("\t%d",fr[i]);
EXERCISE-11
PROGRAM:
/* C Program to implement Sequenced File allocation strategies */
#include <
stdio.h>
#include<conio
.h> void main()
{
for(j=st;j<(st+len);j+
+) if(f[j]==0)
{ f[j]
=1;
printf("%d\t%d\n",j,f[j]);
if(j!=(st+len-1))
CHR
else
b)INDEXED : CHR
A special block known as the Index block contains the pointers to all the blocks occupied by a
K
file. Each file has its own index block. The ith entry in the index block contains the disk address of
the ith file block. The directory entry contains the address of the index block as shown in the
image
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h> void main()
{
else
{
CHR
n",ind); goto x;
}
y: count=0;
for(i=0;i<n;i
K
++)
{
scanf("%d", &index[i]);
if(f[index[i]]=
=0) count++;
}
if(count==n)
for(j=0;j<n;j++)
f[index[j]]=1;
printf("Allocated\
n"); printf("File
Indexed\n");
for(k=0;k<n;k++)
printf("%d---->%d : %d\n",ind,index[k],f[index[k]]);
}
else
CHR
getch();
c)LINKED :
K
Each file is a linked list of disk blocks which need not be contiguous. The disk blocks can be
scattered anywhere on the disk. The directory entry contains a pointer to the starting and the
ending file block. Each block contains a pointer to the next block occupied by the file.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
scanf("%d",&
a); f[a]=1;
}
CHR
x: printf("Enter index starting block and
length: "); scanf("%d%d", &st,&len);
k=len;
K
if(f[st]==
0)
{
for(j=st;j<(st+k);j++)
if(f[j]==0)
{ f[j]
=1;
printf("%d---->%d\n",j,f[j]);
else
else
}
OUTPUT: CHR
Enter how many blocks already
K
allocated: 3 Enter blocks already
allocated:1 3 5
Enter index starting block and
length: 2 4
2 >1
3 Block is already
allocated 4 > 1
5 Block is already
allocated 6 > 1
7 >1
SOURCE CODE:
#include<stdio.h>
int mutex=1,full=0,empty=3,x=0;
main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf(“\n 1.Producer \n 2.Consumer \n 3.Exit”);
while(1)
{
printf(“\n Enter your choice:”);
scanf(“%d”,&n);
switch(n)
{
case 1:
if((mutex==1)&&(empty!=0))
producer();
else
printf(“Buffer is full”);
break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else
printf(“Buffer is empty”);
break;
case 3:
exit(0);
break;
}
}
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf(“\n Producer produces the item %d”,x);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf(“\n Consumer consumes item %d”,x);
x--;
mutex=signal(mutex);
}
EXERCISE-13
Write a C program that illustrates two processes communicating using shared memory
Description :
Shared memory is the fastest form of IPC available. Once the memory is mapped into the
address space of the processes that are sharing the memory region, no kernel involvement occurs
in passing data between the processes. What is normally required, however, is some form of
synchronization between the processes that are storing and fetching information to and from the
shared memory region. Shared memory is the most useful of the 3 structures. All the other IPC
structures have similar system calls. Shared memory is memory that is accessible to a number of
processes. By several orders of magnitude, it is the quickest way of sharing information among a
set of processes. Keep in mind that shared memory is available on all operating systems. Only
the calls will be different.
Syntax :
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int shmget ( key_t key, size_t size, int shmflg)
Algorithm :
Step 1: Start
Step 2 : Create a shared memory using mhmget().
Step 3 : Store integer value in shared memory. (shmat())
Step 4 : Create a child process using fork().
Step 5 : Get a semaphore on shared memory using semget().
Step 6 : Increase the value of shared variable
Step 7 : Release the semaphore
Step 8 : Repeat step 4,5,6 in child process also.
Step 9 : Remove shared memory
Step 10: Stop
Program :
#include<stdio.h>
#include<sys/ipc.h>
#include<sys/stat.h>
#include<sys/msg.h>
#include<sys/sem.h>
#include<string.h>
int main()
{
int shmid,sid=-1;
int shmptr;
pid_t pid;
shmid=shmget(20,1024,0644|IPC_CREAT);
shmptr=shmat(shmid,0,0);
if(shmptr==1)
printf("error\n");
else
printf("\nshared memory created\n");
if(sid<0)
{
if((sid=shmget(30,1,IPC_CREAT|0644))<0)
printf("\nsemaphore is created");
else
printf("semaphore is not created\n");
}
printf("\nenter integer value");
scanf("%d",&shmptr);
printf("the entered value is:%d\n",shmptr);
if((pid=fork())==0)
{
wait(sid);
shmptr+=1;
printf("child value is:%d\n",shmptr);
signal(sid);
}
else if(pid>0)
{
shmptr-=1;
printf("the parent value is :%d\n",shmptr);
}
}
EXERCISE-14
Write C program to create a thread using pthreads library and let it run its function.
What is a Thread?
A thread is a single sequence stream within in a process. Because threads have some of the
properties of processes, they are sometimes called lightweight processes.
What are the differences between process and thread?
Threads are not independent of one other like processes as a result threads shares with other
threads their code section, data section and OS resources like open files and signals. But, like
process, a thread has its own program counter (PC), a register set, and a stack space.
Why Multithreading?
Threads are popular way to improve application through parallelism. For example, in a browser,
multiple tabs can be different threads. MS word uses multiple threads, one thread to format the
text, other thread to process inputs, etc.
Threads operate faster than processes due to following reasons:
1) Thread creation is much faster.
2) Context switching between threads is much faster.
3) Threads can be terminated easily
4) Communication between threads is faster.
In main() we declare a variable called thread_id, which is of type pthread_t, which is an integer
used to identify the thread in the system. After declaring thread_id, we call pthread_create()
function to create a thread.
pthread_create() takes 4 arguments.
The first argument is a pointer to thread_id which is set by this function.
The second argument specifies attributes. If the value is NULL, then default attributes shall be
used.
The third argument is name of function to be executed for the thread to be created.
The fourth argument is used to pass arguments to the function, myThreadFun.
The pthread_join() function for threads is the equivalent of wait() for processes. A call to
pthread_join blocks the calling thread until the thread with identifier equal to the first argument
terminates.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> //Header file for sleep(). man 3 sleep for details.
#include <pthread.h>
int main()
{
pthread_t thread_id;
printf("Before Thread\n");
pthread_create(&thread_id, NULL, myThreadFun, NULL);
pthread_join(thread_id, NULL);
printf("After Thread\n");
exit(0);
}
EXERCISE-15
A concurrent programming environment lets us designate tasks that can run in parallel. It also
lets us specify how we would like to handle the communication and synchronization issues that
result when concurrent tasks attempt to talk to each other and share data.
Because most concurrent programming tools and languages have been the result of
academic research or have been tailored to a particular vendor’s products, they are often
inflexible and hard to use. Pthreads, on the other hand, is designed to work across multiple
vendors’ platforms and is built on top of the familiar UNIX C programming interface. Pthreads
gives you a simple and portable way of expressing multithreading in your programs.
Program:
#include<stdlib.h>
#include<pthread.h>
void *mythread1(void *vargp)
{
int i;
printf("thread1\n");
for(i=1;i<=10;i++)
printf("i=%d\n",i);
printf("exit from thread1\n");
return NULL;
}
void *mythread2(void *vargp)
{
int j;
printf("thread2 \n");
for(j=1;j<=10;j++)
printf("j=%d\n",j);
printf("Exit from thread2\n");
return NULL;
}
int main()
{
pthread_t tid;
printf("before thread\n");
pthread_create(&tid,NULL,mythread1,NULL);
pthread_create(&tid,NULL,mythread2,NULL);
pthread_join(tid,NULL);
pthread_join(tid,NULL);
exit(0);
}
ADDITIONAL PROGRAMS
a) mv – to rename a file
Accepet old file name and new file name
Use rename( ) to rename; if file exists
Print error; otherwise
The C Program:
#include <stdio.h>
main()
{
char oldname[67],newname[67];
int r;
printf("Enter old filename : ");
scanf("%s",oldname);
printf("Enter new filename : ");
scanf("%s",newname);
r=rename(oldname,newname);
if(r==0)
printf("File %s renamed to %s\n", oldname,newname);
else
printf("Rename error\n");
return (0);
}
Process logic:
Open source file in read mode
Open target file in write mode
Read from source file and write to target file character by character up to end of sourcefile.
The C Program:
/*file week11b.c
to copy contents of a file to another */
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char **argv)
{
int n,size, fd1, fd2;
char c;
fd1=open(argv[1],O_RDONLY);
fd2=open(argv[2],O_WRONLY);
size=lseek(fd1,-1,SEEK_END);
n=lseek(fd1,0,SEEK_SET);
while(n++<size)
{
read(fd1,&c,1);
write(fd2,&c,1);
}
}
2. Write a C program that takes one or more file or directory names as command line input
and reports the following information on the file:
a) file type
b) number of links
c) read, write and execute permission
d) Time of last access (use stat/fstat system calls)
Process logic:
Accept the file names from command line argument
Use structure struct stat to display the fileds of the structure:
st_mode for type and access permission ( in octal 4 to read 2 to write 1 to execute 7 for rwx)
st_nlink for number of links
st_atime for last access time
The C Program: (To compile gcc cfile.c to run last compiled file ./a.out )
Program:
to display file attributes */
#include <stdio.h>
#include <sys/stat.h>
int main(int argc, char **argv)
{
struct stat statbuf;
int k;
for(k=1;k<argc;k++)
{
if(lstat(argv[1], &statbuf)==1) printf("can’t stat file\n");
else
{
printf("File : %s\n",argv[k]);
printf("Type and permission : %o\n",statbuf.st_mode);
printf("Number of links %d\n",statbuf.st_nlink);
printf("Time of last access: %s\n",ctime(&statbuf.st_atime));
}
}
}