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

OS & LINUX Labmanual R16

The document outlines the objectives and structure of an Operating System and Linux Programming Lab course at GIET Engineering College. It includes various tasks such as simulating CPU scheduling algorithms, memory management, and writing C programs to interact with Unix/Linux commands and file systems. The lab aims to familiarize students with operating system concepts and enhance their skills in using the Linux environment and shell scripting.

Uploaded by

nagulm1450
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)
15 views76 pages

OS & LINUX Labmanual R16

The document outlines the objectives and structure of an Operating System and Linux Programming Lab course at GIET Engineering College. It includes various tasks such as simulating CPU scheduling algorithms, memory management, and writing C programs to interact with Unix/Linux commands and file systems. The lab aims to familiarize students with operating system concepts and enhance their skills in using the Linux environment and shell scripting.

Uploaded by

nagulm1450
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

OPERATING SYSTEM & LINUX PROGRAMMING LAB

GIET ENGINEERING COLLEGE


III [Link] I SEMESTER R16

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

OPERATING SYSTEM & LINUX PROGRAMMING LAB

OBJECTIVES:
 To identify the design aspects of operating system.
 To study the process management concepts & Techniques.
 To study the storage management concepts.
 To familiarize students with the Linux environment
 To learn the fundamentals of shell scripting/programming

PART – A:
1. Simulate the following CPU scheduling algorithms
(a) Round Robin b) SJF c) FCFS d) Priority
2. Multiprogramming-Memory management- Implementation of fork (), wait (), exec() and
exit (), System calls
3. Simulate the following
a. Multiprogramming with a fixed number of tasks (MFT)
b. Multiprogramming with a variable number of tasks (MVT)
4. Simulate Bankers Algorithm for Dead Lock Avoidance
5. Simulate Bankers Algorithm for Dead Lock Prevention.
6. Simulate the following page replacement algorithms.
(a) FIFO b) LRU c) LFU
7. Simulate the following File allocation strategies
(a) Sequenced b) Indexed c) Linked

Page No 1 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

PART – B:
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.
(b) Study of vi editor.
(c) Study of Bash shell, Bourne shell and C shell in Unix/Linux operating system.
(d) Study of Unix/Linux file system (tree structure).
(e) Study of .bashrc, /etc/bashrc and Environment variables.
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. Write a C program that illustrates two processes communicating using shared memory
6. Write a C program to simulate producer and consumer problem using semaphores
7. Write C program to create a thread using pthreads library and let it run its function.
8. Write a C program to illustrate concurrent execution of threads using pthreads library.

OUTCOMES:
 To use Unix utilities and perform basic shell control of the utilities
 To use the Unix file system and file access control.
 To use of an operating system to develop software
 Students will be able to use Linux environment efficiently
 Solve problems using bash for shell scripting

Page No 2 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

TABLE OF CONTENT

OPERATING SYSTEM
1 Simulate the following CPU scheduling algorithms
(a) Round Robin b) SJF c) FCFS d) Priority
2 Multiprogramming-Memory management- Implementation of fork (), wait
(), exec() and exit (), System calls
3 Simulate the following
a. Multiprogramming with a fixed number of tasks (MFT)
b. Multiprogramming with a variable number of tasks (MVT)
4 Simulate Bankers Algorithm for Dead Lock Avoidance
5 Simulate Bankers Algorithm for Dead Lock Prevention
6 Simulate the following page replacement algorithms.
(a) FIFO b) LRU c) LFU
7 Simulate the following File allocation strategies
(a) Sequenced b) Indexed c) Linked
LINUX PROGRAMMING
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.
(b) Study of vi editor.
(c) Study of Bash shell, Bourne shell and C shell in Unix/Linux operating
system.
(d) Study of Unix/Linux file system (tree structure).
(e) Study of .bashrc, /etc/bashrc and Environment variables.
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 Write a C program that illustrates two processes communicating using
shared memory
6 Write a C program to simulate producer and consumer problem using
semaphores
7 Write C program to create a thread using pthreads library and let it run its
function.
8 Write a C program to illustrate concurrent execution of threads using
pthreads library.

// Program to implement FCFS//

Page No 3 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Description: FCFS is the simplest algorithm. Here the process that requests the CPU first is
allocated to CPU first. This is done with FIFO Queue. The Average Waiting Time under the FCFS
policy is quite long. Once the CPU is allocated process it will not release the cpu until it is
terminated or switched.

Program:
#include<stdio.h>
main()
{
char p[5][5];
int arrival_time[10],i,n,burst_time[10],start_time[10],finish_time[10],
waiting_time[10],turnaround_time[10],tot=0,tot1=0;
float avg_wait=0.0,avg_turn=0.0;
clrscr();
printf("\n **FIRST COME FIRST SERVE SCHEDULING ALGORITHM** ");
printf("Enter no of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter process %d name:\n",i+1);
scanf("%s",&p[i]);
printf("Enter Burst time:");
scanf("%d",&burst_time[i]);
}
start_time[0]=0;
for(i=0;i<n;i++)
{
start_time[i+1]=start_time[i]+burst_time[i];
finish_time[i]=start_time[i]+burst_time[i];
waiting_time[i]=finish_time[i]-burst_time[i];
turnaround_time[i]=start_time[i]+burst_time[i];

Page No 4 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

tot=tot+waiting_time[i];
tot1=tot1+turnaround_time[i];
}
avg_wait=tot/n;
avg_turn=tot/n;
printf("Process_Name\tBurst_Time\tStart_Time\tFinish_Time\tWaiting_Time\tTurnaround_Time\
n");
for(i=0;i<n;i++)
{
printf("\n%s\t%d\t%d\t%d\t%d\t
%d",p[i],burst_time[i],start_time[i],finish_time[i],waiting_time[i],turnaround_time[i]);
}
printf("\n Average waiting time is %f",avg_wait);
printf("\n Average turnaround time is %f",avg_turn);
getch();
}

SAMPLE DATA :

Page No 5 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

**FIRST COME FIRST SERVE SCHEDULING ALGORITHM**


Enter no. of process: 4
Enter process name: A
Enter Burst time: 3
Enter process name: B
Enter Burst time: 6
Enter process name: C
Enter Burst time: 4
Enter process name: D
Enter Burst time: 2

Process_Name Burst_Time Start_Time Finish_Time Waiting_Time Turnaround_Time


A 3 0 3 0 3
B 6 3 9 3 9
C 4 9 13 9 13
D 2 13 15 13 15

Average waiting time is: 6.000000


Average turnaround time is: 6.000000

// Program to implement SJF //

Description : Both pre emptive and non preemptive. the algorithm schedules the processes by this

Page No 6 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

cpu burst time, the processes with less cpu burst time will the processed first before other processes.
if two processes have same burst times then they will be scheduled by using FCFS scheduling. This
is also called as “shortest next cpu burst”.

