0% found this document useful (0 votes)
72 views

S.N O. Topics For Practice: Content

The document discusses various basic UNIX commands like date, cal, echo, ls, who, uptime, uname, hostname, bc, man, cat, grep, rm, touch, cp, mv, cut, head, tail, chmod, and wc. It provides the syntax and examples of using these commands to check date and time, display calendar, print messages, list files, view user information, check system uptime, view system information, set hostname, use calculator, view manual pages, create, view, concatenate files, search files, delete files, create blank files, copy and move files between locations, cut/view parts of files, view starting/ending lines of files, modify file permissions, and count

Uploaded by

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

S.N O. Topics For Practice: Content

The document discusses various basic UNIX commands like date, cal, echo, ls, who, uptime, uname, hostname, bc, man, cat, grep, rm, touch, cp, mv, cut, head, tail, chmod, and wc. It provides the syntax and examples of using these commands to check date and time, display calendar, print messages, list files, view user information, check system uptime, view system information, set hostname, use calculator, view manual pages, create, view, concatenate files, search files, delete files, create blank files, copy and move files between locations, cut/view parts of files, view starting/ending lines of files, modify file permissions, and count

Uploaded by

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

To study of Basic UNIX Commands and various UNIX editors such as vi, ed, ex and EMACS.

S.N Topics for Practice


o.1 Revision practice of various commands like man, cp, mv, ln, rm, unlink, mkdir, rmdir.
2 Implement two way process communication using pipes
3 Implement message queue form of IPC
4 Implement shared memory and semaphore form of IPC
5 Simulate the CPU scheduling algorithms - Round Robin, SJF, FCFS, priority
6 Simulate Bankers algorithm for Deadlock Avoidance and Prevention
7 Simulate all FIFO Page Replacement Algorithm using C program
8 Simulate all LRU Page Replacement Algorithms using C program
9 Simulate Paging Technique of Memory Management
1 Practice various commands/utilities such as catnl, uniq, tee, pg, comm, cmp, diff, tr, tar, cpio, mount,
0 umount, find, umask, ulimit, sort, grep, egrep,fgrep cut, paste, join, du, df , ps, who, etc and many more.
CONTENT:
Note: Syn->Syntax

a) date
–used to check the date and time Syn:
$date
Forma Purpose Example Result
+%m To display only month $date+%m 06
+%h To display month name $date+%h June
+%d To display day of month $date+%d O1
+%y To display last two digits of $date+%y 09
+%H years
To display hours $date+%H 10
+%M To display minutes $date+%M 45
+%S To display seconds $date+%S 55

b) cal
–used to display the calendar Syn:$cal 2
2009

c)echo
–used to print the message on the screen.
Syn:$echo “text”

d)ls
–used to list the files. Your files are kept in a directory.
Syn:$lsls–s
All files (include files with prefix) ls–l
Lodetai (provide file statistics) ls–t Order
by creation time
ls– u Sort by access time (or show when last accessed together with –l) ls–s Order by
size
ls–r Reverse order
ls–f Mark directories with /,executable with* , symbolic links with @, local sockets with =, named
pipes(FIFOs)with
ls–s Show file size
ls– h“ Human Readable”, show file size in Kilo Bytes & Mega Bytes (h can be used together with –l or)
ls[a-m]*List all the files whose name begin with alphabets From „a‟ to „m‟
ls[a]*List all the files whose name begins with „a‟ or „A‟
Eg:$ls>my list Output of „ls‟ command is stored to disk file named „my list‟

e)lp
–used to take printouts Syn:$lp
filename
f)man
–used to provide manual help on every UNIX commands.
Syn:$man unix command
$man cat

g)who & whoami


–it displays data about all users who have logged into the system currently. The next command displays about current
user only.
Syn:$who$whoami

h)uptime
–tells you how long the computer has been running since its last reboot or power-off.
Syn:$uptime

i)uname
–it displays the system information such as hardware platform, system name and processor, OS type.
Syn:$uname–a

j)hostname
–displays and set system host name Syn:$
hostname

k)bc
–stands for „best calculator‟

$bc $ bc $ bc $ bc
10/2*3 scale =1 ibase=2 sqrt(19
15 2.25+1 obase=16 6) quit
14
3.35 11010011
quit 89275
1010
Ā
Quit
$bc $ bc-l
for(i=1;i<3;i=i+1) scale=2
1I s(3.14)
2 0
3 quit
FILE MANIPULATION COMMANDS
a)cat–this create, view and concatenate files.
Creation: Syn:
$cat>filename

Viewing: Syn:
$cat filename
Add text to an existing file:
Syn:$cat>>filename

Concatenate: Syn:
$catfile1file2>file3
$catfile1file2>>file3 (no over writing of file3)

b)grep–used to search a particular word or pattern related to that word from the file. Syn:$grep search
word filename
Eg:$grep anu student

c)rm–deletes a file from the file system Syn:$rm


filename

d)touch–used to create a blank file.


Syn:$touch file names

e)cp–copies the files or directories Syn:


$cpsource file destination file Eg:$cp
student stud

f)mv–to rename the file or directory syn:$mv old


file new file
Eg:$mv–i student student list(-i prompt when overwrite)

g)cut–it cuts or pickup a given number of character or fields of the file. Syn:$cut<option><filename>
Eg: $cut –c filename
$cut–c1-10emp
$cut–f 3,6emp
$ cut –f 3-6 emp
-c cutting columns
-f cutting fields

h)head–displays10 lines from the head(top)of a given file Syn:$head


filename
Eg:$head student
To display the top two lines:

4|Page
Syn:$head-2student

i) tail–displays last 10 lines of the file Syn:$tail


filename
Eg:$tail student
To display the bottom two lines;
Syn:$ tail -2 student

j)chmod–used to change the permissions of a file or directory. Syn:$ch mod


category operation permission file Where,
Category–is the user type
Operation–is used to assign or remove permission Permission–is the
type of permission
File–are used to assign or remove permission all

Examples:
$chmodu-wx student
Removes write and execute permission for users
$ch modu+rw,g+rwstudent
Assigns read and write permission for users and groups
$chmodg=rwx student
Assigns absolute permission for groups of all read, write and execute permissions

k)wc–it counts the number of lines, words, character in a specified file(s) with the options as –l,-
w,-c

Category Operation Permission


u– +assign r– read
users -remove w–
g– =assign absolutely write
group x-
o–$wc –l filename
Syn: execute
$wc –w filename
$wc–c filename

1) mv = renames a file or moves it from one directory to another directory

Syntax

mv [-f] [-i] oldname newname  (to rename)

mv [-f] [-i] filename newdirectory

-f mv will move the file(s) without prompting even if it is writing over an existing target. Note that this is the
default if the standard input is not a terminal.
-i Prompts before overwriting another file.
oldname The oldname of the file renaming.
newname The newname of the file renaming.
filename The name of the file you want to move directory – The directory of were you want the file to go.

Examples

mv myfile.txt newdirectory/ – moves the file myfile.txt to the directory newdirectory.

mv myfile.txt ../ – moves the file myfile.txt back one directory (if available).


.

2) cp = copies files from one location to another

Examples

cp file1.txt newdir

Copies the file1.txt in the current directory to the newdir directory.

cp /home/public_html/mylog.txt /home/public_html/backup/mylog.bak

Copies the mylog.txt file in the public_html directory into the public_html/backup directory as mylog.bak. The files are

identical however have different names.

cp *.txt newdir

Copy all files ending in .txt into the newdir directory.

