Oslp r16 Labmanual Final
Oslp r16 Labmanual Final
LABORATORY MANUAL
FOR
Institute Vision:
To emerge as an acclaimed centre of learning that provides value-based technical education for the
holistic development of students
Institute Mission:
• Undertake activities that provide value-based knowledge in Science, Engineering, and technology
Department Vision:
To evolve into a Centre of learning that imparts quality education in Computer Science and
Engineering to produce highly competent professionals.
Department Mission:
Impart computing and technical skills with an emphasis on professional competency and human
values.
Enrich the learning aptitude to face the dynamic environment of the Computer Industry.
Enhance the analytical and problem-solving capability through contests and technical
seminars.
GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING FOR WOMEN
(Approved by AICTE New Delhi & Affiliated to JNTUK, Kakinada)
Course Outcomes
Software Requirements:
Extra Programs
1. Simulate Paging Technique of memory management.
2. Simulate Single level directory File Organization Technique.
3. Write a shell script to check whether the file is regular file, directory file or block
special file.
4. Write a shell script to find the sum of ‘n’ numbers using while loop.
5. Write a shell script to print 0 to 9 numbers using until.
6. Write a shell script to find the factorial of a given number using while loop.
7. Write a shell script to execute unix command using switch,break,continue.
8. Write a shell script that accepts a list of file names as its arguments, counts and report
the occurrence of each word that is present in the first argument file on other argument
file.
GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING FOR WOMEN
(Approved by AICTE New Delhi & Affiliated to JNTUK, Kakinada)
LAB RUBRICS
Internals Category Points
Attended and Attended and Attended but Not attended
Attendance completed on partially completed in but completed
(1) the same day completed on the extra lab in the extra lab
the same day
Complete Partial Most of the Complete
understanding understanding experiment misunderstandi
Understanding of
of the of the misunderstood ng of the
the Experiment
experiment experiment experiment
(2)
with learning with learning
objectives objectives
Day to Day
Complete Complete Complete Complete
Performance
implementation implementation implementation implementation
Implementation
with result with result with result with result
with result analysis
analysis and analysis only analysis and analysis only in
(5)
interpretation interpretation extra lab
in extra lab
Submission of Submission of Submission of Submission of
Observation the observation the observation the observation the observation
submission on time on time almost on time immediately after the extra
(2) after the extra lab
lab
Write all the Write all the Some elements Some elements
Comprehensiveness elements of the elements of the are missing but are missing and
& Legible experiments experiments presented poor
(3) which can be with poor clearly handwriting
easily readable handwriting
Record
Submission of Submission of Submission of Submission of
the record on the record the record the record after
Timely Submission
time almost on time immediately the extra lab
(2)
after the extra
lab
GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING FOR WOMEN
(Approved by AICTE New Delhi & Affiliated to JNTUK, Kakinada)
INDEX
SNO NAME OF THE EXPERIMENT PAGE NO.
OPERATING SYSTEMS
1. Simulate the following CPU scheduling algorithms 1
a) Round Robin b) SJF c) FCFS d) Priority
Multiprogramming-Memory management- Implementation of fork (), wait
2. (),exec() and exit (), System calls 9
Simulate the following
a) Multiprogramming with a fixed number of tasks (MFT)
3. b) Multiprogramming with a variable number of tasks (MVT) 12
4. Simulate Bankers Algorithm for Dead Lock Avoidance 17
5. Simulate Bankers Algorithm for Dead Lock Prevention 21
Simulate the following page replacement algorithms.
6. a) FIFO b) LRU c) LFU 26
Simulate the following File allocation strategies
7. a) Sequenced b) Indexed c) Linked 35
LINUX PROGRAMMING
1. Execute different Linux commands 42
Write a C program that makes a copy of a file using standard I/O, and system
2. calls. 54
3. Write a C program to emulate the UNIX ls –l command. 55
Write a C program that illustrates how to execute two commands
concurrently with a command pipe.
4. Ex: - ls –l | sort 56
Write a C program that illustrates two processes communicating using shared
5. memory. 58
Write a C program to simulate producer and consumer problem using
6. semaphores 61
Write C program to create a thread using pthreads library and let it run its
7. function 63
Write a C program to illustrate concurrent execution of threads using pthreads
8. library 64
OS& LINUX EXTRA PROGRAMS
1. Simulate Paging Technique of memory management. 66
2. Simulate Single level directory File Organization Technique. 67
3. write a shell script to check whether the file is regular file, directory file or 68
block special file
4. Write a shell script to find the sum of ‘n’ numbers using while loop 69
5. Write a shell script to print 0 to 9 numbers using until 69
6. write a shell script to find the factorial of a given number using while loop 70
7. Write a shell script to execute unix command using switch,break,continue 70
8. Write a shell script that accepts a list of file names as its arguments, counts and 71
report the occurrence of each word that is present in the first argument file on
other argument file
Operating Systems And Linux Programming Lab
OPERATING SYSTEMS
a)Round Robin
Theory
• Once a process is executed for a given time period, it is pre-empted and other
process executes for a given time period.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int bt[30],wt[30],tat[30],temp[10],p[20],i,t;
int n,x=0,sum=0,twt=0,ttat=0,z[30],j=0;
float awt=0.0,atat=0.0;
char pn[10][10],s[10];
clrscr();
printf("\n Enter no. of Processes ::");
scanf("%d",&n);
printf("\n Enter time slice ::");
scanf("%d",&t);
for(i=0;i<n;i++)
{
printf("\nEnter the process %d name ::",i+1);
scanf("%s",&pn[i]);
printf("Enter the Burst time for process %d::",i+1);
scanf("%d",&bt[i]);
p[i]=0;
temp[i]=bt[i];
sum=sum+bt[i];
}
while(sum!=x)
{
for(i=0;i<n;i++)
{
if(bt[i]!=0)
{
if(bt[i]>t)
{
bt[i]=bt[i]-t;
x=x+t;
z[j]=x;
j++;
p[i]++;
}
else
{
wt[i]=x-(p[i]*t);
x=x+bt[i];
z[j]=x;
j++;
bt[i]=0;
}
}
}
}
printf("\n\n \n");
printf("\n\tPname\tBT(ms)\tWT(ms)\tTAT(ms)\n");
printf("\n \n");
for(i=0;i<n;i++)
{
tat[i]=wt[i]+temp[i];
}
for(i=0;i<n;i++)
{
twt+=wt[i];
ttat+=tat[i];
printf("\n\t%s\t%3d\t%3d\t%3d\n",pn[i],temp[i],wt[i],tat[i]);
}
printf("\n \n");
awt=(float)twt/(float)n;
atat=(float)ttat/(float)n;
printf("\n\nGantt Chart ::\n\n");
printf("\t0");
for(i=0;i<j;i++)
printf("%4d",z[i]);
printf("\n\n Total waiting time is ::%dms",twt);
Theory
• Easy to implement in Batch systems where required CPU time is known in advance.
• The processer should know in advance how much time process will take.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,bt[10],n,twt=0,temp1,z[20],p[10],ttat=0;
int wt[10],tat[10],sum=0,sum1=0;
float avgt=0.0,atat=0.0;
clrscr();
printf("\n Enter no. of Processes :");
scanf("%d",&n);
printf(" Enter the %d burst times.\n",n);
for(i=0;i<n;i++)
{
printf(" Enter Burst time for process-%d :",i+1);
scanf("%d",&bt[i]);
p[i]=i+1;
}
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
{
if(bt[i]>bt[j])
{
temp1=bt[i];
bt[i]=bt[j];
bt[j]=temp1;
temp1=p[i];
p[i]=p[j];
p[j]=temp1;
}
}
}
for(i=0;i<n;i++)
{
if(i==0)
{
wt[i]=0;
sum=sum+bt[i];
}
else
{
wt[i]=sum;
sum=sum+bt[i];
}
tat[i]=wt[i]+bt[i];
sum1=sum1+bt[i];
z[i]=sum1;
}
{
twt+=wt[i];
ttat+=tat[i];
printf("\n\tP%d\t%d\t%d\t%d\n",p[i],bt[i],wt[i],tat[i]);
}
printf("\n \n");
avgt=(float)twt/(float)n;
atat=(float)ttat/(float)n;
printf("\n\nGantt Chart ::\n\n");
printf("\t0");
for(i=0;i<=j-1;i++)
printf("%4d",z[i]);
printf("\n\n Total waiting time is ::%d",twt);
printf("\n\n Average waiting time is ::%f",avgt);
printf("\n\n Total Turn Around time is ::%d",ttat);
printf("\n\n Average Turn Around time is ::%f",atat);
getch();
}
Output:
Theory
Program
#include<stdio.h>
void main()
{
int i,n,sum,wt,tat,twt,ttat;
int t[10];
char pn[10][10];
float awt,atat;
clrscr();
printf("Enter number of processes:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
flushall();
printf("\nEnter the Process Name :");
gets(pn[i]);
printf("Enter the Burst Time of Process-%s :",pn[i]);
scanf("%d",&t[i]);
}
printf("\n FIRST COME FIRST SERVE SCHEDULING ALGORITHM \n");
printf(" ");
printf("\n Process \t WaitingTime(ms)\tTurnAroundTime(ms)\n\n");
printf(" %s \t\t 0 \t\t\t%d \n",pn[0],t[0]);
sum=0;
twt=0;
ttat=t[0];
for(i=1;i<n;i++)
{
sum+=t[i-1];
wt=sum;
tat=sum+t[i];
twt=twt+wt;
ttat=ttat+tat;
printf("\n %s \t\t %d \t\t\t%d",pn[i],wt,tat);
printf("\n");
}
awt=(float)twt/n;
atat=(float)ttat/n;
printf("\n Average Waiting Time: %4.2f ms",awt);
printf("\n Average Turnaround Time: %4.2f ms",atat);
getch();
}
Output
• Processes with same priority are executed on first come first served basis.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int p[30],pr[30],key,loc,bt[30],temp,max,wt[30],ta[30],sum=0,i,j,n,sw=0;
clrscr();
wt[0]=0;
printf("enter the number of processes=");
scanf("%d",&n);
printf("enter the burst time for each process");
for(i=0;i<n;i++)
{
p[i]=i+1;
printf("\np%d=",i+1);
scanf("%d",&bt[i]);
Output
Experiment#2:
Theory
fork() :
fork() creates a new process by duplicating the calling process, The new process, referred to
as child, is an exact duplicate of the calling process, referred to as parent, except for the
following :
1. The child has its own unique process ID, and this PID does not match the ID of any
existing process group.
2. The child’s parent process ID is the same as the parent’s process ID.
3. The child does not inherit its parent’s memory locks and semaphore adjustments.
4. The child does not inherit outstanding asynchronous I/O operations from its
parent nor does it inherit any asynchronous I/O contexts from its parent.
On success, the PID of the child process is returned in the parent, and 0 is returned in
the child. On failure, -1 is returned in the parent, no child process is created, and errno is
set appropriately.
exec():
The exec() family of functions replaces the current process image with a new process image.
It loads the program into the current process space and runs it from the entry point.
int execle(const char *path, const char *arg, ..., char * const envp[]);
A call to wait() blocks the calling process until one of its child processes exits or a signal is received.
After child process terminates, parent continues its execution after wait system call instruction.
Child process may terminate due to any of these:
• It calls exit();
exit():
Program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* for fork */
#include <sys/types.h> /* forpid_t*/
#include <sys/wait.h> //for wait
int main(int argc,char** argv)
{
/*Spawn a child to run the program.*/
pid_t pid=fork();
if (pid==0)
{ /* child process */
execv("/bin/ls",argv);
exit(127); /* only if execv fails */
}
else
{pid!=0; //parent process
printf("\nWaiting Child process to finish");
waitpid(pid,0,0); /* wait for child to exit */
wait(NULL);
}
}
Output
$os509 $cc multiprogramming.c
$os509 $./a.out –l
Total 28
Experiment#3
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.
Program
#include<stdio.h>
#include<conio.h>
#include<math.h>
#define MAX 10
main()
{
int ma,bs,ps,tmp,sbn[MAX]={0},ebn[MAX]={0},count=0,i=0,k,ifrag[MAX]={0};
char ch;
clrscr();
printf("\nEnter total memory available (in MB)");
scanf("%d",&ma);
printf("\nEnter size of each block(in MB)");
scanf("%d",&bs);
while(ma)
{
printf("\nDo u have a program(y/n)");
fflush(stdin);
scanf("%c",&ch);
if((ch!='y') && (ch!='Y'))
{
printf("\nMemory available %d MB",ma);
break;
}
printf("\nEnter the size of program(inMB)");
scanf("%d",&ps);
if(ps>ma)
{
printf("\nMemory required:%d\nBUT\nMemory available:%d",ps,ma);
break;
}
count++;
if(!i)
{
sbn[i]=0;
ebn[i]=(ceil((float)ps/bs))-1;
}
else
{
sbn[i]=ebn[i-1]+1;
ebn[i]=sbn[i]+(ceil((float)ps/bs))-1;
}
tmp=((ceil((float)ps/bs)*bs));
ifrag[i]=tmp-ps;
i++;
ma-=tmp;
printf("\nMemory allocated %dMB\nMemory available %dMB",tmp,ma);
printf("\nBlocks\tnum_of_blocks\tInternal_fragmentation(inMB)");
for(k=0;k<count;k++)
printf("\n\n%d-%d\t\t%d\t\t%d",sbn[k],ebn[k],ebn[k]-sbn[k]+1,ifrag[k]);
}
getch();
}
Output
Program
#include<stdio.h>
#include<conio.h>
main()
{
static int jobs[20][2],flag[10];
int ch;
static int i,k,nj,nb,tms;
clrscr();
printf("Enter Total Memory Size::");
scanf("%d",&tms);
printf("Enter no. of jobs::");
scanf("%d",&nj);
printf("Enter %d job(s) information \n1.jobid 2.jobsize\n",nj);
for(i=0;i<nj;i++)
scanf("%d%d",&jobs[i][0],&jobs[i][1]);
for(i=0;i<nj;i++)
{
if(tms>=jobs[i][1])
{
tms=tms-jobs[i][1];
nb=nb+1;
flag[i]=1;
}
}
printf("\nJobs which are allocated:\n");
for(i=0;i<nj;i++)
if(flag[i] == 1)
printf("%d\t%d\n",jobs[i][0],jobs[i][1]);
printf("\nTotal memory space available which is not allocated is:%d\n",tms);
printf("\nJobs which are not allocated:\n");
for(i=0;i<nj;i++)
if(flag[i] == 0)
printf("%d\t%d\n",jobs[i][0],jobs[i][1]);
if(nb!=nj)
{
while(1)
{
printf("\nEnter jobid to deallocate:");
scanf("%d",&k);
for(i=0;i<nj;i++)
{
if(jobs[i][0]==k)
{
if(flag[i]==1)
{
tms=tms+jobs[i][1];
Output
Experiment: #4
Let ‘n’ be the number of processes in the system and ‘m’ be the number of resources types.
Available :
• It is a 1-d array of size ‘m’ indicating the number of available resources of each type.
Max : It is a 2-d array of size ‘n*m’ that defines the maximum demand of each process in a
system.
• Max[ i, j ] = k means process Pi may request at most ‘k’ instances of resource type Rj.
Allocation :
• It is a 2-d array of size ‘n*m’ that defines the number of resources of each
type currently allocated to each process.
Need :
• It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of each
process.
Program
#include<stdio.h>
#include<stdlib.h>
int main()
{
int Max[10][10], need[10][10], alloc[10][10], avail[10], completed[10], safeSequence[10];
int p, r, i, j, process, count;
count = 0;
printf("Enter the no of processes : "); scanf("%d", &p);
for(i = 0; i< p; i++)
completed[i] = 0;
printf("\n\nEnter the no of resources : ");
scanf("%d", &r);
printf("\n\nEnter the Max Matrix for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ", i + 1);
for(j = 0; j < r; j++)
scanf("%d", &Max[i][j]);
}
printf("\n\nEnter the allocation for each process : ");
for(i = 0; i < p; i++)
{
printf("\nFor process %d : ",i + 1);
for(j = 0; j < r; j++)
scanf("%d", &alloc[i][j]);
}
printf("\n\nEnter the Available Resources : ");
for(i = 0; i < r; i++)
scanf("%d", &avail[i]);
for(i = 0; i < p; i++)
for(j = 0; j < r; j++)
need[i][j] = Max[i][j] - alloc[i][j];
do
{
printf("\n Max matrix:\tAllocation matrix:\n");
for(i = 0; i < p; i++)
{
process = i ;
for(j = 0; j < r; j++)
{
if(avail[j] < need[i][j])
{
process = -1; break;
}
}
}
if(process != -1) break;
}
if(process != -1)
{
printf("\nProcess %d runs to completion!", process + 1);
safeSequence[count] = process + 1;
count++;
for(j = 0; j < r; j++)
{
avail[j] += alloc[process][j]; alloc[process][j] = 0; Max[process][j] = 0;
completed[process] = 1;
}
}}
while(count != p && process != -1);
if(count == p)
{
printf("\nThe system is in a safe state!!\n"); printf("Safe Sequence : < ");
for( i = 0; i < p; i++)
printf("%d ", safeSequence[i]); printf(">\n");
}
else
printf("\nThe system is in an unsafe state!!");
}
Output
Enter the no of processes : 5
Enter the no of resources : 3
Enter the Max Matrix for each process :
For process 1 : 7
5
3
For process 2 : 3 2 2
For process 3 : 7 0 2
For process 4 : 2 2 2
For process 5 : 4 3 3
Enter the allocation for each process :
For process 1 : 010
For process 2 : 2 0 0
For process 3 : 3 0 2
For process 4 : 2 1 1
For process 5 : 0 0 2
Enter the available Resources : 3 3 2
Max matrix: Allocation matrix:
753 0 10
322 2 00
702 3 02
222 2 11
433 0 02
Experiment: #5
Prevention Theory
1. Mutual Exclusion
3. No preemption
4. Circular wait
Deadlock Prevention
1. Allocate all required resources to the process before the start of its execution, this way
hold and wait condition is eliminated but it will lead to low device utilization. for
example, if a process requires printer at a later time and we have allocated printer
before the start of its execution printer will remain blocked till it has completed its
execution.
2. The process will make a new request for resources after releasing the current set of
resources. This solution may lead to starvation.
Eliminate No Preemption
Preempt resources from the process when resources required by other high priority processes.
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 for process %d:",i);
for(j=1;j<= rno;j++)
scanf("%d",&max[i][j]);
}
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];
}
}
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;
}
}
}
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();
}
Output
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
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
Experiment: #6
Program
include<stdio.h>
int main()
{
int i,j,n,a[50],frame[10],no,k,avail,count=0; printf("\n ENTER
THE NUMBER OF PAGES:\n");
scanf("%d",&n);
printf("\n ENTER THE PAGE NUMBER :\n"); for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("\n ENTER THE NUMBER OF FRAMES :"); scanf("%d",&no);
for(i=0;i<no;i++) frame[i]= -1;
j=0;
printf("\tref string\t page frames\n");
for(i=1;i<=n;i++)
{
printf("%d\t\t",a[i]);
avail=0;
for(k=0;k<no;k++)
if(frame[k]==a[i])
avail=1;
if (avail==0)
{
frame[j]=a[i];
j=(j+1)%no;
count++;
for(k=0;k<no;k++)
printf("%d\t",frame[k]);
}
printf("\n");
}
printf("Page Fault Is %d",count); return 0;
}
Output
ENTER THE NUMBER OF PAGES: 20
ENTERTHEPAGENUMBER:70120304230321201701 ENTER THE
NUMBER OF FRAMES :3
Page Fault Is 15
scanf("%d",&nof);
printf(" Enter the size of reference string::");
scanf("%d",&nor);
printf("\n Enter reference string with length %d::",nor);
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\n\t\t LRU PAGE REPLACEMENT ALGORITHM ");
printf("\nThe given reference string:"); for(i=0;i<nor;i++)
printf("%2d",ref[i]);
printf("\n");
for(i=1;i<=nof;i++)
{
frm[i]=-1;
lrucal[i]=0;
}
for(i=0;i<10;i++)
recent[i]=0;
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference Pg No. %d ->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}
}
if(flag==0)
{
count++;
if(count<=nof)
victim++;
else
victim=lruvictim();
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%3d",frm[j]);
}
recent[ref[i]]=i;
}
printf("\n\n\t Total No.of page faults:%d",pf);
getch();
}
int lruvictim()
{
int i,j,temp1,temp2;
for(i=0;i<nof;i++)
{
temp1=frm[i];
lrucal[i]=recent[temp1];
}
temp2=lrucal[0];
for(j=1;j<nof;j++)
{
if(temp2>lrucal[j])
temp2=lrucal[j];
}
for(i=0;i<nof;i++)
if(ref[temp2]==frm[i])
return i;
return 0;
}
Output
Theory
Least Frequently Used (LFU) is a caching algorithm in which the least frequently used cache
block is removed whenever the cache is overflowed. In LFU we check the old page as well as
the frequency of that page and if the frequency of the page is larger than the old page we
cannot remove it and if all the old pages are having same frequency then take last i.e FIFO
method for that and remove that page.
Program
#include<conio.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int find(int frame_size,int queue[],int page_num)
{
int i,found=0;
for (i=1;i<=frame_size;i++)
{
if(queue[i]==page_num)
found=1;
}
return found;
}
int nxt_ref(char* reference_string,int distinct[],int type,int start,int queue[],int frame_size)
{
int i,v,victim=0,length,*ref,j,page_num,max,victim_flag=1;
char c[1];
ref=(int*)calloc(type,sizeof(int));
for (i=1;i<=type;i++)
{
for(j=1;j<=frame_size;j++)
{
if(queue[j]==distinct[i])
{
ref[i]=0; /*if present in queue*/
break;
}
else
{
ref[i]=-1; /*if not present*/
}
}
}
length=strlen(reference_string);
for (i=start;i<length;i++)
{
c[0]=reference_string[i];
page_num=atoi(c);
for( j=1;j<=type;j++)
{
if ( (distinct[j]==page_num) && (ref[j]==0))
{
ref[j]=(i-start)+1;
break;
}}
}
for (j=1;j<=type;j++)
{
if(ref[j]==0)
{
victim_flag=0;
v=j;
break;
}
}
if (victim_flag==0)
{
for (j=1;j<=frame_size;j++)
{
if(queue[j]==distinct[v])
{
victim=j;
break;
}
}
}
else
{
max=-1;
v=0;
for (j=1;j<=type;j++)
{
if(ref[j]>max)
{
max=ref[j];
v=distinct[j];
}
}
for (j=1;j<=frame_size;j++)
{
if(queue[j]==v)
{
victim=j;
break;
}
}
}
return victim;
}
{
int i,queue[6],page_num,available,victim=1,distinct[10],type;
int page_fault=0,length,j,flag=0,k,p; char c[1];
for(i=1;i<=frame_size;i++)
{
queue[i]= -1;
}
length=strlen(reference_string);
type=1;
for(j=0;j<length;j++)
{
flag=0;
c[0]=reference_string[j];
page_num=atoi(c);
for(k=1;k<=type;k++)
{
if(distinct[k]==page_num)
{
flag=1;
break;
}
}
if(flag==0)
{
distinct[type]=page_num;
type++;
}
}
type=type-1;
for(j=0;j<length;j++)
{
flag=0;
c[0]=reference_string[j];
page_num=atoi(c);
printf("\n\n%d] Page number=%d",j+1,page_num);
available=find(frame_size,queue,page_num);
if (available==0)
{
for (p=1;p<=frame_size;p++)
{
if (queue[p]==-1)
{
flag=p;
break;
}
}
if(flag!=0)
{
queue[flag]=page_num;
page_fault++;
}
else if(flag==0)
{
victim=nxt_ref(reference_string,distinct,type,j+1,queue,frame_size);
printf("\tPage not available");
printf(" So replaced with Page no %d",queue[victim]);
queue[victim]=page_num;
page_fault++;
}
}
else
{
printf("\tPage is already available in frames");
}
display(queue,frame_size);
getch();
}
printf("\n \tTotal Page Faults : %d",page_fault);
}
void main()
{
int frame_size;
char reference_string[50];
clrscr();
printf("\n Enter frame size : ");
scanf("%d",&frame_size);
printf("\n Enter reference string : ");
scanf("%s",&reference_string);
optimal(frame_size,reference_string);
getch();
}
Output
Experiment#7
The allocation methods define how the files are stored in the disk blocks. There are three
main disk space or file allocation methods.
• Contiguous Allocation
• Linked Allocation
• Indexed Allocation
In this scheme, each file occupies a contiguous set of blocks on the disk. For example, if a file
requires n blocks and is given a block b as the starting location, then the blocks assigned to the
file will be: b, b+1, b+2,……b+n-1. This means that given the starting block address
and the length of the file (in terms of blocks required), we can determine the blocks
occupied by the file.
The directory entry for a file with contiguous allocation contains
In this scheme, a special block known as the Index block contains the pointers to all the
blocks occupied by a file. Each file has its own index block. The ith entry in the index block
contains the disk address of the ith file block
In this scheme, each file is a linked list of disk blocks which need not be contiguous. The disk
blocks can be scattered anywhere on the disk.
The directory entry contains a pointer to the starting and the ending file block. Each block contains a
pointer to the next block occupied by the file.
Program
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int st[20],b[20],b1[20],ch,i,j,n,blocks[20][20],sz[20];
char F[20][20],S[20];
clrscr();
printf(" Enter no. of Files ::");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n Enter file-%d name ::",i+1);
scanf(" %s",&F[i]);
printf(" Enter file-%d size(in kb)::",i+1);
scanf("%d",&sz[i]);
printf(" Enter Starting block of file-%d::",i+1);
scanf("%d",&st[i]);
printf(" Enter blocksize of File-%d(in bytes)::",i+1);
scanf("%d",&b[i]);
}
for(i=0;i<n;i++)
{
b1[i]=(sz[i]*1024)/b[i];/*no. of blks allocated by each file*/
printf("\nTotal %d blks allocated by File-%d.",b1[i],i+1);
}
for(i=0;i<n;i++)
{
for(j=0;j<b1[i];j++)
blocks[i][j]=st[i]+j;
}
do
{
printf("\nEnter the Filename ::");
scanf("%s",S);
for(i=0;i<n;i++)
{
if(strcmp(S,F[i])==0)
{
printf("\nFname\tFSize(kb)\tStart\tNblocks\tBlocks\n");
printf("\n \n");
printf("\n%s\t%d\t%7d\t%4d\t",F[i],sz[i],st[i],b1[i]);
for(j=0;j<b1[i];j++)
printf("%d->",blocks[i][j]);
break;
}
}
if(i==n)
printf("\nGiven file %s not found.",S);
printf("\n \n"); printf("\nDo U want to
continue ::(Y(1):n(0))"); scanf("%d",&ch);
if(ch!=1)
break;
}while(1);
}
Output
#include<stdio.h>
#include<conio.h>
#include<string.h>
int n;
void main()
{
int b[20],b1[20],i,j,blocks[20][20],sz[20],ib[20];
char F[20][20],S[20],ch;
clrscr();
printf("\n Enter no. of Files ::");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf(" Enter file-%d name ::",i+1);
scanf("%s",&F[i]);
printf(" Enter file-%d size(in kb)::",i+1);
scanf("%d",&sz[i]);
printf(" Enter blocksize of File-%d(in bytes)::",i+1);
scanf("%d",&b[i]);
printf(" Enter index block of file%d:",i+1);
scanf("%d",&ib[i]);
printf("\n");
}
for(i=0;i<n;i++)
{
b1[i]=(sz[i]*1024)/b[i];
printf(" Enter %d blocks for file-%d.\n",b1[i],i+1);
for(j=0;j<b1[i];j++)
{
printf("\tEnter the %d-block ::",j+1);
scanf("%d",&blocks[i][j]);
}
}
do
{
printf("\nEnter the Filename to display information ::");
scanf("%s",&S);
for(i=0;i<n;i++)
{
if(strcmp(F[i],S)==0)
{
printf("\nFname\tIndexBlock\tFsize(kb)\tBsize(b)\tNblocks\tBlocks\n");
printf("\n \n");
printf("\n%s\t\t%d\t%3d\t\t%d\t\t%d\t",F[i],ib[i],sz[i],b[i],b1[i]);
for(j=0;j<b1[i];j++)
printf("%d->",blocks[i][j]);
break;
}
}
if(i==n)
printf("\nGiven file %s not found.",S);
printf("\n "); printf("\nDo U want to
continue ::(Y(1):n(0))"); scanf("%d",&ch);
}while(ch!=0);
}
Output
#include<stdio.h>
#include<conio.h>
#include<string.h>
int n;
void main()
{
int b[20],b1[20],i,j,blocks[20][20],sz[20];
char F[20][20],S[20],ch;
int sb[20],eb[20],x;
clrscr();
}
if(i==n)
{
printf("\nGiven file %s not found.",S);
}
printf("\n "); printf("\nDo U want to continue
(Y(1):n(0))::"); scanf("%d",&ch);
if(ch!=1)
break;
}while(1);
}
Output
LINUX PROGRAMMING
Experiment#1
man,who,cat, cd, cp, ps, ls, mv, rm, mkdir, rmdir, echo, more, date, time, kill, history,
b) Study of vi editor.
c) Study of Bash shell, Bourne shell and C shell in Unix/Linux operating system.
WHO Command
Options
-H print headings.
Cat Command
cat filename
cat> filename
Cd Command.
Cd directoryname
Cal command
cal command will print the calendar on current month by default. If you want to
print calendar of august of 1965. That's eighth month of 1965.
August 1965
S M Tu W Th F S
1234567
891011121314
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Pwd command.
pwd command will print your home directory on screen, pwd means print working directory.
/home/satish
Ls command
ls command is most widely used command and it displays the contents of directory.
options
· ls will list all the files in your home directory, this command has
many options.
· ls -l will list all the file names, permissions, group, etc in long format ls
-a will list all the files including hidden files that start with . .
· ls -lt will list all files names based on the time of creation, newer files bring first.
· ls –Fx will list files and directory names will be followed by slash.
· ls -Rwill lists all the files and files in the all the directories, recursively.
· ls -R | more will list all the files and files in all the directories, one page at a time.
Mkdir command
mkdir aditya
Cd command
cd gvp
will change directory from current directory to gvp directory. Use pwd to check your
current directory and ls to see if gvp directory is there or not.
Chmod command
cal.txt.
initially when this file will be created the permissions for this file depends upon umask set in
ls -la cal.txt
In this line above I have -rw-rw-rw- meaning respectively that owner can read and write file,
member of the owner's group can read and write this file and anyone else connected to this
system can read and write this file., next ssb is owner of this file dxidev is the group of this file,
there are 135 bytes in this file, this file was created on December 3 at time16:14 and at the end
there is name of this file. Learn to read these permissions in binary, like this for example
Decimal 644 which is 110 100 100 in binary meand rw-r--r-- or user can read,write this file,
group can read only, everyone else can read only. Similarly, if permissions are 755 or 111 101
101 that means rwxr-xr-x or user can read, write and execute, group can read and execute,
everyone else can read and execute. All directories have d in front of permissions. So if you
don't want anyone to see your files or to do anything with it use chmod command and make
permissions so that only you can read and write to that file, i.e.
mkdir Command
rmdir Command
Date command.
Time Command time - time a simple command or give resource usage The time
command runs the specified program command with the given arguments. When
command finishes, time writes a message to standard error giving timing statistics
PS command
Options.
Shutdown command.
Shutdown command can only be executed by root. To gracefully bring down a system,
options.
state (default)
MV Command
mv filename1 filename2
cp Command
Kill Command
The command kill sends the specified signal to the specified process or
terminate a process
ECHO Command
More Command
b) Study of vi editor.
Editor
An editor allows the users to see a portion of a file on the screen and to modify characters
Vi editor
· It is a full screen editor and allows the user to view and edit the
· Vi is case sensitive.
Modes of Vi editor
Command mode
In this mode all the keys pressed by the user are interpreted to be editor commands. No text
Insert mode
This mode permits to insert a new text, editing and replacement of existing text. When
Vi editor is in insert mode the letters typed at the keyboard are echoed on the screen.
Escape mode
Syntax: vi filename
Command Action
H or backspace Left one character
l or spacebar Right one character
K or - Up one line
J or + Down one line
I Moves forward a word
#b Moves back a word
· To add text at the end of the file, position the cursor at the last character of
the file.
· Inserting text in the middle of the file is possible by pressing ‘i’. The editor accepts and
Saving text
Quitting vi
c) Study of Bash shell, Bourne shell and C shell in Unix/Linux operating system.
The shell provides you with an interface to the UNIX system. It gathers input from you
and executes programs based on that input. When a program finishes executing, it displays
that program's output. A shell is an environment in which we can run our commands,
programs, and shell scripts. There are different flavors of shells, just as there are different
flavors of operating systems. Each flavor of shell has its own set of recognized commands
and functions.
Shell Prompt:
The prompt, $, which is called command prompt, is issued by the shell. While the prompt is
displayed, you can type a command. The shell reads your input after you press Enter. It
determines the command you want executed by looking at the first word of your input. A
Following is a simple example of date command which displays current date and
time:
$date
Thu Jun 25 08:30:19 MST 2009
Shell Types:
The Bourne shell. If you are using a Bourne-type shell, the default prompt is the
$ character.
The C shell. If you are using a C-type shell, the default prompt is the % character.
There are again various subcategories for Bourne Shell which are listed as follows:
· C shell ( csh)
The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while
The Bourne shell was the first shell to appear on UNIX systems, thus it is referred
to as "the shell".
The Bourne shell is usually installed as /bin/sh on most versions of UNIX. For this
reason, it is the shell of choice for writing scripts to use on several different
versions of UNIX.
sh
The Bourne shell, called "sh," is one of the original shells, developed for Unix computers
by Stephen Bourne at AT&T's Bell Labs in 1977. Its long history of use means many
software developers are familiar with it. It offers features such as inputand output
redirection, shell scripting with string and integer variables, and condition testing and
looping.
bash
with it, but with several enhancements. Linux systems still offer the sh shell, but
"bash" -- the "Bourne-again Shell," based on sh -- has become the new defaultstandard. One
attractive feature of bash is its ability to run sh shell scripts unchanged.Shell scripts are
complex sets of commands that automate programming andmaintenance chores; being able
to reuse these scripts saves programmers time.Conveniences not present with the original
Developers have written large parts of the Linux operating system in the C and C++
languages. Using C syntax as a model, Bill Joy at Berkeley University developed the "C-
shell," csh, in 1978. Ken Greer, working at Carnegie-Mellon University, took csh
concepts a step forward with a new shell, tcsh, which Linux systems now offer. Tcsh
fixed problems in csh and added command completion, in which the shell makes
educated "guesses" as you type, based on your system's directory structure and files.
Tcsh does not run bash scripts, as the two have substantial differences.
ksh
David Korn developed the Korn shell, or ksh, about the time tcsh was introduced. Ksh
is compatible with sh and bash. Ksh improves on the Bourne shell by adding
floatingpoint arithmetic, job control, command aliasing and command completion. AT&T
held proprietary rights to ksh until 2000, when it became open source.
1. /bin
The /bin directory is for User Binaries. It is where many of the most common
Linux commands are stored. Specifically, this is where the single user mode
2. /sbin
This directory is almost exactly like the /bin directory, with one exception.
maintenance.
3. /etc
The configuration files for your programs and operating system are stored in /etc.
4. /dev
This is where all of the device files are located. For example, this is the directory
that you would call to in order to mount a drive with a command like: mount
/dev/sda2 /mnt/backup
5. /proc
The /proc directory is one of the most interesting in the whole Linux File System. It
is actually its own virtual file system with a massive amount of text information
6. /var
This is where all of the variable files are stored. Most commonly, this is where
7. /tmp
8. /usr
9. /home
This is where all of the user home directories are except for the root user’s
10. /boot
The files that make up the boot loader go in /boot. Everything from boot
11. /lib
All of the binary files that are located in /bin and /sbin are supported by the
12. /opt
/opt is short for “optional”. It is the directory where individual vendors can
13. /mnt
The /mnt directory is the mount point that system administrators can use to mount
14. /media
The /media directory serves the same purpose as the /mnt directory except it
15. /srv
.bashrc is a shell script that Bash runs whenever it is started interactively. You can put any
command in that file that you could type at the command prompt.You put commands here to
set up the shell for use in your particular environment, or to customize things to your
preferences. A common thing to put in .bashrc are aliases that you want to always be
available. Like .bash_profile you will also commonly see a .bashrc file in your home
directory.
This file is meant for setting command aliases and functions used by bash shell users.
The /etc/bashrc for Red Hat and/etc/bash.bashrc in Ubuntu is the system wide
version of .bashrc.
Interestingly enough in the Red Hat implementation the /etc/bashrc also executes
the shell scripts within/etc/profile.d but only if the users shell is a Interactive Shell
An environment variable is a named object that contains data used by one or more
applications. In simple terms, it is a variable with a name and a value. The value of an
environmental variable can for example be the location of all executable files in the
file system, the default editor that should be used, or the system locale settings. Users
new to Linux may often find this way of managing settings a bit unmanageable.
Experiment#2
2. Write a C program that makes a copy of a file using standard I/O, and system calls
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
Experiment#3
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
int pid; //process id
pid = fork(); //create another process
if ( pid < 0 )
{ //fail
printf(“\nFork failed\n”);
exit (-1);
}
else if ( pid == 0 )
{ //child
execlp ( “/bin/ls”, “ls”, “-l”, NULL ); //execute ls
}
else
{ //parent
wait (NULL); //wait for child
printf(“\nchild complete\n”);
exit (0);
}
}
Output
total 100
-rwxrwx—x 1 guest-gvp guest-gvp 140 2012-07-06 14:55 f1
drwxrwxr-x 4 guest-gvp guest-gvp 140 2012-07-06 14:40
dir1 child complete
Experiment#4
Output
-rw-rw-r—l
Student student 340 jul 27 10:45 pipe2.c
Experiment#5
shared memory
Theory
Shared Memory is an efficient means of passing data between programs. One program will
create a memory portion which other processes (if permitted) can access.The problem with
the pipes, FIFO’s and message queues is that for two processes to exchange information, the
information has to go through the kernel.
Shared memory provides a way around this by letting two or more processes share a memory
segment.In shared memory concept if one process is reading into some shared memory,for
example, other processes must wait for the read to finish before processing the data.A process
creates a shared memory segment using shmget()|. The original owner of a shared memory
segment can assign ownership to another user with shmctl(). It can also revoke this
assignment. Other processes with proper permission can perform various control functions on
the shared memory segment using shmctl().
Once created, a shared segment can be attached to a process address space using shmat(). It
can be detached using shmdt. The attaching process must have the appropriate permissions
for shmat(). Once attached, the process can read or write to the segment, as allowed by the
permission requested in the attach operation.
A shared segment can be attached multiple times by the same process. A shared memory
segment is described by a control structure with a unique ID that points to an area of physical
memory. The identifier of the segment is called the shmid. The structure definition for the
shared memory segment control structures and prototypews can be found in <sys/shm.h>.
shmget() is used to obtain access to a shared memory segment. It is prototyped by: int
shmget(key_t key, size_t size, int shmflg);
Program
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
struct country
{
char name[30];
char capital_city [30];
char currency[30];
int population;
};
int main(int argc,char*argv[])
{
int shm_id;
char*shm_addr;
int*countries_num;
struct country*countries;
struct shmid_ds shm_desc;
shm_id=shmget(100,2048,IPC_CREAT|IPC_EXCL\0600);
if(shm_id==-1){
perror(“main:shmget:”);
exit(1);
}
shm_addr=shmat(shm_id,NULL,0);
if(!shm_addr){
perror(“main:shmat:”);
exit(1);
}
countries_num=(int*)shm_addr;
*countries_num=0;
countries=(struct country*)((void*)shm_addr sizeof(int));
strcpy(countries[0],name,”U.S.A”);
strcpy(countries[0],capital_city,”WASHINGTON”);
strcpy(countries[0],currency,”U.S.DOLLAR”);
countries[0].population=250000000;
( countries_num) ;
strcpy(countries[1].name,”israel”);
strcpy(countries[1].capital_city,”jerushalem”);
strcpy(countries[1].currency,”NEW ISRAEL SHEKED”);
countries[1].population=6000000;
(*countries_num) ;
strcpy(countries[2].name,”France”);
strcpy(countries[2].capital_city,”paris”);
strcpy(countries[2].currency,”Frank”);
countries[2].population=60000000;
(*countries_num) ;
for(i=0;i<(*countries_num);i )t
{
printf(“country%d:\n”,i 1);
printf(“name:%d:\n”,i 1);
printf(“currency:%s:\n”,countries[i].currency);
printf(“population:%d:\n”,countries[i].population);
}
if(shmdt(shm_addr)==-1){
perror(“main:shmdt:”);
}
if(shmctl(shm_id,IPC_RMID,&SHM_DESC)==-1)
{
perror(“main:shmctl:”);
}
return 0;
}
Output
Shared memory ID=65537 child pointer 3086680064
Child value =1
Shared memory ID=65537 child pointer 3086680064
Parent value=1
Parent value=42
Child value=42
Experiment#6
ALGORITHM:
1. Start the process
2. Initialize buffer size
3. Consumer enters, before that producer buffer was not empty.
4. Producer enters, before check consumer consumes the buffer.
5. Stop the process.
Program
#include<stdio.h>
int mutex=1,full=0,empty=3,x=0;
main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.PRODUCER\n2.CONSUMER\n3.EXIT\n"); while(1) {
printf("\nENTER YOUR CHOICE\n");
scanf("%d",&n); switch(n) {
case 1:
if((mutex==1)&&(empty!=0))
producer();
else printf("BUFFER IS FULL"); break;
case 2:
if((mutex==1)&&(full!=0))
consumer();
else printf("BUFFER IS EMPTY"); break;
case 3: exit(0); break;
}
}
}
int wait(int s)
{
return(--s);
}
int signal(int s)
{
return(++s);
}
void producer() { mutex=wait(mutex);
full=signal(full); empty=wait(empty); x++;
Experiment#7
7. Write C program to create a thread using pthreads library and let it run its function.
Theory
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *mythread(void *vargp)
{
sleep(1);
printf("Welcome to GVPCEW\n");
return NULL;
}
int main()
{
pthread_t tid;
printf("before thread\n");
pthread_create(&tid,NULL,mythread,NULL);
pthread_join(tid,NULL);
exit(0);
}
Output
Welcome to GVPCEW
Experiment#8
Theory
A concurrent programming environment lets us designate tasks that can run in parallel. It also
lets us specify how we would like to handle the communication and synchronization issues
that result when concurrent tasks attempt to talk to each other and share data.
Because most concurrent programming tools and languages have been the result of academic
research or have been tailored to a particular vendor’s products, they are often inflexible and
hard to use. Pthreads, on the other hand, is designed to work across multiple vendors’
platforms and is built on top of the familiar UNIX C programming interface. Pthreads gives
you a simple and portable way of expressing multithreading in your programs..
Program
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *mythread1(void *vargp)
{
int i;
printf("thread1\n");
for(i=1;i<=100;i++)
printf("i=%d\n",i);
printf("exit from thread1\n");
return NULL;
}
void *mythread2(void *vargp)
{
int j;
printf("thread2 \n");
for(j=1;j<=100;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);
Output
thread1
i=1
i=2;
i=3
thread2
j=1
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
Extra programs
Experiment#1
Question: Simulate Paging Technique of memory management.
Program
/* Simulate Paging Technique of memory management
*/ #include<stdio.h>
#define MAX 50
void main()
{
int page[MAX],i,n,f,ps,off,pno,baddr,laddr;
clrscr();
printf("\nEnter the no. of pages in virtual memory::");
scanf("%d",&n);
printf("\nEnter page size::");
scanf("%d",&ps);
Input/Output:
Experiment#2
Program
/*Single level directory*/
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<graphics.h>
void main()
{
int gd=DETECT,gm,count,i,j,mid,cir_x;
char fname[10][20];
clrscr();
initgraph(&gd,&gm,"c:\\tc\\bgi");
/*cleardevice();*/
setbkcolor(RED);
puts("Enter no. of files do u have?");
scanf("%d",&count);
for(i=0;i<count;i++)
{
/*cleardevice();*/
setbkcolor(RED);
printf("Enter file %d name:",i+1);
Gayatri Vidya Parishad College of Engineering for Women Page 67
Operating Systems And Linux Programming Lab
scanf("%s",fname[i]);
setfillstyle(1,CYAN);
mid=640/count;
cir_x=mid/3;
bar3d(270,100,370,150,0,0);
settextstyle(2,0,4);
settextjustify(1,1);
outtextxy(320,125,"RootDirectory");
setcolor(BLUE);
for(j=0;j<=i;j++,cir_x+=mid)
{
line(320,150,cir_x,250);
fillellipse(cir_x,250,30,30);
outtextxy(cir_x,250,fname[j]);
}
getch();
}
}
Input/Output:
Output displayed in graphics mode. It is unable to take Print Screen.
Experiment#3
Question: Write a shell script to check whether the file is regular file, directory file or
block special file.
Program
Output
sh ifclause.sh
enter filename: syscall
syscall is regular file
Experiment#4
Question: Write a shell script to find the sum of ‘n’ numbers using while loop
Program
Sum=0
echo ‘enter n’
read n
i=1
while [$i –le $n]
do
sum=`expr$sum+$i`
i=’expr $i+1’
done
echo `sum of $n numbers is $sum`
Output
sh sumofnum.sh
enter n
5
Sum of 5 numbers is 15
Experiment#5
Question: Write a shell script to print 0 to 9 numbers using until
Program
a=0
until[$a –gt 9]
do
echo $a
a=`expr $a+1`
done
Output
sh dispuntil.sh
0
1
2
3
4
5
6
7
8
9
Experiment#6
Question: Write a shell script to find the factorial of a given number using while loop
Program
echo enter n
read n
factorial=1
if[$n –eq 0]
then
factorial=1
else
while[$n –gt 0]
do
factorial=`expr $factorial \* $n`
n=`expr $n-1`
done
fi
echo factorial is $factorial
Output
sh factorial.sh
enter n
5
Factorial is 120
Experiment#7
Question: Write a shell script to execute unix command using switch,break,continue
Program
ans=y
while[“any”=”y”]
do
echo”MENU \n 1.list of files \n 2.today’s date \n 3.process status \n 4.users of system \n
5.present working directory \n 6.quit to unix \n enter your option: \c”
read choice
case “$choice”in
1.ls –l;;
2.date;;
3.ps;;
4.who;;
5.pwd;;
6.break;;
*)echo “Invalid choice”
Continue;;
esac
done
Output
sh breakandcont.sh
menu
1.list of files
2.today’s date
3.process status
4.users of system
5.present working directory
6.quit to unix
Enter your option:2
Wed aug 28 14:32:21 Ist 2019
Menu
1.list of files
2.today’s date
3.process status
4.users of system
5.present working directory
6.quit to unix
Enter your option:6
Experiment#8
Question: Write a shell script that accepts a list of file names as its arguments, counts and
report the occurrence of each word that is present in the first argument file on other
argument file
Program
Output
$ cat test.sh
Unix
Os
$cat a.sh
Unix is an os
$cat b.sh
This is unix
$ sh list of files.sh test.sh a.sh b.sh
Unix
1
1
os
1
0
Gayatri Vidya Parishad College of Engineering for Women Page 71