Program :
#include<stdio.h>
main()
{
int at[10],i,n,j,st[10],ft[10],wt[10],tt[10],tot=0,tot1=0,temp1,bt[10];
char p[10][5],temp[5];
float avgwt=0.0,avgturn=0.0;
clrscr();
printf("\n ** SHORTEST JOB FIRST SCHEDULING ALGORITHM ** ");
printf("`enter no of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter process %d name:\n",i+1);
scanf("%s",&p[i]);
printf("Enter burst time:");
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
if(bt[i]>bt[j])
{
temp1=bt[i];

bt[i]=bt[j];
bt[j]=temp1;
strcpy(temp,p[i]);

Page No 7 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

strcpy(p[i],p[j]);
strcpy(p[j],temp);
}
}
st[0]=0;
for(i=0;i<n;i++)
{
st[i+1]=st[i]+bt[i];
ft[i]=st[i]+bt[i];
wt[i]=ft[i]-bt[i];
tt[i]=st[i]+bt[i];
tot=tot+wt[i];
tot1=tot1+tt[i];
}
avgwt=(float)tot/n;
avgturn=(float)tot1/n;
printf("Process_Name \t Service_Ttime \t Start_Time \t Finish_Time \t Waiting_Time \t
Turnaround_Time\n");
for(i=0;i<n;i++)
{
printf("\n%s\t%d\t%d\t%d\t%d\t%d",p[i],bt[i],st[i],ft[i],wt[i],tt[i]);
}
printf("\n Average Waiting Time is : %f",avgwt);
printf("\n Average Turnaround Time is :%f",avgturn);
getch();
}

SAMPLE DATA:

** SHORTEST JOB FIRST SCHEDULING ALGORITHM **

Page No 8 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Enter [Link] process: 4


Enter process 1 name: A
Enter burst time:3
Enter process 2 name: B
Enter burst time:6
Enter process 3 name: C
Enter burst time:4
Enter process 4 name: D
Enter burst time:2

Process name Service_time Start_time Finish_time Waiting_time Turnaround_time


D 2 0 2 0 2
A 3 2 5 2 5
C 4 5 9 5 9
B 6 9 15 9 15

Average Waiting Time is: 4.00


Average Turnaround Time is: 7.75

// Program to implement Priority //

Description : Either preemptive or non preemptive. This algorithm associates each process with a
priority and the process with highest priority will get the CPU first. If two processes with same

Page No 9 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

priority FCFS scheduling is used to break the tie.

Program :
#include<stdio.h>
main()
{
int i,n,j,bt[10],st[10],pr[10],ft[10],wt[10],tt[10],temp1;
char pn[10][5],temp[10];
float tot=0.0,tot1=0.0,avgwt=0.0,avgturn=0.0;
clrscr();
printf("\n ** PRIORITY SCHEDULING ALGORITHM **");
printf("`enter no of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter process %d name:\n",i+1);
scanf("%s",&pn[i]);
printf("Enter Burst time:");
scanf("%d",&bt[i]);
printf("Enter priority:");
scanf("%d",&pr[i]);
}
st[0]=0;
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)

if(pr[i]>pr[j])
{
temp1=pr[i];
pr[i]=pr[j];

Page No 10 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

pr[j]=temp1;
temp1=bt[i];
bt[i]=bt[j];
bt[j]=temp1;
strcpy(temp,pn[i]);
strcpy(pn[i],pn[j]);
strcpy(pn[j],temp);
}
}
for(i=0;i<n;i++)
{
st[i+1]=st[i]+bt[i];
ft[i]=st[i]+bt[i];
wt[i]=ft[i]-bt[i];
tt[i]=st[i]+bt[i];
tot=tot+wt[i];
tot1=tot1+tt[i];
}
avgwt=tot/n;
avgturn=tot1/n;
printf("Process_Name\tBurst_Time\tPriority\tStart_Time\tFinish_Time\tWait_Time\
tTurnAround_Time\n");
for(i=0;i<n;i++)
{
printf("\n%s\t%d\t%d\t%d\t%d\t%d\t%d",pn[i],bt[i],pr[i],st[i],ft[i],wt[i], tt[i]);
}
printf("\n Average waiting time is: %f",avgwt);
printf("\n Average turnaround time is: %f",avgturn);
getch();
}

Page No 11 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

SAMPLE DATA :
** PRIORITY SCHEDULING ALGORITHM **
Enter no. of process: 4
Enter process name: A
Enter process time: 3
Enter priority: 4
Enter process name: B
Enter process time: 6
Enter priority: 3
Enter process name: c
Enter process time: 4
Enter priority: 2
Enter process name: D
Enter process time: 2
Process name Burst time Priority Start time Finish time Wait time Turnaround time
D 2 1 0 2 0 2
C 4 2 2 6 2 6
B 6 3 6 12 6 12
A 3 4 12 15 12 15
Enter priority: 1

Average waiting time is: 5.000000


Average turnaround time is: 8.750000

// PROGRAM SIMULATING ROUND ROBIN CPU SCHEDULING ALGORITHM //

Description : This is designed especially for time sharing systems. it is similar to FCFS scheduling
but preemption is added to switch between processes. a small unit of time called a time quantum or
time slice is defined. It is usually from 10to [Link] ready queue is treated as circular queue &

Page No 12 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

cpu scheduler goes around the ready queue allocating the cpu to each processes for a time interval
of up to 1 time quantum.