cp -r /home/hope/files/* /home/hope/backup

Copies all the files, directories, and subdirectories in the files directory into the backup directory.

3) rm : deletes a file without confirmation (by default).

rm myfile.txt

Remove the file myfile.txt without prompting the user.

rm -r directory

Remove a directory, even if files existed in that directory. It will prompt for every single file

rm -rf directory

Remove a directory, even if files existed in that directory.It will not ask for confirmation for each file.

To remove a file whose name starts with a `-‘, for example `-foo’, use one of these commands:

rm — -foo
rm ./-foo

4) mkdir = to create a new directory

mkdir filename

.
5) rmdir = deletes a directory

rmdir mydir – removes the directory mydir (it wont work if files existed in the directory)

rm -r directory – would remove a directory, even if files existed in that directory.

there is no -r option for rmdir, therefore to remove a directory with files inside can use rm -r or rm-rf

rmdir -p dir3/dir4/dir5 - remove dir5, dir4 and dir3 if dir5 were empty, dir4 only contained dir5 and dir3 only

contained dir4 (which, in turn, contained dir5):


EXPERIMENT 1

1.1 OBJECTIVE
Write a C program to simulate the following non-preemptive CPU scheduling algorithms to find turnaround time
and waiting time for the above problem.
a) FCFS b) SJF c) Round Robin d) Priority

1.2 DESCRIPTION
Assume all the processes arrive at the same time.

1.2.1 FCFS CPU SCHEDULING ALGORITHM


For FCFS scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. The
scheduling is performed on the basis of arrival time of the processes irrespective of their other parameters. Each
process will be executed according to its arrival time. Calculate the waiting time and turnaround time of each of
the processes accordingly.
FCFS एल्गोरिथम का उपयोग करके औसत प्रतीक्षा समय की रोह् गणना करने के लिए पहले पहली प्रक्रिया का प्रतीक्षा समय शून्य रखा जाता
है और दूसरी प्रक्रिया का प्रतीक्षा समय पहली प्रक्रिया का फटने का समय होता है और तीसरी प्रक्रिया के प्रतीक्षा समय का योग होता है पहली
और दूसरी प्रक्रिया के फटने का समय और इसी तरह। सभी प्रतीक्षा समयों की गणना के बाद औसत प्रतीक्षा समय की गणना सभी प्रतीक्षा
समयों के औसत के रूप में की जाती है। FCFS मुख्य रूप से कहता है कि पहले आओ पहले पाओ एल्गोरिथम जो पहले आया उसे पहले
परोसा जाएगा।

Waiting time (n) = waiting time (n-1) + Burst time (n-1)


Turnaround time (n)= waiting time(n)+Bursttime(n)
Average waiting time = Total waiting Time / Number of process
Average Turnaround time = Total Turnaround Time / Number of process

1.2.2 SJF CPU SCHEDULING ALGORITHM


For SJF scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. Arrange
all the jobs in order with respect to their burst times. There may be two jobs in queue with the same execution
time, and then FCFS approach is to be performed. Each process will be executed according to the length of its
burst time. Then calculate the waiting time and turnaround time of each of the processes accordingly.

1.2.3 ROUND ROBIN CPU SCHEDULING ALGORITHM


For round robin scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times,
and the size of the time slice. Time slices are assigned to each process in equal portions and in circular order,
handling all processes execution. This allows every process to get an equal chance. Calculate the waiting time
and turnaround time of each of the processes accordingly.

1.2.4 PRIORITY CPU SCHEDULING ALGORITHM


For priority scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times, and
the priorities. Arrange all the jobs in order with respect to their priorities. There may be two jobs in queue with
the same priority, and then FCFS approach is to be performed. Each process will be executed according to its
priority. Calculate the waiting time and turnaround time of each of the processes accordingly.
1.3 PROGRAM

1.3.1 FCFS CPU SCHEDULING ALGORITHM


#include<stdio.h>
#include<conio.h>
main()
{
int bt[20], wt[20], tat[20], i, n;
float wtavg, tatavg;
clrscr();
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
EXPERIMENT 6

6.1 OBJECTIVE
Write a C program to simulate paging technique of memory management.

6.2 DESCRIPTION
In computer operating systems, paging is one of the memory management schemes by which a computer stores
and retrieves data from the secondary storage for use in main memory. In the paging memory-management
scheme, the operating system retrieves data from secondary storage in same-size blocks called pages. Paging is a
memory-management scheme that permits the physical address space a process to be noncontiguous. The basic
method for implementing paging involves breaking physical memory into fixed-sized blocks called frames and
breaking logical memory into blocks of the same size called pages. When a process is to be executed, its pages
are loaded into any available memory frames from their source.

6.3 PROGRAM
#include<stdio.h>
#include<conio.h>

main()
{
int ms, ps, nop, np, rempages, i, j, x, y, pa, offset;
int s[10], fno[10][20];

clrscr();

printf("\nEnter the memory size -- ");


scanf("%d",&ms);

printf("\nEnter the page size -- ");


scanf("%d",&ps);

nop = ms/ps;
printf("\nThe no. of pages available in memory are -- %d ",nop);

printf("\nEnter number of processes -- ");


scanf("%d",&np);

rempages = nop; for(i=1;i<=np;i+

+)
{

printf("\nEnter no. of pages required for p[%d]-- ",i);


scanf("%d",&s[i]);

if(s[i] >rempages)
{
printf("\nMemory is Full");
break;
}
rempages = rempages - s[i];
printf("\nEnter pagetable for p[%d] --- ",i);
for(j=0;j<s[i];j++)
scanf("%d",&fno[i][j]);
}

printf("\nEnter Logical Address to find Physical Address ");


printf("\nEnter process no. and pagenumber and offset -- ");

scanf("%d %d %d",&x,&y, &offset);


20
if(x>np || y>=s[i] || offset>=ps)
printf("\nInvalid Process or Page Number or offset");
else
{
pa=fno[x][y]*ps+offset;
printf("\nThe Physical Address is -- %d",pa);
}
getch();
}
INPUT
Enter the memory size – 1000 Enter the page
size -- 100
The no. of pages available in memory are -- 10 Enter number of
processes -- 3
Enter no. of pages required for p[1]-- 4
Enter pagetable for p[1] --- 8 6 9 5

Enter no. of pages required for p[2]-- 5


Enter pagetable for p[2] --- 1 4 5 7 3

Enter no. of pages required for p[3]-- 5

OUTPUT
Memory is Full

Enter Logical Address to find Physical Address


Enter process no. and pagenumber and offset 3 6
The Physical Address is -- 760 0

EXPERIMENT 8

8.1 OBJECTIVE
Write a C program to simulate Bankers algorithm for the purpose of deadlock avoidance.

8.2 DESCRIPTION

ऑपरेटिंग सिस्टम में बैंकर अल्गोरिथम एक रिसोर्स एलोके शन और डेडलॉक avoidance अल्गोरिथम है जो सुरक्षा के लिए जांच करता है। ऐसा ये सारे
रिसोर्सेज के पहले से तय किये हुए अधिकतम संभव मात्रा के एलोके शन को सिमुलेट कर के करता है।

इसके बाद यह “s-state” बनाकर ये चेक करता है किनते संभव एक्टिविटीज हो सकते हैं और ये निर्णय लेता है कि एलोके शन को जारी रखना चाहिए या
नहीं।

बैंकर अल्गोरिथम को implement करने के लिए निम्नलिखित अल्गोरिथम लगाए जाते हैं:

मान लीजिये कि ‘n’ सिस्टम में प्रोसेस की संख्या है और ‘m’ रिसोर्स के प्रकार की संख्या है।

अवेलेबल: 

 आकार का एक 1-d ऐरे है जो हर टाइप के रिसोर्सेज की संख्या बताता है।


 Available[ j ] =k का अर्थ हुआ कि यहाँ पर रिसोर्स टाइप Rj के  ‘k’ इंस्टैंस हैं।

मैक्स:

 ये एक 2-d ऐरे है जिसका आकार ‘n*m’ है और ये सिस्टम के हर एक प्रोसेस के अधिकतम मांग को दिखाता है।
 Max[ i, j ] = k का अर्थ हुआ कि प्रोसेस Pi Rj रिसोर्स टाइप के  ‘k’ इंस्टैंस का निवेदन कर सकता है।

एलोके शन:

 It is a 2-d array of size  that defines the number of resources of each type currently
allocated to each process. ये ‘n*m’ आकार का एक 2-d ऐरे है जो हर प्रोसेस को अभी allocate हुए हर एक टाइप
के रिसोर्सेज की संख्या बताता है।
 Allocation[ i, j ] = k का अर्थ हुआ कि प्रोसेस Pi रिसोर्स टाइप  Rj के अभी ‘k’ इंस्टैंस को allocate किया गया है।

नीड:

ये ‘n*m’ आकार का एक 2-d ऐरे है जो प्रत्येक प्रोसेस के बचे हुए रिसोर्सेज की जरूरत को बताता है।

 Need [ i,  j ] = k का अर्थ हुआ कि प्रोसेस  Pi अभी allocate किया हुआ है रिसोर्स टाइप Rj के  ‘k’इंस्टैंस को।
 Need [ i,  j ] = Max [ i,  j ] – Allocation [ i,  j ]

specifies the resources currently allocated to process  specifies the additional resources
that process  may still request to complete its task.

Allocationi ये बताता है कि अभी प्रोसेस Pi और Needi को कौन सा प्रोसेस allocate किया गया है और साथ ही वो अतिरिक्त रिसोर्स जो
प्रोसेस Pi निवेदन कर सकता है ताकि टास्क पूरा हो जाये।

बैंकर अल्गोरिथम दो अल्गोरिथम से मिल कर बना होता है- सेफ्टी अल्गोरिथम और रिसोर्स रिक्वे स्ट अल्गोरिथम।

सेफ्टी अल्गोरिथम (safety algorithm in hindi)

ये एक ऐसा अल्गोरिथम है जो यहपता करता है कि कोई सिस्टम सुरक्षित स्टेट में है भी या नहीं। इसे ऐसे दिखाया जा सकता है:

1) सबसे पहले लेंथ ‘m’ और ‘n’ के वेक्टर को अपना कार्य पूरा करने दीजिये

Initialize: Work = Available


Finish[i] = false; for i=1, 2, 3, 4….n

2) i को खोजिये जिसमे,
a) Finish[i] = false
b) Needi <= Work if no such i exists goto step (4)

3) Work = Work + Allocation


Finish[i] = true
goto step (2)

4) if finish [i] = true for all i


अगर ये है तब सिस्टम सुरक्षित स्टेट में है।

रिसोर्स रिक्वे स्ट अल्गोरिथम (resource request algorithm in hindi)

मान लीजिये कि Requesti एक रिक्वे स्ट ऐरे है जो कि प्रोसेस Pi का है। Requesti [j] = k का अर्थ हुआ कि प्रोसेस Pi रिसोर्स टाइप Rj का k इंस्टैंस
चाहता है। जब प्रोसेस Pi द्वारा कोई निवेदन किया जाता है तब निम्नलिखित एक्शन लिए जाते हैं:

1) If Requesti <= Needi
Goto step (2) ; नहीं तो एक एरर कं डीशन उठाया जाएगा क्योंकि प्रोसेस अपने अधिकतम क्ले म को पार कर चुका है।

2) If Requesti <= Available Goto step (3); नहीं तो Pi को इन्तजार करना पड़ेगा क्योंकि रिसोर्स अभी उपलब्ध नहीं है।

3) सिस्टम Pi को उस्का निवेदन स्वीकार कर रिसोर्सेज allocate करना दिखाने के लिए ये करेगा:
Available = Available – Requesti
Allocationi = Allocationi + Requesti
Needi = Needi– Requesti

इस तरह आपने समझा कि कै से बैंकर्स अल्गोरिथम द्वारा हम इस प्रक्रिया को पूरा करते हैं। आप इसे अपने सिस्टम में भी प्रैक्टिस कर के देख सकते हैं।

In a multiprogramming environment, several processes may compete for a finite number of resources. A process
requests resources; if the resources are not available at that time, the process enters a waiting state.
Sometimes, a waiting process is never again able to change state, because the resources it has requested are
held by other waiting processes. This situation is called a deadlock. Deadlock avoidance is one of the techniques
for handling deadlocks. This approach requires that the operating system be given in advance additional
information concerning which resources a process will request and use during its lifetime. With this additional
knowledge, it can decide for each request whether or not the process should wait. To decide whether the
current request can be satisfied or must be delayed, the system must consider the resources currently available,
the resources currently allocated to each process, and the future requests and releases of each process.
Banker’s algorithm is a deadlock avoidance algorithm that is applicable to a system with multiple instances of
each resource type.

8.3 PROGRAM
#include<stdio.h>
struct file
{
int all[10];
int max[10];
int need[10];
int flag;
};
void main()
{
struct file f[10];
int fl;
int i, j, k, p, b, n, r, g, cnt=0, id, newr;
int avail[10],seq[10];
clrscr();
printf("Enter number of processes -- ");
scanf("%d",&n);
printf("Enter number of resources -- ");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("Enter details for P%d",i);
printf("\nEnter allocation\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].all[j]);
printf("Enter Max\t\t -- \t");
for(j=0;j<r;j++)
scanf("%d",&f[i].max[j]);
f[i].flag=0;
}
printf("\nEnter Available Resources\t -- \t");
for(i=0;i<r;i++)
scanf("%d",&avail[i]);

printf("\nEnter New Request Details -- ");


printf("\nEnter pid \t -- \t");
scanf("%d",&id);
printf("Enter Request for Resources \t -- \t");
for(i=0;i<r;i++)
{
scanf("%d",&newr);
f[id].all[i] += newr;
29
avail[i]=avail[i] - newr;
}

for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
f[i].need[j]=f[i].max[j]-f[i].all[j];
if(f[i].need[j]<0)
f[i].need[j]=0;
}
}
cnt=0;
fl=0;
while(cnt!=n)
{
g=0;
for(j=0;j<n;j++)
{
if(f[j].flag==0)
{
b=0;
for(p=0;p<r;p++)
{
if(avail[p]>=f[j].need[p])
b=b+1;
else
b=b-1;
}
if(b==r)
{
printf("\nP%d is visited",j); seq[fl+
+]=j;
f[j].flag=1; for(k=0;k<r;k+
+)
avail[k]=avail[k]+f[j].all[k];
cnt=cnt+1;
printf("("); for(k=0;k<r;k+
+)
printf("%3d",avail[k]);
printf(")");
g=1;
}
}
}
if(g==0)
{
printf("\n REQUEST NOT GRANTED -- DEADLOCK OCCURRED");
printf("\n SYSTEM IS IN UNSAFE STATE");
goto y;
}
}
printf("\nSYSTEM IS IN SAFE STATE");
printf("\nThe Safe Sequence is -- (");
for(i=0;i<fl;i++)
printf("P%d ",seq[i]);
printf(")");
y: printf("\nProcess\t\tAllocation\t\tMax\t\t\tNeed\n"); for(i=0;i<n;i+
+)
{
printf("P%d\t",i);
for(j=0;j<r;j++)
30
printf("%6d",f[i].all[j]); for(j=0;j<r;j+
+)
printf("%6d",f[i].max[j]);
for(j=0;j<r;j++)
printf("%6d",f[i].need[j]);
printf("\n");
}
getch();
}
INPUT
Enter number of – 5
processes
Enter number of -- 3
resources
Enter details for P0
allocation -- 0 1 0
Enter Max -- 7 5 3

Enter details for P1


Enter allocation -- 2 0 0
Enter Max -- 3 2 2

Enter details for P2


Enter allocation -- 3 0 2
Enter Max -- 9 0 2

Enter details for P3


Enter allocation -- 2 1 1
Enter Max -- 2 2 2

Enter details for P4


Enter allocation -- 0 0 2
Enter Max -- 4 3 3

Enter Available Resources -- 3 3 2


Enter New Request Details -- Enter pid
-- 1
Enter Request for Resources -- 1 0 2

OUTPUT
P1 is visited( 5 3 2)
P3 is visited( 7 4 3)
P4 is visited( 7 4 5)
P0 is visited( 7 5 5)
P2 is visited( 10 5 7) SYSTEM IS IN SAFE STATE
The Safe Sequence is -- (P1 P3 P4 P0 P2 )

Process Allocation Max Need


P0 0 1 0 7 5 3 7 4 3
P1 3 0 2 3 2 2 0 2 0
P2 3 0 2 9 0 2 6 0 0
P3 2 1 1 2 2 2 0 1 1
P4 0 0 2 4 3 3 4 3 1
EXPERIMENT 10

10.1 OBJECTIVE
Write a C program to simulate page replacement algorithms
a) FIFO b) LRU c) LFU

10.2 DESCRIPTION
Page replacement is basic to demand paging. It completes the separation between logical memory and physical
memory. With this mechanism, an enormous virtual memory can be provided for programmers on a smaller
physical memory. There are many different page-replacement algorithms. Every operating system probably has
its own replacement scheme. A FIFO replacement algorithm associates with each page the time when that page
was brought into memory. When a page must be replaced, the oldest page is chosen. If the recent past is used
as an approximation of the near future, then the page that has not been used for the longest period of time can
be replaced. This approach is the Least Recently Used (LRU) algorithm. LRU replacement associates with each
page the time of that page's last use. When a page must be replaced, LRU chooses the page that has not been
used for the longest period of time. Least frequently used (LFU) page-replacement algorithm requires that the
page with the smallest count be replaced. The reason for this selection is that an actively used page should have
a large reference count.

10.3 PROGRAM

10.3.1 FIFO PAGE REPLACEMENT ALGORITHM


#include<stdio.h>
#include<conio.h>
main()
{
int i, j, k, f, pf=0, count=0, rs[25], m[10], n;
clrscr();
printf("\n Enter the length of reference string -- ");
scanf("%d",&n);
printf("\n Enter the reference string -- ");
for(i=0;i<n;i++)
scanf("%d",&rs[i]);
printf("\n Enter no. of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
m[i]=-1;

printf("\n The Page Replacement Process is -- \n");


for(i=0;i<n;i++)
{
for(k=0;k<f;k++)
{
if(m[k]==rs[i])
break;
}
if(k==f)
{
m[count++]=rs[i];
pf++;
}
for(j=0;j<f;j++)
printf("\t%d",m[j]);
if(k==f)
printf("\tPF No. %d",pf);
printf("\n");
if(count==f)
count=0;
}
printf("\n The number of Page Faults using FIFO are %d",pf);
getch();
36
}

INPUT
Enter the length of reference string – 20
Enter the reference string --7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter no. of frames -- 3

OUTPUT
The Page Replacement Process is –
7 - -1 PF No.
7 01 -1 1 No.
PF
7 0 1 2 No.
PF
2 0 1 3 No.
PF
2 0 1 4
2 3 1 PF No.
2 3 0 5
PF No.
4 3 0 6
PF No.
4 2 0 7
PF No.
4 2 3 8
PF No.
0 2 3 9 No.
PF
0 2 3 10
0 2 3
0 1 3 PF No.
0 1 2 11 No.
PF
0 1 2 12
0 1 2
7 1 2 PF No.
7 0 2 13 No.
PF
7 0 1 14 No.
PF
15
The number of Page Faults using FIFO are 15

10.3.2 LRU PAGE REPLACEMENT ALGORITHM


#include<stdio.h>
#include<conio.h>
main()
{
int i, j , k, min, rs[25], m[10], count[10], flag[25], n, f, pf=0, next=1;
clrscr();
printf("Enter the length of reference string -- ");
scanf("%d",&n);
printf("Enter the reference string -- ");
for(i=0;i<n;i++)
{
scanf("%d",&rs[i]);
flag[i]=0;
}
printf("Enter the number of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
{
count[i]=0;
m[i]=-1;
}
printf("\nThe Page Replacement process is -- \n");
for(i=0;i<n;i++)
{
for(j=0;j<f;j++)
{
if(m[j]==rs[i])
{
flag[i]=1;
37
count[j]=next;
next++;
}

}
if(flag[i]==0)
{
if(i<f)
{
m[i]=rs[i];
count[i]=next; next++;

}
else
{ min=0;
for(j=1;j<f;j++)
if(count[min] > count[j]) min=j;

m[min]=rs[i];
count[min]=next; next+
+;

}
pf++;
}
for(j=0;j<f;j++)
printf("%d\t", m[j]);
if(flag[i]==0)
printf("PF No. -- %d" , pf); printf("\n");
}
printf("\nThe number of page faults using LRU are %d",pf);
getch();
}

INPUT
Enter the length of reference string -- 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 Enter
the number of frames -- 3

OUTPUT
The Page Replacement process is --
7 - - PF No. --
7 01 -1 1 No. --
PF
7 0 1 2 No. --
PF
2 0 1 3 No. --
PF
2 0 1 4
2 0 3 PF No. --
2 0 3 5
4 0 3 PF No. --
4 0 2 6
PF No. --
4 3 2 7
PF No. --
0 3 2 8 No. --
PF
0 3 2 9
0 3 2
1 3 2 PF No. --
1 3 2 10
1 0 2 PF No. --
1 0 2 11
1 0 7 PF No. --
12
1 0 7
38
1 0 7
The number of page faults using LRU are 12

10.3.3 LFU PAGE REPLACEMENT ALGORITHM


#include<stdio.h>
#include<conio.h>

main()
{
int rs[50], i, j, k, m, f, cntr[20], a[20], min, pf=0;
clrscr();
printf("\nEnter number of page references -- ");
scanf("%d",&m);

printf("\nEnter the reference string -- "); for(i=0;i<m;i+


+)
scanf("%d",&rs[i]);

printf("\nEnter the available no. of frames -- ");


scanf("%d",&f);

for(i=0;i<f;i++)
{
cntr[i]=0;
a[i]=-1;
}
Printf(“\nThe Page Replacement Process is – \n“);
for(i=0;i<m;i++)
{

for(j=0;j<f;j++)
if(rs[i]==a[j])
{
cntr[j]++;
break;
}
if(j==f)
{
min =
0;
for(k=1;k<f;k++)
if(cntr[k]<cntr[min])
min=k;
a[min]=rs[i];
cntr[min]=1;
pf++;
}
printf("\n");
for(j=0;j<f;j++)
printf("\t%d",a[j]);
if(j==f)
printf(“\tPF No. %d”,pf);
}
printf("\n\n Total number of page faults -- %d",pf);
getch();
}

INPUT
Enter number of page references -- 10
Enter the reference string -- 1234525251
Enter the available no. of frames -- 3 43
39
OUTPUT
The Page Replacement Process is –

1 -1 -1 PF
1 2 -1 No. 1
PF
1 2 3 No. 2
PF
4 2 3 No. 3
PF
5 2 3 No. 4
PF
5 2 3 No. 5
5 2 3
5 2 1 PF
5 2 4 No. 6
PF
5 2 3 No. 7
PF
No. 8
Total number of page faults -- 8
40
EXPERIMENT 11

11.1 OBJECTIVE
*Write a C program to simulate page replacement algorithms
a) Optimal

11.2 DESCRIPTION
Optimal page replacement algorithm has the lowest page-fault rate of all algorithms and will never suffer from
Belady's anomaly. The basic idea is to replace the page that will not be used for the longest period of time. Use
of this page-replacement algorithm guarantees the lowest possible page fault rate for a fixed number of frames.
Unfortunately, the optimal page-replacement algorithm is difficult to implement, because it requires future
knowledge of the reference string.

11.3 PROGRAM
#include<stdio.h>
int n;
main()
{
int seq[30],fr[5],pos[5],find,flag,max,i,j,m,k,t,s;
int count=1,pf=0,p=0;
float pfr;
clrscr();
printf("Enter maximum limit of the sequence: ");
scanf("%d",&max);
printf("\nEnter the sequence: ");
for(i=0;i<max;i++)
scanf("%d",&seq[i]);
printf("\nEnter no. of frames: ");
scanf("%d",&n);
fr[0]=seq[0]; pf+
+;
printf("%d\t",fr[0]);
i=1;
while(count<n)
{
flag=1; p+
+;
for(j=0;j<i;j++)
{
if(seq[i]==seq[j])
flag=0;
}
if(flag!=0)
{
fr[count]=seq[i];
printf("%d\t",fr[count]);
count++;
pf++;
} i+
+;
}
printf("\n");
for(i=p;i<max;i++)
{
flag=1;
for(j=0;j<n;j++)
{
if(seq[i]==fr[j])
flag=0;
}
if(flag!=0)
41
{
for(j=0;j<n;j++)
{
m=fr[j]; for(k=i;k<max;k+
+)
{
if(seq[k]==m)
{
pos[j]=k;
break;
}
else
pos[j]=1;
}
}
for(k=0;k<n;k++)
{
if(pos[k]==1)
flag=0;
}
if(flag!=0)
s=findmax(pos);
if(flag==0)
{
for(k=0;k<n;k++)
{
if(pos[k]==1)
{
s=k;
break;
}
}
}
fr[s]=seq[i];
for(k=0;k<n;k++)
printf("%d\t",fr[k]);
pf++;
printf("\n");
}
}
pfr=(float)pf/(float)max;
printf("\nThe no. of page faults are %d",pf);
printf("\nPage fault rate %f",pfr);
getch();
}
int findmax(int a[])
{
int max,i,k=0;
max=a[0];
for(i=0;i<n;i++)
{
if(max<a[i])
{
max=a[i];
k=i;
}
}
return k;
}
INPUT
Enter number of page references -- 10
Enter the reference string -- 1234525251
43
Enter the available no. of frames -- 3

OUTPUT
The Page Replacement Process is –

1 -1 -1 PF
1 -1 No. 1
PF
1 3 No. 2
PF Total number of page faults -- 8
4 3 No. 3
PF
5 3 No.
PF 4
5 3 No. 5
5 3
5 1 PF
5 4 No. 6
PF
5 3 No. 7
PF
No. 8
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
getch();
}

INPUT
Enter the number of processes 3
--
Enter Burst Time for Process 0 2
--
Enter Burst Time for Process 1 4
3
--
Enter Burst Time for Process 2 3
--
OUTPUT
PROCESS BURST TIME WAITING TIME TURNAROUND
P0 24 0 TIME 24
P1 3 24 27
P2 3 27 30

Average Waiting Time-- 17.000000


Average Turnaround Time -- 27.000000

1.3.2 SJF CPU SCHEDULING ALGORITHM


#include<stdio.h>
#include<conio.h>
main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp;
float wtavg, tatavg;
clrscr();
printf("\nEnter the number of processes -- ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i);
scanf("%d", &bt[i]);

}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;

temp=p[i];
p[i]=p[k];
p[k]=temp;
}
wt[0] = wtavg = 0;
tat[0] = tatavg = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i];
wtavg = wtavg + wt[i];
tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]);
printf("\nAverage Waiting Time -- %f", wtavg/n);
printf("\nAverage Turnaround Time -- %f", tatavg/n);
getch();
}

INPUT
Enter the number of processes 4
--
Enter Burst Time for Process 0 6
--
Enter Burst Time for Process 1 8
--
Enter Burst Time for Process 2 7
--
Enter Burst Time for Process 3 3
--
OUTPUT
PROCESS BURST TIME WAITING TURNAROUND
P3 3 TIME 0 TIME
P0 6 3
P2 7 9 16
P1 8 16 24
Average Waiting Time -- 7.000000
Average Turnaround Time -- 13.000000

1.3.3 ROUND ROBIN CPU SCHEDULING ALGORITHM


#include<stdio.h>
main()
{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max;
float awt=0,att=0,temp=0;
clrscr();
printf("Enter the no of processes -- ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1);
scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- ");
scanf("%d",&t);
max=bu[0];
for(i=1;i<n;i++)
if(max<bu[i])
max=bu[i]; for(j=0;j<(max/t)+1;j+
+)
for(i=0;i<n;i++)
if(bu[i]!=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i];
temp=temp+bu[i];
bu[i]=0;
}
else
{
bu[i]=bu[i]-t;
temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i];
att+=tat[i];
awt+=wa[i];
}
printf("\nThe Average Turnaround time is -- %f",att/n);
printf("\nThe Average Waiting time is -- %f ",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
getch();
}
INPU
T
Enter the no of processes – 3
Enter Burst Time for process 1 – 24
Enter Burst Time for process 2 -- 3
Enter Burst Time for process 3 -- 3

Enter the size of time slice – 3

OUTPUT
The Average Turnaround time is – 15.666667
The Average Waiting time is -- 5.666667

PROCESS BURST TIME WAITING TIME TURNAROUND


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

1.3.4 PRIORITY CPU SCHEDULING ALGORITHM


#include<stdio.h>
main()
{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp;
float wtavg, tatavg;
clrscr();
printf("Enter the number of processes --- ");
scanf("%d",&n);

for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i);
scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++)
for(k=i+1;k<n;k++)
if(pri[i] > pri[k])
{
temp=p[i];
p[i]=p[k];
p[k]=temp;

temp=bt[i];
bt[i]=bt[k];
bt[k]=temp;

temp=pri[i];
pri[i]=pri[k];
pri[k]=temp;

}
wtavg = wt[0] = 0;
tatavg = tat[0] = bt[0];
for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];

wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];


}

printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUND TIME");


for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]);

printf("\nAverage Waiting Time is --- %f",wtavg/n); printf("\nAverage Turnaround Time is


--- %f",tatavg/n); getch();
}

INPUT
Enter the number of processes -- 5
Enter the Burst Time & Priority of Process 0 --- 3
10
Enter the Burst Time & Priority of Process 1 --- 1 1
Enter the Burst Time & Priority of Process 2 --- 2 4
Enter the Burst Time & Priority of Process 3 --- 1 5
Enter the Burst Time & Priority of Process 4 --- 5 2

OUTPUT
PROCESS PRIORITY BURST TIME WAITING TURNAROUND
1 1 1 TIME TIME
4 2 5
0 3 10 16
2 4 2 18
3 5 1 19
Average Waiting Time is --- 8.200000 Average Turnaround Time is ---
12.000000

EXPERIMENT.NO 9
DEAD LOCK AVOIDANCE

AIM: To Simulate bankers algorithm for Dead Lock Avoidance (Banker‘s Algorithm)

DESCRIPTION:
Deadlock is a situation where in two or more competing actions are waiting f or the other to finish, and
thus neither ever does. When a new process enters a system, it must declare the maximum number of
instances of each resource type it needed. This number may exceed the total number of resources in the
system. When the user request a set of resources, the system must determine whether the allocation of each
resources will leave the system in safe state. If it will the resources are allocation; otherwise the process must
wait until some other process release the resources.
Data structures
n-Number of process, m-number of resource types.
Available: Available[j]=k, k – instance of resource type Rj is available. Max: If max[i, j]=k, Pi may
request at most k instances resource Rj.
Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj Need: If Need[I, j]=k, Pi may need
k more instances of resource type Rj, Need[I, j]=Max[I, j]- Allocation[I, j];
Safety Algorithm
1. Work and Finish be the vector of length m and n respectively, Work=Available and
Finish[i] =False.
2. Find an i such that both
Finish[i] =False
Need<=Work If no such I
exists go to step 4.
3. work= work + Allocation, Finish[i] =True;
4. if Finish[1]=True for all I, then the system is in safe state.
Resource request algorithm
Let Request i be request vector for the process Pi, If request i=[j]=k, then process Pi wants k instances
of resource type Rj.
1. if Request<=Need I go to step 2. Otherwise raise an error condition.
2. if Request<=Available go to step 3. Otherwise Pi must since the resources are
available.
3. Have the system pretend to have allocated the requested resources to process Pi by
modifying the state as follows;
Available=Available-Request I; Allocation
I=Allocation +Request I; Need i=Need i-
Request I;
If the resulting resource allocation state is safe, the transaction is completed and process Pi is allocated its
resources. However if the state is unsafe, the Pi must wait for Request i and the old resource-allocation state is
restored.
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.
9. or not if we allow the request.
10. stop the program.
11. end

SOURCE CODE :

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int alloc[10][10],max[10][10]; int
avail[10],work[10],total[10]; int
i,j,k,n,need[10][10];
int m;
int count=0,c=0;
char finish[10];
clrscr();
printf("Enter the no. of processes and resources:");
scanf("%d%d",&n,&m);
for(i=0;i<=n;i++)
finish[i]='n';
printf("Enter the claim matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<m;j++) scanf("%d",&max[i]
[j]);
printf("Enter the allocation matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<m;j++)
scanf("%d",&alloc[i][j]);
printf("Resource vector:");
for(i=0;i<m;i++)
scanf("%d",&total[i]);
for(i=0;i<m;i++)
avail[i]=0; for(i=0;i<n;i++)
for(j=0;j<m;j++) avail[j]+=alloc[i][j];
for(i=0;i<m;i++) work[i]=avail[i];
for(j=0;j<m;j++) work[j]=total[j]-
work[j]; for(i=0;i<n;i++)
for(j=0;j<m;j++) need[i][j]=max[i][j]-
alloc[i][j]; A:
for(i=0;i<n;i++)
{
c=0;
for(j=0;j<m;j++) if((need[i]
[j]<=work[j])&&(finish[i]=='n')) c++;
if(c==m)
{
printf("All the resources can be allocated to Process %d", i+1);
printf("\n\nAvailable resources are:");
for(k=0;k<m;k++)
{
work[k]+=alloc[i][k];
printf("%4d",work[k]);
}
printf("\n");
finish[i]='y';
printf("\nProcess %d executed?:%c \n",i+1,finish[i]); count++;
}
}
if(count!=n)
goto A;
else
printf("\n System is in safe mode"); printf("\n
The given state is safe state"); getch();
}
OUTPUT

Enter the no. of processes and resources: 4 3 Enter


the claim matrix:
322
613
314
422
Enter the allocation matrix:
100
612
211
002
Resource vector:9 3 6
All the resources can be allocated to Process 2
Available resources are: 6 2 3
Process 2 executed?:y
All the resources can be allocated to Process 3 Available resources are: 8 3 4
Process 3 executed?:y
All the resources can be allocated to Process 4 Available resources are: 8 3 6
Process 4 executed?:y
All the resources can be allocated to Process 1
Available resources are: 9 3 6
Process 1 executed?:y System is
in safe mode The given state is
safe state

VIVA QUESTIONS
1) What is meant by deadlock?
2) What is safe state in banker’s algorithms?
3) What is banker’s algorithm?
4) What are the necessary conditions where deadlock occurs?
5) What are the principles and goals of protection?
EXPERIMENT.NO 10 DEAD
LOCKPREVENTION

AIM: To implement deadlock prevention technique

Banker‘s Algorithm:

When a new process enters a system, it must declare the maximum number of instances of
each resource type it needed. This number may exceed the total number of resources in the system.
When the user request a set of resources, the system must determine whether the allocation of each
resources will leave the system in safe state. If it will the resources are allocation; otherwise the
process must wait until some other process release the resources.

DESCRIPTION:

Data structures

n-Number of process, m-number of resource types.

Available: Available[j]=k, k – instance of resource type Rj is available. Max: If max[i,


j]=k, Pi may request at most k instances resource Rj.
Allocation: If Allocation [i, j]=k, Pi allocated to k instances of resource Rj Need: If Need[I, j]=k, Pi
may need k more instances of resource type Rj,
Need[I, j]=Max[I, j]-Allocation[I, j];

Safety Algorithm

Work and Finish be the vector of length m and n respectively, Work=Available and Finish[i]
=False.
Find an i such that
both Finish[i] =False
Need<=Work

If no such I exists go to step 4.

5. work=work+Allocation, Finish[i] =True;

if Finish[1]=True for all I, then the system is in safe state


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. Stop the process.

SOURCE CODE :

#include<stdio.h>
#include<conio.h>
void main()
{
char job[10][10];
int time[10],avail,tem[10],temp[10]; int safe[10]; int
ind=1,i,j,q,n,t;
clrscr();
printf("Enter no of jobs: ");
scanf("%d",&n); for(i=0;i<n;i++)
{
printf("Enter name and time: ");
scanf("%s%d",&job[i],&time[i]);
}
printf("Enter the available resources:");
scanf("%d",&avail);
for(i=0;i<n;i++)
{
temp[i]=time[i];
tem[i]=i;
}
for(i=0;i<n;i++)
for(j=i+1;j<n;j++)
{
if(temp[i]>temp[j])
{
t=temp[i];
temp[i]=temp[j];
temp[j]=t; t=tem[i];
te
m[i
]=t
em
[j];
te
m[j
]=t
;
}
}
for(i=0;i<n;i++)
{
q=tem[i
];
if(time[
q]<=ava
il)
{
safe[ind]=tem[i];
avail=avail-tem[q];
printf("%s",job[saf
e[ind]]); ind++;
}
else
{
printf("No safe sequence\n");
}
}
printf("Safe
sequence is:");
for(i=1;i<ind; i++)
printf("%s
%d\n",job[safe[i]],time[safe[i]]);
getch();
}

OUTPUT:

Enter no of jobs:4
Enter name and
time: A 1 Enter
name and time:
B 4 Enter name
and time: C 2
Enter name and
time: D 3
Enter the available resources:
20 Safe sequence is: A 1, C 2,
D 3, B 4.

EXPERIMENT 1

1.1 PRE-LAB QUESTIONS


1. Define operating system?
2. What are the different types of operating systems?
3. Define a process?
4. What is CPU Scheduling?
5. Define arrival time, burst time, waiting time, turnaround time?

1.2 POST-LAB QUESTIONS


1. What is the advantage of round robin CPU scheduling algorithm?
2. Which CPU scheduling algorithm is for real-time operating system?
3. In general, which CPU scheduling algorithm works with highest waiting time?
4. Is it possible to use optimal CPU scheduling algorithm in practice?
5. What is the real difficulty with the SJF CPU scheduling algorithm?

1.3 ASSIGNMENT QUESTIONS


1. Write a C program to implement round robin CPU scheduling algorithm for the following given scenario. All
the processes in the system are divided into two categories – system processes and user processes. System
processes are to be given higher priority than user processes. Consider the time quantum size for the
system processes and user processes to be 5 msec and 2 msec respectively.
2. Write a C program to simulate pre-emptive SJF CPU scheduling algorithm.

EXPERIMENT 2

2.1 PRE-LAB QUESTIONS


1. What is multi-level queue CPU Scheduling?
2. Differentiate between the general CPU scheduling algorithms like FCFS, SJF etc and multi-level queue CPU
Scheduling?
3. What are CPU-bound I/O-bound processes?

2.2 POST-LAB QUESTIONS


1. What are the parameters to be considered for designing a multilevel feedback queue scheduler?
2. Differentiate multi-level queue and multi-level feedback queue CPU scheduling algorithms?
3. What are the advantages of multi-level queue and multi-level feedback queue CPU scheduling algorithms?

2.3 ASSIGNMENT QUESTIONS


1. Write a C program to simulate multi-level queue scheduling algorithm considering the following scenario.
All the processes in the system are divided into two categories – system processes and user processes.
System processes are to be given higher priority than user processes. Consider each process priority to be
from 1 to 3. Use priority scheduling for the processes in each queue.

EXPERIMENT 3

3.1 PRE-LAB QUESTIONS


1. Define file?
2. What are the different kinds of files?
3. What is the purpose of file allocation strategies?

3.2 POST-LAB QUESTIONS


1. Identify ideal scenarios where sequential, indexed and linked file allocation strategies are most appropriate?
2. What are the disadvantages of sequential file allocation strategy?
3. What is an index block?
4. What is the file allocation strategy used in UNIX?

49
3.3 ASSIGNMENT QUESTIONS
1. Write a C program to simulate a two-level index scheme for file allocation?

EXPERIMENT 4

4.1 PRE-LAB QUESTIONS


1. What is the purpose of memory management unit?
2. Differentiate between logical address and physical address?
3. What are the different types of address binding techniques?
4. What is the basic idea behind contiguous memory allocation?
5. How is dynamic memory allocation useful in multiprogramming operating systems?

4.2 POST-LAB QUESTIONS


1. Differentiate between equal sized and unequal sized MFT schemes?
2. What is the advantage of MVT memory management scheme over MFT?

4.3 ASSIGNMENT QUESTIONS


1. Write a C program to simulate MFT memory management scheme with unequal sized partitions.

EXPERIMENT 5

5.1 PRE-LAB QUESTIONS


1. Differentiate between the memory management schemes MFT and MVT?
2. What is dynamic memory allocation?
3. What is external fragmentation?

5.2 POST-LAB QUESTIONS


1. Which of the dynamic contiguous memory allocation strategies suffer with external fragmentation?
2. What are the possible solutions for the problem of external fragmentation?
3. What is 50-percent rule?
4. What is compaction?
5. Which of the memory allocation techniques first-fit, best-fit, worst-fit is efficient? Why?

5.3 ASSIGNMENT QUESTIONS


1. Write a C program to implement compaction technique.

EXPERIMENT 6

6.1 PRE-LAB QUESTIONS


1. What are the advantages of noncontiguous memory allocation schemes?
2. What is the process of mapping a logical address to physical address with respect to the paging memory
management technique?
3. Define the terms – base address, offset?

6.2 POST-LAB QUESTIONS


1. Differentiate between paging and segmentation memory allocation techniques?
2. What is the purpose of page table?
3. Whether the paging memory management technique suffers with internal or external fragmentation
problem. Why?
4. What is the effect of paging on the overall context-switching time?

6.3 ASSIGNMENT QUESTIONS


1. Write a C program to simulate two-level paging technique.
2. Write a C program to simulate segmentation memory management technique.
50
EXPERIMENT 7

7.1 PRE-LAB QUESTIONS


1. Define directory?
2. Describe the general directory structure?
3. List the different types of directory structures?

7.2 POST-LAB QUESTIONS


1. Which of the directory structures is efficient? Why?
2. Which directory structure does not provide user-level isolation and protection?
3. What is the advantage of hierarchical directory structure?

7.3 ASSI7GNMENT QUESTIONS


1. Write a C to simulate acyclic graph directory structure?
2. Write a C to simulate general graph directory structure?

EXPERIMENT 8

8.1 PRE-LAB QUESTIONS


1. Define resource. Give examples.
2. What is deadlock?
3. What are the conditions to be satisfied for the deadlock to occur?

8.2 POST-LAB QUESTIONS


1. How can be the resource allocation graph used to identify a deadlock situation?
2. How is Banker’s algorithm useful over resource allocation graph technique?
3. Differentiate between deadlock avoidance and deadlock prevention?

8.3 ASSIGNMENT QUESTIONS


1. Write a C program to implement deadlock detection technique for the following scenarios?
a. Single instance of each resource type
b. Multiple instances of each resource type

EXPERIMENT 9

9.1 PRE-LAB QUESTIONS


1. What is disk scheduling?
2. List the different disk scheduling algorithms?
3. Define the terms – disk seek time, disk access time and rotational latency?

9.2 POST-LAB QUESTIONS


1. What is the advantage of C-SCAN algorithm over SCAN algorithm?
2. Which disk scheduling algorithm has highest rotational latency? Why?

9.3 ASSIGNMENT QUESTIONS


1. Write a C program to implement SSTF disk scheduling algorithm?

EXPERIMENT 10

10.1 PRE-LAB QUESTIONS


1. Define the concept of virtual memory?
2. What is the purpose of page replacement?
3. Define the general process of page replacement?
4. List out the various page replacement techniques?
5. What is page fault?

10.2 POST-LAB QUESTIONS


51
1. Which page replacement algorithm suffers with the problem of Belady’s anomaly?
2. Define the concept of thrashing? What is the scenario that leads to the situation of thrashing?

10.3 ASSIGNMENT QUESTIONS


1. Write a C program to simulate LRU-approximation page replacement algorithm?
a. Additional-Reference bits algorithm
b. Second-chance algorithm

EXPERIMENT 11

11.1 PRE-LAB QUESTIONS


1. What are the benefits of optimal page replacement algorithm over other page replacement algorithms?

11.2 POST-LAB QUESTIONS


1. Why can’t the optimal page replacement technique be used in practice?

EXPERIMENT 12

12.1 PRE-LAB QUESTIONS


1. What is the need for process synchronization?
2. Define a semaphore?
3. Define producer-consumer problem?

12.2 POST-LAB QUESTIONS


1. Discuss the consequences of considering bounded and unbounded buffers in producer-consumer problem?
2. Can producer and consumer processes access the shared memory concurrently? If not which technique provides such
a benefit?

12.3 ASSIGNMENT QUESTIONS


1. Write a C program to simulate producer-consumer problem using message-passing system.

EXPERIMENT 13

13.1 PRE-LAB QUESTIONS


1. Differentiate between a monitor, semaphore and a binary semaphore?
2. Define clearly the dining-philosophers problem?

13.2 POST-LAB QUESTIONS


1. Identify the scenarios in the dining-philosophers problem that leads to the deadlock situations?

13.3 ASSIGNMENT QUESTIONS


1. Write a C program to simulate readers-writers problem using monitors?
1

UNIT-1
The File System
The UNIX file system looks like an inverted tree structure. You start with the root directory, denoted
by /, at the top and work down through sub-directories underneath it.

Each node is either a file or a directory of files, where the latter can contain other files and
directories. You specify a file or directory by its path name, either the full, or absolute, path name
or the one relative to a location. The full path name starts with the root, /, and follows the
branches of the file system, each separated by /, until you reach the desired file,
e.g.:
/home/condron/source/xntp
A relative path name specifies the path relative to another, usually the current working
directory that you are at. Two special directory entries should be introduced now:
. the current directory
.. the parent of the current directory
Vi Editor:
There are many ways to edit files in UNIX and for me one of the best ways is using screen- oriented
text editor vi. This editor enables you to edit lines in context with other lines in the file.
Now a days you would find an improved version of vi editor which is called VIM. Here
VIM stands for Vi IMproved.
The vi is generally considered the de facto standard in Unix editors because −
 It's usually available on all the flavors of Unix system.
 Its implementations are very similar across the board.
 It requires very few resources.
 It is more user friendly than any other editors like ed or ex.
You can use vi editor to edit an existing file or to create a new file from scratch. You can also use this
editor to just read a text file.

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


Starting the vi Editor
There are following way you can start using vi editor −

Command Description

vi filename Creates a new file if it already does not exist,


otherwise opens existing file.

vi -R filename Opens an existing file in read only mode.

view filename Opens an existing file in read only mode.


Following is the example to create a new file testfile if it already does not exist in the current
working directory −
$vi testfile
As a result you would see a screen something like as follows −
|
~
~
~
"testfile" [New File]
You will notice a tilde (~) on each line following the cursor. A tilde represents an unused line. If a line
does not begin with a tilde and appears to be blank, there is a space, tab, newline, or some other
nonviewable character present.
So now you have opened one file to start with. Before proceeding further let us understanding few minor but
important concepts explained below.
Operation Modes
While working with vi editor you would come across following two modes −
 Command mode − This mode enables you to perform administrative tasks such as saving files,
executing commands, moving the cursor, cutting (yanking) and pasting lines or words, and finding
and replacing. In this mode, whatever you type is interpreted as a command.
 Insert mode − This mode enables you to insert text into the file. Everything that's
typed in this mode is interpreted as input and finally it is put in the file .
The vi always starts in command mode. To enter text, you must be in insert mode. To come in insert mode
you simply type i. To get out of insert mode, press the Esc key, which will put you back into command mode.
Hint − If you are not sure which mode you are in, press the Esc key twice, and then you'll be in command
mode. You open a file using vi editor and start type some characters and then come in command mode to
understand the difference.
Getting Out of vi
The command to quit out of vi is :q. Once in command mode, type colon, and 'q', followed by return. If your
file has been modified in any way, the editor will warn you of this, and not let you quit. To ignore this
message, the command to quit out of vi without saving is :q!. This lets you exit vi without saving any of the
changes.
The command to save the contents of the editor is :w. You can combine the above command with the quit
command, or :wq and return.
The easiest way to save your changes and exit out of vi is the ZZcommand. When you are in command mode,
type ZZ and it will do the equivalent of :wq.
Basic Commands in Unix:
who, date, stty, pwd, cd, mkdir, rmdir, ls, cp, mv, rm, cat, more, wc,
unlink, chmod ,ps, du, df, mount, umount, find, umask,unmask, ulimit, , w, finger, tail, head , sort,
nl, uniq, grep, egrep, fgrep, cut, paste, join, tee, pg, comm, cmp, diff, tr, tar, gzip,cpio Who:

DIRECTORY RELATED UTILITES:


1. Pwd: Print the full pathname of the current directory.
Syntax: pwd
(Command name stands for “print working directory.”)
2. mkdir: Create one or more directories.
Syntax:
mkdir [options] directories
Example:
mkdir work;
mkdir junk;
3. cd: Change directory. cd is a built-in shell command
4. rmdir rmdir [options] directories
Delete the named directories (the directory itself, not the contents). directories are deleted
from the parent directory and must be empty
5.ls
ls [options] [names]
If no names are given, list the files in the current directory. With one or more names, list files
contained in a directory name or that match a file name. The options let you display a variety of
information in different formats.
Options
-a :List all files, including the normally hidden . files.
-b :Show nonprinting characters in octal.
-c :List files by inode modification time.
-C :List files in columns (the default format, when displaying to a terminal device).
-d :List only the directory's information, not its contents. (Most useful with -l and -i.)
-f :Interpret each name as a directory (files are ignored).
-g :Like -l, but omit owner name (show group).
-i :List the inode for each file.
-l :Long format listing (includes permissions, owner, size, modification time, etc.).
-L :List the file or directory referenced by a symbolic link rather than the link itself.
-m :Merge the list into a comma-separated series of names.
-n :Like -l, but use user ID and group ID numbers instead of owner and group names.
-o :Like -l, but omit group name (show owner).
-p :Mark directories by appending / to them.
-q :Show nonprinting characters as ?.
-r :List files in reverse order (by name or by time).
-R :Recursively list subdirectories as well as current directory.
-s :Print sizes of the files in blocks.
-t :List files according to modification time (newest first).
-u :List files according to the file access time.
-x :List files in rows going across the screen.
-1 :Print one entry per line of output.
Examples
List all files in the current directory and their sizes; use multiple columns and mark special files:
4

ls
-asCF
who
or w
report who is logged in and what processes are running
Eight Fields of ls –l:

where:

o type is a single character which is either 'd' (directory), '-' (ordinary


file), 'l' (symbolic link), 'b' (block-oriented device) or 'c' (character-
oriented device).
o permissions is a set of characters describing access rights. There are 9
permission characters, describing 3 access types given to 3 user
categories. The three access types are read ('r'), write ('w') and
execute ('x'), and the three users categories are the user who owns the
file, users in the group that the file belongs to and other users (the
general public). An 'r', 'w' or 'x' character means the corresponding
permission is present; a '-' means it is absent.
o links refers to the number of filesystem links pointing to the
file/directory (see the discussion on hard/soft links in the next
section).
o owner is usually the user who created the file or directory.
o group denotes a collection of users who are allowed to access the file
according to the group access rights specified in the permissions field.
o size is the length of a file, or the number of bytes used by the
operating system to store the list of files in a directory.
o date is the date when the file or directory was last modified (written
to). The -u option display the time when the file was last accessed
(read).
o name is the name of the file or directory.

FILE HANDLING AND TEXT PROCESSING UTILITIES:

cp - copy a file

Copy the contents of one file to another with the cp command.


Syntax
cp [options] old_filename new_filename
Common Options
-i interactive (prompt and wait for confirmation before proceeding)

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


5

-r recursively copy a directory


Examples
cp old_filename new_filename
You now have two copies of the file, each with identical contents. They are completely
independent of each other and you can edit and modify either as needed. They each have their own
inode, data blocks, and directory table entries.
mv - move a file
Rename a file with the move command, mv.
Syntax
mv [options] old_filename new_filename
Common Options
-i interactive (prompt and wait for confirmation before proceeding)
-f don’t prompt, even when copying over an existing target file (overrides -i)
Examples
mv old_filename new_filename
You now have a file called new_filename and the file old_filename is gone. Actually all
you’ve
done is to update the directory table entry to give the file a new name. The contents of the file
remain where they were.
rm - remove a file
Remove a file with the rm, remove, command.
Syntax
rm [options] filename
Common Options
-i interactive (prompt and wait for confirmation before proceeding)
-r recursively remove a directory, first removing the files and subdirectories beneath it
-f don’t prompt for confirmation (overrides -i)
Examples
rm old_filename
A listing of the directory will now show that the file no longer exists. Actually, all you’ve done is
to remove the directory table entry and mark the inode as unused. The file contents are still on
the disk,but the system now has no way of identifying those data blocks with a file name.

File Permissions
Each file, directory, and executable has permissions set for who can read, write, and/or
execute it.
To find the permissions assigned to a file, the ls command with the -l option should be used. Also,
using the -g option with "ls -l" will help when it is necessary to know the group for which the
permissions are
When using the "ls -l" command on a file the output will appear as follows:
-rwxr-x--- user unixgroup size Month nn hh:mm filename
The area above designated by letters and dashes (-rwxr-x---) is the area showing the file type
andpermissions as defined in the previous Section. Therefore, a permission string, for example, of-
rwxr-x--- allows the user (owner) of the file to read, write, and execute it; those in the unixgroup of
the file can read and execute it; others cannot access it at all.
chmod - change file permissions
The command to change permissions on an item (file, directory, etc) is chmod (change
mode). The syntax involves using the command with three digits (representing the user

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


6

(owner, u) permissions, the group (g) permissions, and other (o) user's permissions) followed by
the argument (which may be a file name or list of files and directories). Or by using symbolic
representation for the permissions and who they apply to.
Each of the permission types is represented by either a numeric equivalent: read=4,
write=2, execute=1 or a single letter:
read=r, write=w, execute=x
A permission of 4 or r would specify read permissions. If the permissions desired are read and
write,the 4 (representing read) and the 2 (representing write) are added together to make a
permission of 6.Therefore, a permission setting of 6 would allow read and write permissions.
Alternatively, you could use symbolic notation which uses the one letter representation for who
and for the permissions and an operator, where the operator can be:
+ add permissions - remove permissions = set permissions
So to set read and write for the owner we could use "u=rw" in symbolic notation.
Syntax
chmod nnn [argument list] numeric mode
chmod [who]op[perm] [argument list] symbolic mode
where nnn are the three numbers representing user, group, and other permissions, who is any of
u, g,o, or a (all) and perm is any of r, w, x. In symbolic notation you can separate permission
specifications by commas, as shown in the example below.
Common Options
-f force (no error message is generated if the change is unsuccessful)
-R recursively descend through the directory structure and change the modes
Examples
If the permission desired for file1 is user: read, write, execute, group: read, execute, other: read,
execute, the command to use would be
chmod 755 file1 or chmod u=rwx,go=rx file1
Reminder: When giving permissions to group and other to use a file, it is necessary to allow
at leastexecute permission to the directories for the path in which the file is located. The
easiest way to do this is to be in the directory for which permissions need to be granted:
chmod 711 . or chmod u=rw,+x . or chmod u=rwx,go=x .
where the dot (.) indicates this directory.

chown - change ownership


Ownership of a file can be changed with the chown command. On most versions of Unix this can
only be done by the super-user, i.e. a normal user can’t give away ownership of their files.
chown is used as below, where # represents the shell prompt for the super-user:
Syntax
chown [options] user[:group]
Common Options
-R recursively descend through the directory structure
-f force, and don’t report any errors
Examples
# chown new_owner file
chgrp - change group
Anyone can change the group of files they own, to another group they belong to, with the
chgrp

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


7

command.
Syntax
chgrp [options] group file
Common Options
-R recursively descend through the directory structure
-f force, and don’t report any errors
Examples
% chgrp new_group file
echo - echo a statement
The echo command is used to repeat, or echo, the argument you give it back to the standard
output device. It normally ends with a line-feed, but you can specify an option to prevent this.
Syntax
echo [string]
Common Options
-n don’t print <new-line>
\c don’t print <new-line>
\t tab
\f form-feed (SVR4)
\n new-line (SVR4)
\v vertical tab (SVR4)
Examples
% echo Hello Class or echo "Hello Class" To
prevent the line feed:
% echo -n Hello Class or echo "Hello Class \c"
where the style to use in the last example depends on the echo command in use.
The \x options must be within pairs of single or double quotes, with or without other string
characters.
cat - concatenate a file
Display the contents of a file with the concatenate command, cat.
Syntax
cat [options] [file]
Common Options
-n precede each line with a line number
-v display non-printing characters, except tabs, new-lines, and form-feeds
-e display $ at the end of each line (prior to new-line) (when used with -v option)
Examples
% cat filename
You can list a series of files on the command line, and cat will concatenate them, starting each
in turn, immediately after completing the previous one,
e.g.:
cat file1 file2 file3
more, less, and pg - page through a file
more, less, and pg let you page through the contents of a file one screenful at a time. These may
not all be available on your Unix system. They allow you to back up through the previous
pages and search for words, etc.
Syntax
more [options] [+/pattern]
[filename] less [options]
[+/pattern] [filename] pg [options]
[+/pattern] [filename] Options

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


8

more less pg Action


-c -c -c clear display before displaying
-i ignore case
-w default default don’t exit at end of input, but prompt and wait
-lines -lines # of lines/screenful
+/pattern +/pattern +/pattern search for the pattern
head - display the start of a file
head displays the head, or start, of the file.
Syntax
head [options] file
Common Options
-n number number of lines to display, counting from the top of the file
-number same as above
Examples
By default head displays the first 10 lines. You can display more with the "-n number", or "-
number" options, e.g., to display the first 40 lines:
$ head -40 filename or head -n 40 filename
tail - display the end of a file
tail displays the tail, or end, of the file.
Syntax
tail [options] file
Common Options
-number number of lines to display, counting from the bottom of the file
Examples
The default is to display the last 10 lines, but you can specify different line or byte numbers, or a
different starting point within the file. To display the last 30 lines of a file use the -number
style:
$ tail -30 filename
date - current date and time
date displays the current data and time. A superuser can set the date and time.
Syntax
date [options] [+format]
Common Options
-u use Universal Time (or Greenwich Mean Time)
+format specify the output format
%a weekday abbreviation, Sun to Sat
%h month abbreviation, Jan to Dec
%j day of year, 001 to 366
%n <new-line>
%t <TAB>
%y last 2 digits of year, 00 to 99
%D MM/DD/YY date
%H hour, 00 to 23
%M minute, 00 to 59
%S second, 00 to 59
%T HH:MM:SS time
Examples
beauty condron>date
Mon Jun 10 09:01:05 EDT 1996

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


9

beauty condron>date -u
Mon Jun 10 13:01:33 GMT 1996
beauty condron>date +%a%t%D
Mon 06/10/96
beauty condron>date '+%y:%j'
96:162

cmp - compare file contents


The cmp command compares two files, and (without options) reports the location of the first
difference between them. It can deal with both binary and ASCII file comparisons. It does a byte-by-
byte comparison.
Syntax
cmp [options] file1 file2 [skip1] [skip2]
The skip numbers are the number of bytes to skip in each file before starting the comparison.
Common Options
-l report on each difference
-s report exit status only, not byte differences
diff - differences in files
The diff command compares two files, directories, etc, and reports all differences between the two.
It deals only with ASCII files. It’s output format is designed to report the changes necessary to
convert the first file into the second.
Syntax
diff [options] file1 file2
Common Options
-b ignore trailing blanks
-i ignore the case of letters
-w ignore <space> and <tab> characters
-e produce an output formatted for use with the editor, ed
-r apply diff recursively through common sub-directories
cut - select parts of a line
The cut command allows a portion of a file to be extracted for another use.
Syntax
cut [options] file
Common Options
-c character_list character positions to select (first character is 1)
-d delimiter field delimiter (defaults to <TAB>)
-f field_list fields to select (first field is 1)
Both the character and field lists may contain comma-separated or blank-character-separated
numbers (in increasing order), and may contain a hyphen (-) to indicate a range. Any
numbers
missing at either before (e.g. -5) or after (e.g. 5-) the hyphen indicates the full range starting with
thefirst, or ending with the last character or field, respectively. Blank-character- separated lists
must beenclosed in quotes. The field delimiter should be enclosed in quotes if it has special meaning
to the shell, e.g. when specifying a <space> or <TAB> character.
Examples
In these examples we will use the file users:
jdoe John Doe 4/15/96
lsmith Laura Smith
3/12/96 pchen Paul
Chen 1/5/96 jhsu Jake
Hsu 4/17/96

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


10

sphilip Sue Phillip 4/2/96


If you only wanted the username and the user's real name, the cut command could be used to get
only
that information:
% cut -f 1,2
users jdoe
John Doe
lsmith Laura
Smith pchen
Paul Chen jhsu
Jake Hsu
sphilip Sue
Phillip paste -
merge files
The paste command allows two files to be combined side-by-side. The default delimiter
between the columns in a paste is a tab, but options allow other delimiters to be used.
Syntax
paste [options] file1 file2
Common Options
-d list list of delimiting characters
-s concatenate lines
The list of delimiters may include a single character such as a comma; a quoted string, such as a
space; or any of the following escape sequences:
\n <newline> character
\t <tab> character
\\ backslash character
\0 empty string (non-null character)
It may be necessary to quote delimiters with special meaning to the shell.
A hyphen (-) in place of a file name is used to indicate that field should come from standard input.
touch - create a file
The touch command can be used to create a new (empty) file or to update the last access
date/time onan existing file. The command is used primarily when a script requires the pre-
existence of a file (for example, to which to append information) or when the script is
checking for last date or time afunction was performed.
Syntax touch [options] [date_time] file
wc - count words in a file
wc stands for "word count"; the command can be used to count the number of lines,
characters, or
words in a file.
Syntax
wc [options] file
Common Options
-c count bytes
-m count characters (SVR4)
-l count lines
-w count words
ln - link to another file
The ln command creates a "link" or an additional way to access (or gives an additional name to)
another file.
Syntax

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


11

ln [options] source [target]


If not specified target defaults to a file of the same name in the present working directory.
Common Options
-f force a link regardless of target permissions; don’t report errors (SVR4 only)
-s make a symbolic link
Examples
A symbolic link is used to create a new path to another file or directory
sort - sort file contents
The sort command is used to order the lines of a file. Various options can be used to choose the order
as well as the field on which a file is sorted. Without any options, the sort compares entire lines
in the
file and outputs them in ASCII order (numbers first, upper case letters, then lower case
letters).
Syntax
sort [options] [+pos1 [ -pos2 ]] file

Common Options
-b ignore leading blanks (<space> & <tab>) when determining starting and ending
characters for the sort key
-d dictionary order, only letters, digits, <space> and <tab> are significant
-f fold upper case to lower case
-k keydef sort on the defined keys (not available on all systems)
-i ignore non-printable characters
-n numeric sort
-o outfile output file
-r reverse the sort
-t char use char as the field separator character
-u unique; omit multiple copies of the same line (after the sort)
+pos1 [-pos2] (old style) provides functionality similar to the "-k keydef" option.
tee - copy command output
tee sends standard in to specified files and also to standard out. It’s often used in command
pipelines.
Syntax
tee [options] [file[s]]
Common Options
-a append the output to the files
-i ignore interrupts
uniq - remove duplicate lines
uniq filters duplicate adjacent lines from a file.
Syntax
uniq [options] [+|-n] file [file.new]
Common Options
-d one copy of only the repeated lines
-u select only the lines not repeated
+n ignore the first n characters
-s n same as above
-n skip the first n fields, including any blanks (<space> & <tab>)
-f fields same as above
tr - translate characters

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


12

The tr command translates characters from stdin to stdout.


Syntax
tr [options] string1 [string2]
With no options the characters in string1 are translated into the characters in string2, character
by
character in the string arrays. The first character in string1 is translated into the first character in
string2, etc.
To translate all lower case alphabetic characters to upper case we could use either of:
tr ’[a-z]’ ’[A-Z]’ or tr ’[:lower:]’ ’[:upper:]’
FILE ARCHIVING, COMPRESSION AND CONVERSION COMMANDS:
File Compression
The compress command is used to reduce the amount of disk space utilized by a file. When a file has
been compressed using the compress command, a suffix of .Z is appended to the file name. The
ownership modes and access and modification times of the original file are preserved. uncompress
restores the files originally compressed by compress.
Syntax
compress [options] [file]
uncompress [options] [file.Z]
zcat [file.Z]
Common Options
-c write to standard output and don’t create or change any files
-f force compression of a file, even if it doesn’t reduce the size of the file or if
the target file (file.Z) already exists.
-v verbose. Report on the percentage reduction for the file.
The GNU programs to provide similar functions to those above are often installed as gzip,
gunzip, and zcat, respectively. Files compressed with gzip are given the endings .z or .gz. tar -
archive files
The tar command combines files into one device or filename for archiving purposes. The tar
command does not compress the files; it merely makes a large quantity of files more manageable.
Syntax
tar [options] [directory file]
Common Options
c create an archive (begin writting at the start of the file)
t table of contents list
x extract from an archive
v verbose
f archive file name
b archive block size
tar will accept its options either with or without a preceding hyphen (-). The archive file can be a
disk file, a tape device, or standard input/output. The latter are represented by a hyphen. SYSTEM
RESOURCE COMMANDS:
df - summarize disk block and file usage
df is used to report the number of disk blocks and inodes used and free for each file system.
The
output format and valid options are very specific to the OS and program version in use.
Syntax
df [options] [resource]
Common Options

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


13

-l local file systems only


-k report in kilobytes
du - report disk space in use
du reports the amount of disk space in use for the files or directories you specify.
Syntax
du [options] [directory or file]

Common Options
-a display disk usage for each file, not just subdirectories
-s display a summary total only
-k report in kilobytes
ps - show status of active processes
ps is used to report on processes currently running on the system. The output format and valid
options are very specific to the OS and program version in use.
Syntax
ps [options]
Mount:
A file system must be mounted in order to be usable by the system. To see what is currently mounted
(available for use) on your system, use this command:
$mount
Syntax:
mount -t file_system_type device_to_mount directory_to_mount_to
For example, if you want to mount a CD-ROM to the directory /mnt/cdrom, for example, you can
type:
$ mount -t iso9660 /dev/cdrom /mnt/cdrom
This assumes that your CD-ROM device is called /dev/cdrom and that you want to mount it to
/mnt/cdrom. Refer to the mount man page for more specific information or type mount -h at the
command line for help information.
After mounting, you can use the cd command to navigate the newly available file system through the
mountpoint you just made.
Unmounting the File System:
To unmount (remove) the file system from your system, use the umount command by identifying the
mountpoint or device
For example, to unmount cdrom, use the following command:
$ umount /dev/cdrom
find - find files
The find command will recursively search the indicated directory tree to find files matching a type or
pattern you specify. find can then list the files or execute arbitrary commands based on the results.
Syntax
find directory [search options] [actions]
Common Options
For the time search options the notation in days, n is:
+n more than n days
n exactly n days
-n less than n days
Umask :
Show the permissions that are given to view files by default
ulimit

UNIX IT5T1 PVPSIDDHARTHA INSTITUTE OF TECHNOLOGY


NAME
ulimit - Modify shell resource limits.
SYNOPSIS
ulimit [-SHacdefilmnpqrstuvx] [limit]

DESCRIPTION
Modify shell resource limits.
Provides control over the resources available to the shell and processes it creates,
on systems that allow such control.
finger - get information about users
finger displays the .plan file of a specific user, or reports who is logged into a specific machine. The user must
allow general read permission on the .plan file.
Syntax
finger [options] [user[@hostname]]
Common Options
-l force long output format
-m match username only, not first or last names
-s force short output format
cpio copies files to and from archives. cpio stands for “copy in, copy out”.
TEXT PROCESSING COMMANDS:
The grep program searches a file or files for lines that have a certain pattern. The syntax is:
$grep pattern file(s)
Option Description
-v Print all lines that do not match pattern.
-n Print the matched line and its line number.
-l Print only the names of files with matching lines (letter "l")
-c Print only the count of matching lines.
-i Match either upper- or lowercase.

Displays only Aug Files

$ls -l | grep "Aug"

-rw-rw-rw- 1 john doc 11008 Aug 6 14:10 ch02

-rw-rw-rw- 1 john doc 8515 Aug 6 15:30 ch07

-rw-rw-r-- 1 john doc 2488 Aug 15 10:51 intro

-rw-rw-r-- 1 carol doc 1605 Aug 23 07:35 macros

egrep is the same as running grep -E. In this mode, grep evaluates yourPATTERN string as an extended
regular expression (ERE). Nowadays, ERE does not "extend" very far beyond basic regular expressions, but
they can still be very useful.

fgrep is the same as running grep -F. In this mode, grep evaluates your PATTERNstring as a "fixed string" —
every character in your string is treated literally. For example, if your string contains an asterisk ("*"), grep
will try to match it with an actual asterisk rather than
interpreting this as a wildcard. If your string contains multiple lines (if it contains newlines), each
line will be considered a fixed string, and any of them can trigger a match.

grep 'fred' /etc/passwd # search for lines containing 'fred' in /etc/passwd


grep fred /etc/passwd # quotes usually not when you don't use regex patterns grep
null *.scala # search multiple files

case-insensitive
grep -i joe users.txt # find joe, Joe, JOe, JOE, etc.
regular expressions
grep '^fred' /etc/passwd # find 'fred', but only at the start of a line grep
'[FG]oo' * # find Foo or Goo in all files in the current dir
grep '[0-9][0-9][0-9]' * # find all lines in all files in the current dir with three numbers in a row
display matching filenames, not lines
grep -l StartInterval *.plist # show all filenames containing the string 'StartInterval' grep -il
StartInterval *.plist # same thing, case-insensitive
show matching line numbers
grep -n we gettysburg-address.txt # show line numbers as well as the matching lines
lines before and after grep match
grep -B5 "the living" gettysburg-address.txt # show all matches, and five lines before each
match
grep -A10 "the living" gettysburg-address.txt # show all matches, and ten lines after each match
grep -B5 -A5 "the living" gettysburg-address.txt # five lines before and ten lines after
reverse the meaning
grep -v fred /etc/passwd # find any line *not* containing 'fred' grep
-vi fred /etc/passwd # same thing, case-insensitive
grep in a pipeline
ps auxwww | grep httpd # all processes containing 'httpd'
ps auxwww | grep -i java # all processes containing 'java', ignoring case ls
-al | grep '^d' # list all dirs in the current dir
search for multiple patterns
egrep 'apple|banana|orange' * # search for multiple patterns, all files in current dir
egrep -i 'apple|banana|orange' * # same thing, case-insensitive
multiple search strings, multiple filename patterns:
grep -li "jtable" $(find . -name "*.java,v" -exec grep -li "prevayl" {} \;) # find all files
named "*.java,v" containing both # 'prevayl' and 'jtable'
grep + find
find . -type f -exec grep -il 'foo' {} \; # print all filenames of files under current dir
containing 'foo', case-insensitive
recursive grep search
grep -rl 'null' . # very similar to the previous find command; does a recursive
search
grep -ril 'null' /home/al/sarah /var/www # search multiple dirs
egrep -ril 'aja|alvin' . # multiple patterns, recursive

You might also like