Program :
#include<stdio.h>
main()
{
int i,f=0,q,n,c=0,a[10],srt[10],wtt[10],ft[10];
char pn[10];
clrscr();
printf("\n ** ROUND ROBIN SCHEDULING ALGORITHM ** ");
printf("enter the no of processes:");
scanf("%d",&n);
printf("enter the quantum:");
scanf("%d",&q);
for(i=0;i<n;i++)
{
printf("enter the process name:");
scanf("%s",&pn[i]);
printf("enter the service time");
scanf("%d",&srt[i]);
}
for(i=0;i<n;i++)
{
a[i]=srt[i];
}
i=0;
while(1)
{
if(srt[i]!=0)
{

Page No 13 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

if(srt[i]<=q)
{
f=f+srt[i];
ft[i]=f;
wtt[i]=ft[i]-a[i];
srt[i]=0;
}
else
{
srt[i]=srt[i]-q;
f=f+q;
}
}
else
c++;
if(c==n)
break;
i++;
if(i==n)
{
i=0;
c=0;
}
}
printf("\n PROCESS_NAME\t SERVICE_TIME\tWAIT_TIME\t TURN_AROUND_TIME");
for(i=0;i<n;i++)
{
printf("\n %c\t\t\t %d\t\t%d\t\t%d",pn[i],a[i],wtt[i],ft[i]);
}
printf("\n");
getch();

Page No 14 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

SAMPLE DATA :
** ROUND ROBIN SCHEDULING ALGORITHM **
Enter no. of processes: 4
Enter quantum: 2
Enter the process name: a
Enter the service time : 3
Enter the process name: b
Enter the service time : 2
Enter the process name: c
Enter the service time : 4
Enter the process name: d
Enter the service time : 5
PROCESS_NAME SERVICE_TIME WAIT_TIME TURN_AROUND_TIME
1 3 6 9
2 2 2 4
3 4 7 11
4 5 9 14

// PROGRAM TO IMPLEMENT MFT //

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.

Page No 15 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Program :
#include<stdio.h>
main()
{
int par_size,n,count=0,flag,size,wastage;
char ch;
clrscr();
printf("** MULTI PROGRAMMING WITH FIXED TASKS **");
printf("\nEnter the number of partitions:");
scanf("%d",&n);
printf("Enter the partition size:");
scanf("%d",&par_size);
ch='y';
while(ch=='y')
{
flag=0;
if(count<n)
{
printf("Enter the size of the job which you want to execute:");
scanf("%d",&size);
if(par_size>=size)
{
flag=1;

count++;
wastage=par_size-size;
printf("Job is executed\n");
printf("Memory Wastage is:%2d\n",wastage);
}
}
else

Page No 16 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

{
printf("No partition is free\n");
exit(0);
}
if(flag==0)
printf("This job cannot be executed, Job size exceeds Partition size.\n");
printf("Enter your choice(y or n):");
scanf(" %c",&ch);
}
}

SAMPLE OUTPUT:
** MULTI PROGRAMMING WITH FIXED TASKS **
Enter the number of partitions: 6
Enter the partition size: 5
Enter the size of the job which you want to execute: 4
Job is executed.
Memory Wastage is : 1
Enter your choice is (y/n) : y
Enter the size of the job which you want to execute: 7
This job cannot be executed, Job size exceeds Partition size.
Enter your choice (y/n) : n

// Program to implement MVT //

Description: MVT (Multiprogramming with a Variable number of Tasks) is the memory


management technique 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

Page No 17 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

suffers with external fragmentation.

Program :
#include<stdio.h>
void sort(int a[],int size)
{
int i,j,temp;
for(i=0;i<size;i++)
{
for(j=0;j<size-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}}}
void main()
{
int a[20],n,i,flag,count=0,size,wastage;
char ch;
clrscr();
printf("** MULTI PROGRAMMING WITH VARIABLE TASKS **");
printf("\n Enter the number of partitions:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter Partition: %d size:",i+1);
scanf("%d",&a[i]);
}

Page No 18 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

sort(a,n);
ch='y';
while(ch=='y')
{
if(count<n)
{
printf("Enter the size of the job that is to be executed:");
scanf("%d",&size);
flag=0;
for(i=0;i<n;i++)
{
if((a[i]>=size)&&(a[i]!=0))
{
count=count+1;
wastage=a[i]-size;
a[i]=0;
flag=1;
printf("Job is executed.\n");
printf("Memory Wastage is:%2d\n",wastage);
break;
}}
}
else
{
printf("All partitions are filled\n");
exit(0);
}
if(flag==0)
printf("This job cannot be executed, Job size exceeds the partition size.\n");
printf("enter your choice(y or n):");
fflush(stdin);

Page No 19 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

ch=getchar();
if(ch=='y')
continue;
else
break;
} }

SAMPLE DATA:
** MULTI PROGRAMMING WITH VARIABLE TASKS **
Enter the number of partitions: 4
Enter Partition: 1 size: 4
Enter Partition: 2 size: 3
Enter Partition: 3 size: 5
Enter Partition: 4 size: 2
Enter the size of the job that is to be executed: 2
Job is executed.
Memory wastage is: 1
Enter your choice(y/n) : y
Enter the size of the job that is to be executed: 2
Job is executed.
Memory wastage is: 2
Enter your choice (y/n) : n

// BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE //

Description: 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.

Page No 20 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

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.

Program:
#include<stdio.h>
#include<conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n,r;
void input();
void show();
void cal();
int main()
{
int i,j;
printf("********** Baner's Algorithm for Dead lock Avoidance ************\n");
input();
show();
cal();
getch();
return 0;
}
void input()
{
int i,j;
printf("Enter the no of Processes::\t");
scanf("%d",&n);

Page No 21 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

printf("Enter the no of Resources::\t");


scanf("%d",&r);
printf("Enter the Max Matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&max[i][j]);
}
}
printf("Enter the Allocation Matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&alloc[i][j]);
}
}
printf("Enter the available Resources\n");
for(j=0;j<r;j++)
{
scanf("%d",&avail[j]);
}
}
void show()
{
int i,j;
printf("Process\t Allocation\t Max\t Available\t");
for(i=0;i<n;i++)
{
printf("\nP%d\t ",i+1);

Page No 22 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

for(j=0;j<r;j++)
{
printf("%d ",alloc[i][j]);
}
printf("\t");
for(j=0;j<r;j++)
{
printf("%d ",max[i][j]);
}
printf("\t");
if(i==0)
{
for(j=0;j<r;j++)
printf("%d ",avail[j]);
}
}
}
void cal()
{
int finish[100],temp,need[100][100],flag=1,k,c1=0;
int safe[100];
int i,j;
for(i=0;i<n;i++)
{
finish[i]=0;
}
//find need matrix
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{

Page No 23 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

need[i][j]=max[i][j]-alloc[i][j];
}
}
printf("\n");
while(flag)
{
flag=0;
for(i=0;i<n;i++)
{
int c=0;
for(j=0;j<r;j++)
{
if((finish[i]==0)&&(need[i][j]<=avail[j]))
{
c++;
if(c==r)
{
for(k=0;k<r;k++)
{
avail[k]+=alloc[i][j];
finish[i]=1;
flag=1;
}
printf("P%d->",i);
if(finish[i]==1)
{
i=n;
}
}
}
}

Page No 24 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

}
}
for(i=0;i<n;i++)
{
if(finish[i]==1)
{
c1++;
}
else
{
printf("P%d->",i);
}
}
if(c1==n)
{
printf("\n The system is in safe state");
}
else
{
printf("\n Process are in dead lock");
printf("\n System is in unsafe state");
}
}

SAMPLE DATA:
********** Baner's Algorithm for Dead lock Avoidance ************
Enter the no of Processes:: 5

Page No 25 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Enter the no of Resources:: 3


Enter the Max Matrix
7 5 3
3 2 2
9 0 2
2 2 2
4 3 3
Enter the Allocaton Matrx
0 1 0
2 0 0
3 0 2
2 1 1
0 0 2
Enter the available Resources
3 2 2
Processes Allocation Max Available
P1 0 1 0 7 5 3 3 2 2
P2 2 0 0 3 2 2
P3 3 0 2 9 0 2
P4 2 1 1 2 2 2
P5 0 0 2 4 3 3
P2 P4 P5 P3 P1
The system is in safe state

// BANKERS ALGORITHM FOR DEAD LOCK PREVENTION //

Description: Deadlock Prevention algorithms are used in concurrent programming when multiple
processes must acquire more than one shared resource. If two or more concurrent processes obtain
multiple resources indiscriminately, a situation can occur where each process has a resource needed
by another process.

Page No 26 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

We can prevent Deadlock by eliminating any of the four condition.


 Mutual Exclusion
 Hold and Wait
 No Preemption
 Circular Wait
Program:
#include< stdio.h>
#include< conio.h>
void main()
{
int allocated[15][15],max[15][15],need[15][15],avail[15],tres[15],work[15],flag[15];
int pno,rno,i,j,prc,count,t,total;
count=0;
clrscr();
printf("\n Enter number of process:");
scanf("%d",&pno);
printf("\n Enter number of resources:");
scanf("%d",&rno);
for(i=1;i< =pno;i++)
{
flag[i]=0;
}
printf("\n Enter total numbers of each resources:");
for(i=1;i<= rno;i++)
scanf("%d",&tres[i]);
printf("\n Enter Max resources for each process:");
for(i=1;i<= pno;i++)
{
printf("\n for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&max[i][j]);

Page No 27 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

}
printf("\n Enter allocated resources for each process:");
for(i=1;i<= pno;i++)
{
printf("\n for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&allocated[i][j]);
}
printf("\n available resources:\n");
for(j=1;j<= rno;j++)
{
avail[j]=0;
total=0;
for(i=1;i<= pno;i++)
{
total+=allocated[i][j];
}
avail[j]=tres[j]-total;
work[j]=avail[j];
printf(" %d \t",work[j]);
}
do
{
for(i=1;i<= pno;i++)
{
for(j=1;j<= rno;j++)
{
need[i][j]=max[i][j]-allocated[i][j];
}
}

Page No 28 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

printf("\n Allocated matrix Max need");


for(i=1;i<= pno;i++)
{
printf("\n");
for(j=1;j<= rno;j++)
{
printf("%4d",allocated[i][j]);
}
printf("|");
for(j=1;j<= rno;j++)
{
printf("%4d",max[i][j]);
}
printf("|");
for(j=1;j<= rno;j++)
{
printf("%4d",need[i][j]);
}
}
prc=0;
for(i=1;i<= pno;i++)
{
if(flag[i]==0)
{
prc=i;
for(j=1;j<= rno;j++)
{
if(work[j]< need[i][j])
{
prc=0;
break;
}
}

Page No 29 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

}
if(prc!=0)
break;
}
if(prc!=0)
{
printf("\n Process %d completed",i);
count++;
printf("\n Available matrix:");
for(j=1;j<= rno;j++)
{
work[j]+=allocated[prc][j];
allocated[prc][j]=0;
max[prc][j]=0;
flag[prc]=1;
printf(" %d",work[j]);
}
}
}while(count!=pno&&prc!=0);
if(count==pno)
printf("\nThe system is in a safe state!!");
else
printf("\nThe system is in an unsafe state!!");
getch();
}
SAMPLE DATA:
Enter number of process:5
Enter number of resources:3
Enter total numbers of each resources:10 5 7
Enter Max resources for each process:
for process 1:7 5 3
for process 2:3 2 2

Page No 30 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

for process 3:9 0 2


for process 4:2 2 2
for process 5:4 3 3
Enter allocated resources for each process:
for process 1:0 1 0
for process 2:3 0 2
for process 3:3 0 2
for process 4:2 1 1
for process 5:0 0 2
available resources:
2 3 0
Allocated matrix Max need
0 1 0| 7 5 3| 7 4 3
3 0 2| 3 2 2| 0 2 0
3 0 2| 9 0 2| 6 0 0
2 1 1| 2 2 2| 0 1 1
0 0 2| 4 3 3| 4 3 1
Process 2 completed
Available matrix: 5 3 2
Allocated matrix Max need
0 1 0| 7 5 3| 7 4 3
0 0 0| 0 0 0| 0 0 0
3 0 2| 9 0 2| 6 0 0
2 1 1| 2 2 2| 0 1 1
0 0 2| 4 3 3| 4 3 1
Process 4 completed
Available matrix: 7 4 3
Allocated matrix Max need
0 1 0| 7 5 3| 7 4 3
0 0 0| 0 0 0| 0 0 0
3 0 2| 9 0 2| 6 0 0
0 0 0| 0 0 0| 0 0 0

Page No 31 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

0 0 2| 4 3 3| 4 3 1
Process 1 completed
Available matrix: 7 5 3
Allocated matrix Max need
0 0 0| 0 0 0| 0 0 0
0 0 0| 0 0 0| 0 0 0
3 0 2| 9 0 2| 6 0 0
0 0 0| 0 0 0| 0 0 0
0 0 2| 4 3 3| 4 3 1
Process 3 completed
Available matrix: 10 5 5
Allocated matrix Max need
0 0 0| 0 0 0| 0 0 0
0 0 0| 0 0 0| 0 0 0
0 0 0| 0 0 0| 0 0 0
0 0 0| 0 0 0| 0 0 0
0 0 2| 4 3 3| 4 3 1
Process 5 completed
Available matrix: 10 5 7
The system is in a safe state!!

// PROGRAM TO IMPLEMENT FIFO //

Description : The policy treats the page frame to allocate a process as a circular buffer and pages
are removed in round robin style. A pointer is required that circles through the page frames of the
process. The page that falls out of use is the one that was fetched long time back. the regions of
program or data that are used throughout the life of a program will be paged in and out by the FIFO
algorithm. The no. of page replacements with this example are six.

Page No 32 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Program :
#include<stdio.h>
#include<conio.h>
int list[25],i,n,page_fal=0;
void fifo()
{
int fr,temp[10],j=0,k,flag;
printf("Enter the number of frames:\n");
scanf("%d",&fr);
for(i=0;i<fr;i++)
temp[i]=0;
printf("\n");
for(i=0;i<n-1;i++)
printf("%d\t",list[i]);
for(i=0;i<n-1;i++)
{
flag=0;
for(k=0;k<fr;k++)
{
if(temp[k]==list[i])
flag=1;
}
if(!flag)
{
temp[j]=list[i];
j++;
page_fal++;
}
if(j==fr)
j=0;

Page No 33 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

printf("\n");
for(k=0;k<fr;k++)
printf("%d ",temp[k]);
if(!flag)
printf("F");
}
printf("\nNumber of page faults:%d",page_fal);
getch();
}
void main()
{
i=0;
clrscr();
printf("\nEnter the list:");
printf("\nEnter '-1' to end the list");
do
{
scanf("%d",&list[i]);
i++;
}while(list[i-1]!=-1);
n=i;
fifo();
}

SAMPLE DATA :
Enter the list:
Enter '-1' to end the list
1
2
3

Page No 34 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

4
2
1
3
4
5
-1
Enter the number of frames: 4

1 2 3 4 2 1 3 4 5
1 0 0 0 F
1 2 0 0 F
1 2 3 0 F
1 2 3 4 F
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
5 2 3 4 F
Number of page faults: 5

// PROGRAM TO IMPLEMENT LRU //

Description: The policy replaces the page in memory that has not been referenced for the longest
time. The approach used to implement this policy is to tag each page with the time of its last
reference for each reference. There would be tremendous overhead as one could maintain the page
references.

Page No 35 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Program:
#include<stdio.h>
int pages[20],frames[5],n,last=0,p,f=0,s=0;

void main()
{
int i,j;
void push(int);
clrscr();
printf("Enter the number of frames:");
scanf("%d",&n);
printf("Enter the pages(Enter -1 to terminate):");
for(i=0; ;i++)
{
scanf("%d",&pages[i]);
if(pages[i]==-1)
break;
}
for(j=0;j<n;j++)
frames[j]=0;
for(j=0;j<i;j++)
{

printf("\n\t");
push(j);
}
printf("\n\n\t PAGE SUCCESSES:: %d PAGE FAULTS ::%d",s,f);
getch();
}
void push(int i)
{

Page No 36 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

void pop(void);
int k,j,temp;
k=check(i);
if(k!=1)
{
if(last!=n)
frames[last++]=pages[i];
else
{
pop();
frames[n-1]=pages[i];
}
printf("F");
f++;
for(j=0;j<n;j++)
printf("%5d",frames[j]);
}
else
{
printf("S");
s++;
for(k=0;k<n;k++)
if(frames[k]==pages[i])
{
temp=frames[k];
break;
}
for(j=k;j<n-1;j++)
frames[j]=frames[j+1];
frames[n-1]=temp;
for(j=0;j<n;j++)

Page No 37 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

printf("%5d",frames[j]);
}
}
void pop()
{
int i,j;
for(i=0,j=1;j<n;i++,j++)
frames[i]=frames[j];
}
int check(int d)
{
int j,k=0;
for(j=0;j<n;j++)
if(pages[d]==frames[j])
{
k=1;
break;
}
return(k);
}

SAMPLE DATA :

Enter the number of frames:4


Enter the pages(Enter -1 to terminate):
1
2

Page No 38 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

3
4
1
3
2
5
1
-1
F 1 0 0 0
F 1 2 0 0
F 1 2 3 0
F 1 2 3 4
S 2 3 4 1
S 2 4 1 3
S 4 1 3 2
F 1 3 2 5
S 3 2 5 1

PAGE SUCCESSES:: 4 PAGE FAULTS ::5

// PROGRAM TO IMPLEMENT LFU //

Description : The least frequently used page replacement algorithm requires that the page with the
smallest count be replaced.
The reason for the section is that an actively used page should have a large reference count.
A problem arises however when a page is used heavily during the initial phase of a process but then
is never used again. since it was used heavily it has a large count and remains in memory even

Page No 39 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

though it has no longer needed.

Program:
#include<stdio.h>
#include<conio.h>
struct frame
{
int value;
int freq;
int pos;
}f[30];
int no_frame,no_page,page_seq[100],page_fault=0;
void input()
{
int i;
printf("\n\n\tLeast Frequently Used\n");
printf("\nEnter the number of frames:");
scanf("%d",&no_frame);
printf("\nEnter the number of pages:");
scanf("%d",&no_page);
printf("Enter the page sequence:");
for(i=0;i<no_page;i++)
scanf("%d",&page_seq[i]);
printf("\n");
for(i=0;i<no_frame;i++)
{
f[i].pos = -1;
f[i].value =-1;
f[i].freq = 0;
}
}

Page No 40 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

void display()
{
static int prev_page_fault = 0;
int i;
for(i=0;i<no_frame;i++)
{
if(f[i].value == -1)
{
printf("0 ");
}
else
printf("%d ",f[i].value);
}
if(prev_page_fault != page_fault)
{
printf("F");
prev_page_fault = page_fault;
}
printf("\n");
}

int search(int i)
{
int j;
for(j=0;j<no_frame;j++)
{
if(f[j].value == page_seq[i])
return j;
}
return -1;
}
int position()
{

Page No 41 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

int i,j=0,k;
for(i=0;i<no_frame;i++)
{
if(f[i].pos == -1)
return i;
}
for(i=0;i<no_frame;i++)
{
if(f[j].freq > f[i].freq)
{
j = i;
}
}
k = j;
for(i=0;i<no_frame;i++)
{
if(f[j].freq == f[i].freq && j != i)
{
if(f[j].pos > f[i].pos)
j = i;
}
}
k = j;
return k;
}

void lfu()
{
int i,k;
input();
for(i=0;i<no_page;i++)
{
k = search(i);
if(k != -1)
{
f[k].freq++;

Page No 42 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

f[k].pos = i;
}
if(k == -1)
{
k = position();
f[k].pos = i;
f[k].value = page_seq[i];
f[k].freq = 1;
page_fault++;
}
display();
}
}
void main()
{
lfu();
printf("\nNumber of page faults:%d",page_fault);
getch();
}

SAMPLE DATA :
Enter the no. of frames: 3
Enter the no. of pages: 5
Enter the page sequence:
1
2

Page No 43 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

3
1
5

1 0 0
1 2 0
1 2 3
1 2 3
1 5 3

No. of page faults: 1

// PROGRAM TO IMPLEMENT SEQUENTIAL FILE ALLOCATION STRATAGY //

Description: A file is a collection of data, usually stored on disk. As a logical entity, a file enables
to divide data into meaningful groups. As a physical entity, a file should be considered in terms of
its organization. The term "file organization" refers to the way in which data is stored in a file and,
consequently, the method(s) by which it can be accessed.
Sequential File Allocation:

Page No 44 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

In this file organization, the records of the file are stored one after another both physically
and logically. That is, record with sequence number 8 th is located just after the 9th record. A record
of a sequential file can only be accessed by reading all the previous records.

Program:

#include<stdio.h>
#include<conio.h>
struct fileTable
{
char name[20];
int sb, nob;
}ft[30];
void main()
{
int i, j, n;
char s[20];
clrscr();
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter file name %d :",i+1);
scanf("%s",ft[i].name);
printf("Enter starting block of file %d :",i+1);

scanf("%d",&ft[i].sb);
printf("Enter no of blocks in file %d :",i+1);
scanf("%d",&ft[i].nob);
}
printf("\nEnter the file name to be searched: ");
scanf("%s",s);

Page No 45 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

for(i=0;i<n;i++)
if(strcmp(s, ft[i].name)==0)
break;
if(i==n)
printf("\nFile Not Found");
else
{
printf("\nFILE NAME START BLOCK NO OF BLOCKS BLOCKS OCCUPIED\n");
printf("\n%s\t\t%d\t\t%d\t",ft[i].name,ft[i].sb,ft[i].nob);
for(j=0;j<ft[i].nob;j++)
printf("%d, ",ft[i].sb+j);
}
getch();
}

SAMPLE DATA:

Enter no of files :3
Enter file name 1 :A
Enter starting block of file 1 :85
Enter no of blocks in file 1 :6
Enter file name 2 :B

Page No 46 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Enter starting block of file 2 :102


Enter no of blocks in file 2 :4
Enter file name 3 :C
Enter starting block of file 3 :60
Enter no of blocks in file 3 :4
Enter the file name to be searched: B

FILE NAME START BLOCK NO OF BLOCKS BLOCKS OCCUPIED


B 102 4 102, 103, 104, 105

// PROGRAM TO IMPLEMENT LINKED FILE ALLOCATION STRATAGY //

Linked File Allocation

With linked allocation, each file is a linked list of disk blocks; the disk blocks may be
scattered anywhere on the disk. The directory contains a pointer to the first and last blocks of the
file. Each block contains a pointer to the next block.

Program:

Page No 47 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

#include<stdio.h>
#include<conio.h>
struct fileTable
{
char name[20];
int nob;
struct block *sb;
}ft[30];
struct block
{
int bno;
struct block *next;
};
void main()
{
int i, j, n;
char s[20];
struct block *temp;
clrscr();
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter file name %d :",i+1);
scanf("%s",ft[i].name);
printf("Enter no of blocks in file %d :",i+1);
scanf("%d",&ft[i].nob);
ft[i].sb=(struct block*)malloc(sizeof(struct block));
temp = ft[i].sb;
printf("Enter the blocks of the file :");
scanf("%d",&temp->bno);
temp->next=NULL;
for(j=1;j<ft[i].nob;j++)
{

Page No 48 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

temp->next = (struct block*)malloc(sizeof(struct block));


temp = temp->next;
scanf("%d",&temp->bno);
}
temp->next = NULL;
}
printf("\nEnter the file name to be searched -- ");
scanf("%s",s);
for(i=0;i<n;i++)
if(strcmp(s, ft[i].name)==0)
break;
if(i==n)
printf("\nFile Not Found");
else
{
printf("\nFILE NAME NO OF BLOCKS BLOCKS OCCUPIED");
printf("\n %s\t\t%d\t",ft[i].name,ft[i].nob);
temp=ft[i].sb;
for(j=0;j<ft[i].nob;j++)
{
printf("%d  ",temp->bno);
temp = temp->next;
}
}
getch();
}

SAMPLE DATA:

Enter no of files : 2
Enter file 1 : A
Enter no of blocks in file 1 : 4
Enter the blocks of the file 1 : 12 23 9 4
Enter file 2 : B

Page No 49 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Enter no of blocks in file 2 : 5


Enter the blocks of the file 2 : 88 77 66 55 44
Enter the file to be searched : B

FILE NAME NO OF BLOCKS BLOCKS OCCUPIED


B 5 88  77  66  55  44

// PROGRAM TO IMPLEMENT INDEXED FILE ALLOCATION STRATAGY //

Indexed File Allocation


Indexed file allocation strategy brings all the pointers together into one location: an index
block. Each file has its own index block, which is an array of disk-block addresses. The i th entry in
the index block points to the ith block of the file. The directory contains the address of the index
block. To find and read the ith block, the pointer in the ith index-block entry is used.

Program:

Page No 50 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

#include<stdio.h>
#include<conio.h>
struct fileTable
{
char name[20];
int nob, blocks[30];
}ft[30];
void main()
{
int i, j, n;
char s[20];
clrscr();
printf("Enter no of files :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter file name %d :",i+1);
scanf("%s",ft[i].name);
printf("Enter no of blocks in file %d :",i+1);
scanf("%d",&ft[i].nob);
printf("Enter the blocks of the file :");
for(j=0;j<ft[i].nob;j++)
scanf("%d",&ft[i].blocks[j]);
}
printf("\nEnter the file name to be searched-- ");
scanf("%s",s);
for(i=0;i<n;i++)
if(strcmp(s, ft[i].name)==0)
break;
if(i==n)
printf("\nFile Not Found");

Page No 51 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

else
{
printf("\nFILE NAME NO OF BLOCKS BLOCKS OCCUPIED");
printf("\n %s\t\t%d\t",ft[i].name,ft[i].nob);
for(j=0;j<ft[i].nob;j++)
printf("%d, ",ft[i].blocks[j]);
}
getch();
}

SAMPLE DATA:

Enter no of files : 2
Enter file 1: A
Enter no of blocks in the file 1 : 4
Enter the blocks of the file 1 : 12 23 9 4

Page No 52 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Enter file 2: B
Enter no of blocks in the file 2 : 5
Enter the blocks of the file 2 : 72 85 98 54 44
Enter the file to be searched: B

FILE NAME NO OF BLOCKS BLOCKS OCCUPIED


B 5 72  85  98  54  44

Introduction to UNIX File System

What is UNIX?
• A computer operating system.
• It is designed to be used by many people at the same time (multi-user).
• Runs on a variety of processors
• It provides a number of facilities:
– management of hardware resources
– directory and file system

Page No 53 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

– loading / execution / suspension of programs


Why Use UNIX?
• multi-tasking / multi-user
• networking capability
• graphical (with command line)
• easy to program
• portable (PCs, mainframes, super-computers)
File: a container for storing information.
A file is of 3 types.
Ordinary file: It contains data as a stream of characters. It is of 2 types.
• Text file: contains printable characters.
• Binary file: contains both printable & non printable characters.
Directory file: contains no data but it maintains some details of the files & subdirectories that it
contains.
Device file: It represents the device or peripheral.
vi Editor
• vi is a full screen text editor. It was created by Bill Joy.
• Bram Moolenaor improved it and called it vim (vi improved).
• Invoking vi:
$Vi file_name

Modes of operation
• Vi has 3 mode of operation.
1. Command mode: In this mode all the keys pressed by the user are interpreted as
commands. It may perform some actions like move cursor, save, delete text, quit vi, etc.
2. Input/Insert mode: used for inserting text.
– start by typing i ;
– finish with ESC
3. Ex mode or last line mode:
– Used for giving commands at command line.

Page No 54 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

– The bottom line of vi is called the command line.

Text processing utilities


cat: cat is used to create the files.
$cat> filename
Type some text here
Press ctrl+d
$
cat can also be used to display the contents of a file.
$cat filename
cat can also concatenate the contents of 2 files and store them in third file.
$cat>file1 file2>new file
To append the contents of two files into another file use
$cat>file1 file2>>new file
tail:
tail command displays the end of the file. It displays the last ten lines by default.
$tail file
To display last 3 lines use
$tail –n 3 file or
$tail -3 file
We can also address the lines from the beginning of the file instead of the end.
The + count allows to do that.

head:
• head command as the name implies, displays the top of the file. When used without an
option, it displays the first 10 lines of the file.
$head file
• We can use –n option to specify a line count and display, say first 3 lines of the file.
$head –n 3 file or
$head -3 file
sort: Sort can be used for sorting the contents of a file.

Page No 55 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

$sort shortlist
• Sorting starts with the first character of each line and proceeds to the next character only
when the characters in two lines are identical.
Sort options:
• With –t option sorts a file based on the fields.
$sort –t “|” +2 shortlist
• The sort order can be reversed with –r option.
• If the primary key is the third field and the secondary key the second field, we can use
$sort –t \| +2 -3 +1 shortlist
• Numeric sort (-n):
• To sort on number field use sort with –n option.
$sort –t +2 -3 –n group1
• Removing duplicate lines (-u):
• The –u option u purge duplicate lines from a file.
nl: nl is used for numbering lines of a file.
• nl numbers only logical lines –those containing something other apart from the new line
character.
$nl file
• nl uses a tab as a default delimiter, but we can change it with –s option.
$nl –s file
• nl won’t number a line if it contains nothing.

grep: globally search for a regular expression and print.


• grep scans a file for the occurrence of a pattern and depending on the options used, displays
• Lines containing the selected pattern.
• Lines not containing the selected pattern (-v).
• Line numbers where pattern occurs (-n)
• No. of lines containing the pattern (-c)
• File names where pattern occurs (-l)
Syntax: grep option pattern filename(s)
egrep: extended grep

Page No 56 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

egrep extended set includes 2 special characters + and ?.


+ --matches one or more occurrences of the pervious character.
?-- matches zero or more occurrences of the pervious character.
fgrep: fast grep
• If search criteria requires only sequence expressions, fgrep is the best utility.
• Fgrep supports only string patterns, no regular expressions.
• To extract all the lines that contain an apostrophe use fgrep as follows:
$fgrep “’” file
Cut: slitting the file vertically
U can slice a file vertically with cut command.
• Cutting columns(-c):
Cut with –c option cuts the columns.
To extract first 4 columns of the group file :
$cut –c 1-4 group1
The specification –c 1-4 cuts columns 1 to 4.
Cutting fields: To cut 1st and 3rd fields use
$cut –d: -f1,3 group1
Paste: pasting files
• What u cut with the cut can be pasted back with paste command-but vertically rather than
horizontally. u can view two files side by side by pasting them.
• To join two files [Link] and [Link] use
$paste –d= [Link] [Link]

Join:
• is a command in Unix-like operating systems that merges the lines of two sorted text files
based on the presence of a common field.
• The join command takes as input two text files and a number of options. If no command-line
argument is given, this command looks for a pair of lines from the two files having the same
first field (a sequence of characters that are different from space), and outputs a line
composed of the first field followed by the rest of the two lines.
$join file1 file2

Page No 57 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

tee:
Unix tee command breaks up its input into two components; one component is saved in a file, and
other is connected to the standard output.
tee doesn’t perform any filtering action on its input; it gives exactly what it takes.
tee can be placed anywhere in a pipeline.
we can use tee to save the output of the who command in a file and display it as well:
$who |tee [Link]
• The tee command reads standard input, writes its content to standard output and
simultaneously copies it into the specified file or files.
Comm:
• Suppose if u have 2 list of people, u are asked to find out the names available in one and not
the other or even those common to both. Comm is the command that u need to for this work.
• It requires two sorted file and lists the differing entries in different columns.
$comm file1 file2
• Comm display a three-column output.
Cmp: comparing two files
• The two files are compared byte by byte and the location of the first mismatch is echoed to
the screen using cmp.
• Cmp when invoked without options it does not bother about possible subsequent
mismatches.
$cmp group1 group2
If two files are identical cmp display s no message, but simply returns the $ prompt.

diff: converting one file to another


• diff takes different approach to displaying the differences.
• It tells u which lines in one file have to be changed to make two files identical.
• When used with the same files it produces a detailed output.
$diff group[12]
• diff uses certain special symbols with its instructions to indicate the changes needed to make
two files identical.

Page No 58 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

File handling utilities


cp (Copying Files)
– To create an exact copy of a file you can use the “cp” command. The format of this
command is:
Syntax: cp [-option] source destination
Eg:
cp file1 file2
Here file1 is copied to file2.
Eg:
cp file1 file2 dir
File1 file2 are copied to dir.
• Copying Files
cp turns to interactive when –i option is used & destination file also exists.
$cp -i file1 file2
overwrite file2 (yes/no)?
Y at this prompt overwrites the file.

mv (Moving and Renaming Files)


Used to move or rename the files/directories.
Syntax: mv source destination
$mv test sample
Here test is renamed as sample.

ln (link):
• Used to create links (both soft & hard links).
• It creates the alias & increase the link count by one.
Syntax: $ln file1 file2
• ln won’t work if the destination file also exists.

rm (Deleting Files and Directories)


To delete or remove a file, you use the “rm” command. For example,

Page No 59 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Eg: $rm my. listing


will delete “[Link]”.
With –i option removes the files interactively.
$rm –i file1
With –r option recursively removes directories.
$rm –r dir1
mkdir(Make Directory): used to create one or more directories.
Eg: $mkdir book
Creates the directory named book.
Eg: $mkdir dbs doc dmc
Creates three directories.
rmdir (remove directories ):
Removes empty directories.
Eg: $rmdir book
removes directory named book if it is empty.
Eg: $rmdir dbs doc dmc
Removes 3 directories.
find: It recursively examines a directory tree to look for matching some criteria and then takes some
action on the selected files.
Syntax:
$find path_list selection_criteria action
To locate all files named a. out use
Eg: $find / -name a. out –print
• ‘/’ indicates search should start from root directory.
• To locate all c files in current directory
$find . -name “*.c” –print
• To find all files begin with an uppercase letter use
$find . –name ‘[A-Z]*’ –print
chmod: changing file permission
chmod sets a file’s permissions (read, write and execute) for all three categories of
users (owner, group and others)

Page No 60 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

Syntax: chmod category operation permission file(s)


Category operation permissions
u-user + assign permission r-read permission
g-group - remove permission w-write permission
o-others = assigns absolute permission x-execute permission
a-all

Process utilities
ps (process status): Display some process attributes.
• $ps
PID TTY TIME CMD
1078 pts/2 0:00 bash
• Ps presents a snapshot of the process table.
• Ps with –f option displays a fuller listing that includes the PPID.
• Ps with –u option followed by user-id displays the processes owned by the user-id.
• Ps with –e option displays the system processes.
Who: know the users. Displays the users currently logged in the system.
$who
Whoami: Show you the owner of this account
$whoami
W: Tell you who is logging in and doing what!
$w

Finger: Displays the information about the users.


$finger user Find out the personal information of a user
$finger name Try to find the person’s info. by name
• finger email-address
Try to find the person’s info across the network
Disk utilities
• du: disk usage
• du estimate the file space usage on the disk.

Page No 61 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

• It produces a list containing the usage of each subdirectory of its argument and finally
produces a summary.
$du /home/usr1
Mount:
• Used to mount the file systems.
• Takes 2 arguments-device name ,mount point.
• Mount uses an option to specify the type of file system.
• To mount a file system on the /oracle directory on Linux system use
$mount –t ext2 /dev/hda3 /oracle
$mount –t iso9660 /dev/cdrom /mnt /cdrom
$mount –t vfat /dev/hda1 /msdos
$mount –t msdos /dev/fd0 /floppy
Umount: unmounting file systems
• Unmounting is achieved with the umount command. which requires either file system name
or the mount point as argument.
• $umount /oracle
• $umount /dev/hda3
• Unmounting a file system is not possible if the file is opened.

Networking commands
ftp: file transfer protocol
ftp is used to transfer files. It can be used with host name.
$ftp Saturn
Connected to Saturn
220 Saturn ftp server
Name (Saturn: summit ): Henry
Password: ******
To quit ftp use close and then bye or quit.

Page No 62 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

ftp>close
221 good bye
ftp>bye
Transferring files: Files can be of 2 types.
• Uploading( put & mput):
• To upload ur web pages & graphic files to website.
The put command sends a single file to the remote machine.
ftp>binary 200 type set to I
ftp>put [Link]
To copy multiple files use mput.
ftp>mput t*.sql
Downloading files: get & mget
• To download the files from remote machine use get & mget.
ftp>get [Link]
ftp>_

telnet: Remote login


If u have an account on the host in a local network (or on internet ),u can use this
with the host name or the ip address as argument.

$telnet Saturn
Trying to [Link]…
Connected to Saturn
• Login:----
• Password:-----
• To quit telnet by using exit command.
• telnet prompt:
rlogin: remote login without password

Page No 63 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

• rlogin is the Berkley's implementation of the remote login facility.


• To log on to your own identical remote account without using either the user name or
password.
• $rlogin Jupiter
• Last login :….
• rlogin is terminated with ctrl+d or exit or logout.

Backup utilities
tar: the tape archive program
• Tar doesn’t normally write to the standard output but creates an archive in the media.
• Tar accepts file and directory names as arguments.
• It operates recursively.
• It can create several versions of same file in a single archive.
• It can append to an archive without overwriting the entire archive.
• -c option is used to copy files to backup device.
$tar –cvf /dev/rdsk/foq18dt /home/sales/sql/*.sql
• The verbose option (-v) shows the no. of blocks used by each file.
• Files are restored with the –x (extract) key option. when no file or directory name is
specified it restores all files from the backup device.
Awk: Aho, Weinberger and Kernighan
• Awk is not just a command, but a programming language too.
Syntax: awk options ‘selection criteria {action}’ file(s)
• Simple filtering
$ awk ‘/Simpsons/ { print }’ homer |Simpsons
• Splitting a line into fields
$ awk –F ”|” ‘/Simpsons/ {print $1}’ homer
tr: translating characters
• tr command manipulates individual characters in a character stream.
tr options expr1 expr2< standard input
It takes input only from the standard input, it does not take input a file name as its argument.
Examples:

Page No 64 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

$ tr "[a-z]" "z[a-y]" < [Link]


$tr –d ‘|/’ <shortlist | head -3
pg:
• pg is used to display the output of a file in page by page.
$pg file1

When a single command is not sufficient to solve a problem, try to join the commands together.
Two approaches for this are:
• Redirection
• Piping
Redirection:
• Unix commands are built-up in such a way that they can take the input from the keyboard,
often called standard input and usually send their output to the screen, often called standard
output. Commands also send error information to the screen.

We can also change these defaults by using a process called redirection.

// COPY OF A FILE USING STANDARD I/O, AND SYSTEM CALLS//

Program:
#include <unistd.h>
#include <fcntl.h>
int main(int argc, char *argv[]){
int fd1, fd2;
char buffer[100];
long int n1;

Page No 65 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

if(((fd1 = open(argv[1], O_RDONLY)) == -1) ||


((fd2 = open(argv[2], O_CREAT|O_WRONLY|O_TRUNC,
0700)) == -1)){
perror("file problem ");
exit(1);
}
while((n1=read(fd1, buffer, 100)) > 0)
if(write(fd2, buffer, n1) != n1){
perror("writing problem ");
exit(3);
}
// Case of an error exit from the loop
if(n1 == -1){
perror("Reading problem ");
exit(2);
}
close(fd2);
exit(0);
}

// TO EMULATE THE UNIX ls –l COMMAND//


Program:
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/stat.h>
main()
{
char dirname[10];
DIR *p;

Page No 66 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

struct dirent *d;


printf("Enter directory name ");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
{
perror("Cannot find dir.");
exit(-1);
}
while(d=readdir(p))
printf("%s\n",d->d_name);
}

// TO EXECUTE TWO COMMANDS CONCURRENTLY WITH A COMMAND PIPE.


EX:- LS –L | SORT

Program:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{

Page No 67 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

int pfds[2];
char buf[30];
if(pipe(pfds)==-1)
{
perror("pipe failed");
exit(1);
}
if(!fork())
{
close(1);
dup(pfds[1];
system (“ls –l”);
}
else
{
printf("parent reading from pipe \n");
while(read(pfds[0],buf,80))
printf("%s \n" ,buf);
}
}

SAMPLE DATA:
$ vi pipes2.c
$ cc pipes2.c
$ ./[Link]
Parent reading from pipe
Total 2
-rwxrwxr-x l student student 5563Aug 3 10:39 [Link]
-rw-rw-r-- l student student 340 jul 27 10:45 pipe2.c

Page No 68 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

// TWO PROCESSES COMMUNICATING USING SHARED MEMORY//

Program:
#include<stdio.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<string.h>
#include<sys/shm.h>
#define shm_size 1024
int main(int argc,char * argv[])
{
key_t key;
int shmid;
char *data;
int mode;

Page No 69 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

if(argc>2)
{
fprintf(stderr,”usage:stdemo[data_to_writte]\n”);
exit(1);
}
if((shmid=shmget(key,shm_size,0644/ipc_creat))==-1)
{
perror(“shmget”);
exit(1);
}
data=shmat(shmid,(void *)0,0);
if(data==(char *)(-1))
{
perror(“shmat”);
exit(1);
}
if(argc==2)
printf(writing to segment:\”%s”\”\n”,data);
if(shmdt(data)==-1)
{
perror(“shmdt”);
exit(1);
}
return 0;
}
SAMPLE DATA:
$ ./[Link] GEC
Writing to segment GEC

// SIMULATE PRODUCER-CONSUMER PROBLEM USING SEMAPHORES


Description:
Producer-consumer problem is a common paradigm for cooperating processes. A producer
process produces information that is consumed by a consumer process. One solution to the
producer-consumer problem uses shared memory.
To allow producer and consumer processes to run concurrently, there must be available a
buffer of items that can be filled by the producer and emptied by the consumer. This buffer will
reside in a region of memory that is shared by the producer and consumer processes.
A producer can produce one item while the consumer is consuming another item. The
producer and consumer must be synchronized, so that the consumer does not try to consume an item
that has not yet been produced.

Program:
#include<stdio.h>
void main()

Page No 70 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

{
int buffer[10], bufsize, in, out, produce, consume, choice=0;
in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf("\n 1. Produce \t 2. Consume \t3. Exit");
printf("\n Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1: if((in+1)%bufsize==out)
printf("\n Buffer is Full");
else
{
printf("\nEnter the value: ");
scanf("%d", &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
break;
case 2: if(in == out)
printf("\nBuffer is Empty");
else
{
consume = buffer[out];
printf("\nThe consumed value is %d", consume);
out = (out+1)%bufsize;
}
break;
}}}

SAMPLE DATA:
1. Produce 2. Consume 3. Exit
Enter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. Exit
Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit
Enter your choice: 2
The consumed value is 100

Page No 71 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

1. Produce 2. Consume 3. Exit


Enter your choice: 3

2nd one:
1. Produce 2. Consume 3. Exit
Enter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. Exit
Enter your choice: 1
Enter the value: 300

Enter your choice: 2


The consumed value is 100
1. Produce 2. Consume 3. Exit
Enter your choice: 2
The consumed value is 300

Enter your choice: 3

// TO CREATE A THREAD USING PTHREADS LIBRARY & RUN ITS FUNCTION //


Program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

// Let us create a global variable to change it in threads


int g = 0;

// The function to be executed by all threads


void *myThreadFun(void *vargp)
{
// Store the value argument passed to this thread

Page No 72 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

int *myid = (int *)vargp;

// Let us create a static variable to observe its changes


static int s = 0;

// Change static and global variables


++s; ++g;

// Print the argument, static and global variables


printf("Thread ID: %d, Static: %d, Global: %d\n", *myid, ++s, ++g);
}

int main()
{
int i;
pthread_t tid;

// Let us create three threads


for (i = 0; i < 3; i++)
pthread_create(&tid, NULL, myThreadFun, (void *)&tid);

pthread_exit(NULL);
return 0;
}

SAMPLE DATA:
$ cc multithread.c -lpthread
$ ./[Link]
Thread ID: 3, Static: 2, Global: 2
Thread ID: 3, Static: 4, Global: 4
Thread ID: 3, Static: 6, Global: 6

Page No 73 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

// CONCURRENT EXECUTION OF THREADS USING PTHREADS LIBRARY //


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");

Page No 74 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

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); }

SAMPLE DATA:

$ cc w8.c – l pthread
$./[Link]
thread1
i=1
i=2;
i=3
thread2
j=1

Page No 75 GIET ENGINEERING COLLEGE


OPERATING SYSTEM & LINUX PROGRAMMING LAB

j=2
j=3
j=4
j=5
j=6
j=7
j=8
i=4
i=5
i=6
i=7
i=8
i=9
i=10
exit from thread1
j=9
j=10
exit from thread2

Page No 76 GIET ENGINEERING COLLEGE

You might also like