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

Oslp r16 Labmanual Final

This document provides information about the laboratory manual for the Operating Systems and Linux Programming Lab course at Gayatri Vidya Parishad College of Engineering for Women. It includes the vision and mission statements of the institute and computer science department, course outcomes mapped to program outcomes, software requirements, and the JNTUK syllabus for the subject. It also lists some additional programming exercises for students and provides rubrics for internal lab assessment.

Uploaded by

ch Mahendra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views

Oslp r16 Labmanual Final

This document provides information about the laboratory manual for the Operating Systems and Linux Programming Lab course at Gayatri Vidya Parishad College of Engineering for Women. It includes the vision and mission statements of the institute and computer science department, course outcomes mapped to program outcomes, software requirements, and the JNTUK syllabus for the subject. It also lists some additional programming exercises for students and provides rubrics for internal lab assessment.

Uploaded by

ch Mahendra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING FOR WOMEN

(Approved by AICTE New Delhi & Affiliated to JNTUK, Kakinada)


Kommadi, MadhuraWada, Visakhapatnam- 530048

Department of Computer Science and Engineering

LABORATORY MANUAL

FOR

OPERATING SYSEMS AND LINUX PROGRAMMING LAB

Regulation: R16 Year & Semester: III-I


Subject Code: R1631057 NBA Course Code: CS507

Department of Computer Science and Engineering


GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING FOR WOMEN
(Approved by AICTE New Delhi & Affiliated to JNTUK, Kakinada)

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

• Provide opportunities for learning through industry-institute interaction on the state-of-the-art


technologies.

• Create a collaborative environment for research, innovation, and entrepreneurship.

• Promote activities that bring in a sense of social responsibility:

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

Course Outcomes Experiment No.


CO1 Develop programs for various CPU Scheduling Algorithms 1
Build programs for Memory Management Techniques and Page
CO2 2,3,6
Replacement Algorithms.
Construct programs for various File Allocation Strategies, Deadlock
CO3 4,5,7
Prevention and Avoidance Techniques.
CO4 Experiment with different Linux commands. 8
Develop programs simulating various OS concepts and Linux commands
CO5 9,10,11,12,13,14,15
using System Calls.

Mapping of Course Outcomes (COs) with Program Outcomes (POs)

Program Outcomes (POs)


Course
Outcomes PO PO PO PO PO PO PO PO PO PO PO PO PSO PSO
1 2 3 4 5 6 7 8 9 10 11 12 1 2
- 2 2 - 2 - - 2 2
CO1 - - - - -
- 2 2 - 2 - - 2 2
CO2 - - - - -
- 2 2 - 2 - - 2 2
CO3 - - - - -
- - 2 - 3 - 1 2 -
CO4 - - - - -
- - 3 - 3 - 1 3 -
CO5 - - - - -

Software Requirements:

• Linux Operating System with a Built-In Shell


GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING FOR WOMEN
(Approved by AICTE New Delhi & Affiliated to JNTUK, Kakinada)

JNTUK R16 SYLLABUS


GAYATRI VIDYA PARISHAD COLLEGE OF ENGINEERING FOR WOMEN
(Approved by AICTE New Delhi & Affiliated to JNTUK, Kakinada)

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)

Internals Category Points


Complete Complete Partial Misunderstandi
Aim of the understanding understanding understanding ng of the
experiment of the learning of the learning of the learning learning
(1) objectives and objectives only objectives objectives
outcomes
Write all the Write all the Some elements Some elements
elements of the elements of the are missing but are missing and
Write up
experiments experiments presented poor
(3)
which can be with poor clearly handwriting
easily readable handwriting
Internals
Complete Complete Partial Partial
Implementation & implementation implementation implementation implementation
result analysis with result with result with result only
(4) analysis and analysis only analysis only
interpretation
Experiment Experiment Partial Partial subject
and subject and subject experiment knowledge with
Viva- Voce
knowledge knowledge knowledge poor oral
(2)
with good oral with poor oral with poor oral presentation
presentation presentation presentation
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

1. Simulate the following CPU scheduling algorithms


a) Round Robin b) SJF c) FCFS d) Priority

a)Round Robin

Theory

• Round Robin is the pre-emptive process scheduling algorithm.

• Each process is provided a fix time to execute, it is called a quantum.

• Once a process is executed for a given time period, it is pre-empted and other
process executes for a given time period.

• Context switching is used to save states of pre-empted processes.

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];

Gayatri Vidya Parishad College of Engineering for Women Page 1


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 2


Operating Systems And Linux Programming Lab

printf("\n Average waiting time is ::%fms",awt);


printf("\n\n Total Turn Around Time ::%dms",ttat);
printf("\n Average Turn Around Time ::%fms",atat);
getch();
}
Output

(b) SJF- Shortest Job First

Theory

• This is also known as shortest job first, or SJF

• This is a non-preemptive, pre-emptive scheduling algorithm.

• Best approach to minimize waiting time.

• Easy to implement in Batch systems where required CPU time is known in advance.

• Impossible to implement in interactive systems where required CPU time is


not known.

• The processer should know in advance how much time process will take.

Gayatri Vidya Parishad College of Engineering for Women Page 3


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 4


Operating Systems And Linux Programming Lab

printf("The order of processes allocated to CPU are:");


for(i=0;i<n;i++)
printf(" %d",p[i]);
printf("\n "); printf("\n\tPNo\tbt\twt\ttat\n");

printf(" "); for(i=0;i<n;i++)

{
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:

Gayatri Vidya Parishad College of Engineering for Women Page 5


Operating Systems And Linux Programming Lab

c) FCFS- First Come First Serve

Theory

• Jobs are executed on first come, first serve basis.

• It is a non-preemptive, pre-emptive scheduling algorithm.

• Easy to understand and implement.

• Its implementation is based on FIFO queue.

• Poor in performance as average wait time is high.

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

Gayatri Vidya Parishad College of Engineering for Women Page 6


Operating Systems And Linux Programming Lab

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

(d) Priority Scheduling

• Priority scheduling is a non-preemptive algorithm and one of the most


common scheduling algorithms in batch systems.

• Each process is assigned a priority. Process with highest priority is to be executed


first and so on.

• Processes with same priority are executed on first come first served basis.

• Priority can be decided based on memory requirements, time requirements or


any other resource requirement.

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

Gayatri Vidya Parishad College of Engineering for Women Page 7


Operating Systems And Linux Programming Lab

printf("\t priority of p%d=",i+1);


scanf("%d",&pr[i]);
}
for(i=0;i<n;i++)
{
max=i;
for(j=i+1;j<n;j++)
{
if(pr[j] <pr[max])
max=j;
}
temp=pr[max];
pr[max]=pr[i];
pr[i]=temp;
temp=bt[max];
bt[max]=bt[i];
bt[i]=temp;
temp=p[max];
p[max]=p[i];
p[i]=temp;
}
for(i=0;i<n;i++)
{
wt[i+1]=bt[i]+wt[i];
ta[i]=bt[i]+wt[i];
sw+=wt[i];
sum+=ta[i];
}
for(i=0;i<n;i++)
{
printf("\n waiting time for p[%d]=%dms",p[i],wt[i]);
printf("\t turn around time for p[%d]=%dms",p[i],ta[i]);
}
printf("\n\n average waiting time=%fms",(float)sw/n);
printf("\n\n average turn around=%fms",(float)sum/n);
getch();
}

Output

Gayatri Vidya Parishad College of Engineering for Women Page 8


Operating Systems And Linux Programming Lab

Experiment#2:

2. Multiprogramming-Memory management- Implementation of fork (), wait (), exec()


and exit (), System calls

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.

Return value of fork()

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.

The exec() family consists of following functions,

int execl(const char *path, const char *arg, ...);

int execlp(const char *file, const char *arg, ...);

int execle(const char *path, const char *arg, ..., char * const envp[]);

int execv(const char *path, char *const argv[]);

Gayatri Vidya Parishad College of Engineering for Women Page 9


Operating Systems And Linux Programming Lab

int execvp(const char *file, char *const argv[]);

int execvpe(const char *file, char *const argv[],.char *const envp[]);


wait():

A call to wait() blocks the calling process until one of its child processes exits or a signal is received.
After child process terminates, parent continues its execution after wait system call instruction.
Child process may terminate due to any of these:

• It calls exit();

• It returns (an int) from main

• It receives a signal (from the OS or another process) whose default action is


to terminate.

exit():

exit() terminates the process normally.


status: Status value returned to the parent process. Generally, a status value of 0 or
EXIT_SUCCESS indicates success, and any other value or the constant EXIT_FAILURE is
used to indicate an error. exit() performs following operations.
* Flushes unwritten buffered data.
* Closes all open files.
* Removes temporary files.
* Returns an integer exit status to the operating system

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 */
}

Gayatri Vidya Parishad College of Engineering for Women Page 10


Operating Systems And Linux Programming Lab

else
{pid!=0; //parent process
printf("\nWaiting Child process to finish");
waitpid(pid,0,0); /* wait for child to exit */
wait(NULL);
}

printf("\nExiting main process\n");


return 0;

}
Output
$os509 $cc multiprogramming.c
$os509 $./a.out –l
Total 28

-rwxrwxr-x 1 staff2 staff2 7317 aug14 09:22 a.out

-rwxrwxr-x 1 staff2 staff2 7317 aug14 09:16 multiprogramming -


rwxrwxr-x 1 staff2 staff2 361 aug16 09:20 multiprogramming.c -
rwxrwxr-x 1 staff2 staff2 359 aug14 09:16 multiprogramming.c -
rwxrwxr-x 1 staff2 staff2 1320 aug14 09:18 multiprogramming.o

Waiting until child process is finished End of main() process

Gayatri Vidya Parishad College of Engineering for Women Page 11


Operating Systems And Linux Programming Lab

Experiment#3

Simulate the following


a) Multiprogramming with a fixed number of tasks (MFT)
b) Multiprogramming with a variable number of tasks (MVT)

a) Multiprogramming with a fixed number of tasks (MFT)


Theory

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;

Gayatri Vidya Parishad College of Engineering for Women Page 12


Operating Systems And Linux Programming Lab

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

b) Multiprogramming with a variable number of tasks (MVT)


Theory

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

Gayatri Vidya Parishad College of Engineering for Women Page 13


Operating Systems And Linux Programming Lab

MVT suffers with external fragmentation.

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];

Gayatri Vidya Parishad College of Engineering for Women Page 14


Operating Systems And Linux Programming Lab

printf("\nDeallocated job %d\t%d\n", jobs[i][0],jobs[i][1]);


printf("\nExternal fragmentation is:%d",tms);
flag[i]=2;
}
}
}
printf("\nAfter compaction,Available Memory is::%d",tms);
for(i=0;i<nj;i++)
{
if(tms>=jobs[i][1])
{
if(flag[i] == 0)
{
tms=tms-jobs[i][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("\nRemaining memory is: %d",tms);
printf("\nJobs which are not allocated are:\n");
for( i=0;i<nj;i++) /* dellocating mamory*/
if(flag[i] ==0)
printf("%d\t%d\n", jobs[i][0],jobs[i][1]);
printf("\nDo you want to deallocate 1.Yes 2.No");
scanf("%d",&ch);
if(ch ==2)
break;
}
}
printf("\nAllocated jobs are:\n");
for(i=0;i<nj;i++)
if(flag[i]==1)
printf("%d\t%d\n",jobs[i][0],jobs[i][1]);
getch();
}

Gayatri Vidya Parishad College of Engineering for Women Page 15


Operating Systems And Linux Programming Lab

Output

Gayatri Vidya Parishad College of Engineering for Women Page 16


Operating Systems And Linux Programming Lab

Experiment: #4

Simulate Bankers Algorithm for Dead Lock Avoidance


Theory
The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests
for safety by simulating the allocation for predetermined maximum possible amounts of all
resources, then makes an “s-state” check to test for possible activities, before deciding
whether allocation should be allowed to continue.

Following Data structures are used to implement the Banker’s Algorithm:

Let ‘n’ be the number of processes in the system and ‘m’ be the number of resources types.

Available :

• It is a 1-d array of size ‘m’ indicating the number of available resources of each type.

• Available[ j ] = k means there are ‘k’ instances of resource type Rj

Max : It is a 2-d array of size ‘n*m’ that defines the maximum demand of each process in a
system.

• Max[ i, j ] = k means process Pi may request at most ‘k’ instances of resource type Rj.

Allocation :

• It is a 2-d array of size ‘n*m’ that defines the number of resources of each
type currently allocated to each process.

• Allocation[ i, j ] = k means process Pi is currently allocated ‘k’ instances of


resource type Rj

Need :

• It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of each
process.

• Need [ i, j ] = k means process Pi currently need ‘k’ instances of resource type Rj

for its execution.

• Need [ i, j ] = Max [ i, j ] – Allocation [ i, j ]

Gayatri Vidya Parishad College of Engineering for Women Page 17


Operating Systems And Linux Programming Lab

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++)
{

for( j = 0; j < r; j++) printf("%d ", Max[i][j]);


printf("\t\t");
for( j = 0; j < r; j++) printf("%d ", alloc[i][j]);
printf("\n");
}
process = -1;
for(i = 0; i < p; i++)
{
if(completed[i] == 0)//if not completed
{

Gayatri Vidya Parishad College of Engineering for Women Page 18


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 19


Operating Systems And Linux Programming Lab

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

Process 2 runs to completion!


Max matrix: Allocation matrix:
753 0 10
000 0 00
702 3 02
222 2 11
433 0 02

Process 3 runs to completion!


Max matrix: Allocation matrix:
753 0 10
000 0 00
000 0 00
222 2 11
433 0 02

Process 4 runs to completion!


Max matrix: Allocation matrix:
753 0 10
000 0 00
000 000
000 000
433 002

Process 1 runs to completion!


Max matrix: Allocation matrix:
000 0 00
000 0 00
000 0 00
000 0 00
433 0 02

Process 5 runs to completion!


The system is in a safe state!!
Safe Sequence : < 2 3 4 1 5 >

Gayatri Vidya Parishad College of Engineering for Women Page 20


Operating Systems And Linux Programming Lab

Experiment: #5

5. Simulate Bankers Algorithm for Dead Lock

Prevention Theory

Deadlock has following characteristics.

1. Mutual Exclusion

2. Hold and Wait

3. No preemption

4. Circular wait

Deadlock Prevention

We can prevent Deadlock by eliminating any of the above four conditions.

Eliminate Mutual Exclusion


It is not possible to dis-satisfy the mutual exclusion because some resources, such as the
tap drive and printer, are inherently non-shareable.

Eliminate Hold and wait

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.

Gayatri Vidya Parishad College of Engineering for Women Page 21


Operating Systems And Linux Programming Lab

Eliminate No Preemption
Preempt resources from the process when resources required by other high priority processes.

Eliminate Circular Wait


Each resource will be assigned with a numerical number. A process can request the
resources only in increasing order of numbering.
For Example, if P1 process is allocated R5 resources, now next time if P1 ask for R4, R3
lesser than R5 such request will not be granted, only request for resources more than R5 will
be granted.

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++)

Gayatri Vidya Parishad College of Engineering for Women Page 22


Operating Systems And Linux Programming Lab

{
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++)
{

Gayatri Vidya Parishad College of Engineering for Women Page 23


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 24


Operating Systems And Linux Programming Lab

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 00
3 0 2| 9 0 2| 6 00
2 1 1| 2 2 2| 0 11
0 0 2| 4 3 3| 4 31
Process 4 completed
Available matrix: 7 4 3
Allocated matrix Max Need
0 1 0| 7 53| 7 4 3
0 0 0| 0 00| 0 0 0
3 0 2| 9 02| 6 0 0
0 0 0| 0 00| 0 0 0
0 0 2| 4 33| 4 3 1
Process 1 completed
Available matrix: 7 5 3
Allocated matrix Max Need
0 0 0| 0 00| 0 0 0
0 0 0| 0 00| 0 0 0
3 0 2| 9 02| 6 0 0
0 0 0| 0 00| 0 0 0
0 0 2| 4 33| 4 3 1
Process 3 completed
Available matrix: 10 5 5
Allocated matrix Max Need
0 0 0| 0 00| 0 0 0
0 0 0| 0 00| 0 0 0
0 0 0| 0 00| 0 0 0
0 0 0| 0 00| 0 0 0
0 0 2| 4 33| 4 3 1
Process 5 completed
Available matrix: 10 5 7
The system is in a safe state!!

Gayatri Vidya Parishad College of Engineering for Women Page 25


Operating Systems And Linux Programming Lab

Experiment: #6

Simulate the following page replacement algorithms.


a) FIFO b) LRU c) LFU
In an operating system that uses paging for memory management, a page replacement
algorithm is needed to decide which page needs to be replaced when new page comes in.

a) FIFO- First In First Out


Theory
This is the simplest page replacement algorithm. In this algorithm, the operating system
keeps track of all pages in the memory in a queue, the oldest page is in the front of the queue.
When a page needs to be replaced page in the front of the queue is selected for removal.

Program

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

Gayatri Vidya Parishad College of Engineering for Women Page 26


Operating Systems And Linux Programming Lab

Output
ENTER THE NUMBER OF PAGES: 20
ENTERTHEPAGENUMBER:70120304230321201701 ENTER THE
NUMBER OF FRAMES :3

ref string page frames


7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
0
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
3
2
1 0 1 3
2 0 1 2
0
1
7 7 1 2
0 7 0 2
1 7 0 1

Page Fault Is 15

b) LRU- Least Recently Used


In this algorithm page will be replaced which is least recently used.
Program
#include<stdio.h>
#include<conio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],lrucal[50],count=0;
int lruvictim();
void main()
{
clrscr();
printf("\n\t\t\t LRU PAGE REPLACEMENT ALGORITHM");
printf("\n Enter Frame Size::");

Gayatri Vidya Parishad College of Engineering for Women Page 27


Operating Systems And Linux Programming Lab

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;

Gayatri Vidya Parishad College of Engineering for Women Page 28


Operating Systems And Linux Programming Lab

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

c) LFU- Least Frequently Used

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>

Gayatri Vidya Parishad College of Engineering for Women Page 29


Operating Systems And Linux Programming Lab

#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)
{

Gayatri Vidya Parishad College of Engineering for Women Page 30


Operating Systems And Linux Programming Lab

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

void display(int queue[],int frame_size)


{
int p;
printf("\n Page Frames : \t");
for(p=1;p<=frame_size;p++)
{
printf("%d\t",queue[p]);
}
}
void optimal(int frame_size,char* reference_string)

Gayatri Vidya Parishad College of Engineering for Women Page 31


Operating Systems And Linux Programming Lab

{
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)

Gayatri Vidya Parishad College of Engineering for Women Page 32


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 33


Operating Systems And Linux Programming Lab

Output

Gayatri Vidya Parishad College of Engineering for Women Page 34


Operating Systems And Linux Programming Lab

Experiment#7

7. Simulate the following File allocation

strategies a) Sequenced b) Indexed c) Linked

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

a) Sequenced File 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

• Address of starting block

• Length of the allocated portion.

b) Indexed File allocation

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

c) Linked File allocation

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.

Gayatri Vidya Parishad College of Engineering for Women Page 35


Operating Systems And Linux Programming Lab

Program

a) Sequenced File allocation

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

Gayatri Vidya Parishad College of Engineering for Women Page 36


Operating Systems And Linux Programming Lab

}
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

Gayatri Vidya Parishad College of Engineering for Women Page 37


Operating Systems And Linux Programming Lab

b) Indexed File allocation

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

Gayatri Vidya Parishad College of Engineering for Women Page 38


Operating Systems And Linux Programming Lab

}
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

c) Linked File allocation

#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();

Gayatri Vidya Parishad College of Engineering for Women Page 39


Operating Systems And Linux Programming Lab

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 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];
printf("\n file-%d allocate total %d blocks.\n",i+1,b1[i]);
printf(" \tEnter Starting block of file-%d::",i+1);
scanf("%d",&sb[i]);
printf(" \tEnter Ending block of file-%d::",i+1);
scanf("%d",&eb[i]);
printf("\n Enter blocks for file-%d:\n",i+1);
for(j=0;j<b1[i]-2;)
{
printf("\tEnter the %dblock ::",j+1);
scanf("%d",&x);
if(x>sb[i]&&x<eb[i])
{
blocks[i][j]=x;
j++;
}
else
printf(" Invalid block::");
}
}
do
{
printf("\nEnter the Filename ::");
scanf("%s",&S);
for(i=0;i<n;i++)
{
if(strcmp(F[i],S)==0)
{
printf("\nFname\tFsize(kb)\tBsize(b)\tNblocks\tBlocks");
printf("\n \n");
printf("\n%s\t%d\t\t%d\t\t%d\t",F[i],sz[i],b[i],b1[i]);
printf("%d->",sb[i]);
for(j=0;j<b1[i]-2;j++)
printf("%d->",blocks[i][j]);
printf("%d->",eb[i]);
break;
}

Gayatri Vidya Parishad College of Engineering for Women Page 40


Operating Systems And Linux Programming Lab

}
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

Gayatri Vidya Parishad College of Engineering for Women Page 41


Operating Systems And Linux Programming Lab

LINUX PROGRAMMING

Experiment#1

1. a) Study of Unix/Linux general purpose utility command list

man,who,cat, cd, cp, ps, ls, mv, rm, mkdir, rmdir, echo, more, date, time, kill, history,

chmod, chown, finger, pwd, cal, logout, shutdown.

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

WHO Command

who command displays information about the current status of system.

who options file

Who as default prints login names of users currently logged in.

Options

-a use all options.

-b Report information about last reboot.

-d report expired processes.

-H print headings.

-p report previously spawned processes.

-u report terminal usage.

Cat Command

cat filename

cat is used to display the contents of the file.

cat is used to create file

cat> filename

Gayatri Vidya Parishad College of Engineering for Women Page 42


Operating Systems And Linux Programming Lab

Cd Command.

Cd directoryname

Will change directory from current directory to specified directory.

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.

cal 8 1965 will print following results.

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.

Gayatri Vidya Parishad College of Engineering for Women Page 43


Operating Systems And Linux Programming Lab

· ls -R | more will list all the files and files in all the directories, one page at a time.

Mkdir command

mkdir aditya

will create new directory, i.e. here aditya directory is created.

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

chmod command is used to change permissions on a file.

cal.txt.

initially when this file will be created the permissions for this file depends upon umask set in

your profile files. As you can see this file has

666 or -rw-rw-rw attributes.

ls -la cal.txt

-rw-rw-rw- 1 ssb dxidev 135 Dec 3 16:14 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.

Gayatri Vidya Parishad College of Engineering for Women Page 44


Operating Systems And Linux Programming Lab

chmod 600 filename.

mkdir Command

mkdir dirname Makes a new directory

rmdir Command

rmdir dirname Removes directory

Date command.

Date displays todays date, to use it type date at prompt.

Sun Dec 7 14:23:08 EST 2019

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

about this program run.

PS command

ps command is probably the most useful command for systems administrators. It

reports information on active processes.

Options.

-a Lists all processes in system except processes not attached to terminals.

-e Lists all processes in system.

-f Lists a full listing.

-j print process group ID and session ID.

Shutdown command.

Shutdown command can only be executed by root. To gracefully bring down a system,

shutdown command is used.

options.

· -gn use a grace-period of n seconds (default is 60).

· -ik tell the init command to place system in a state k. o s single-user

state (default)

Gayatri Vidya Parishad College of Engineering for Women Page 45


Operating Systems And Linux Programming Lab

¨ 0 shutdown for power-off.

¨ 1 like s, but mount multi-user file systems.

¨ 5 stop system, go to firmware mode.

¨ 6 stop system then reboot.

· -y suppress the default prompt for confirmation.

MV Command

Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.

mv change file name or directory location

mv filename1 filename2

cp Command

cp - copy files and directories

Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.

cp [OPTION]... [-T] SOURCE DEST

Kill Command

The command kill sends the specified signal to the specified process or

process group. If no signal is specified, the TERM signal is sent. kill -

terminate a process

ECHO Command

- display a line of text

More Command

more â file perusal filter for correct viewing

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

and lines by simply typing at the cursor position.

Vi editor

· Vi stands for visual

Gayatri Vidya Parishad College of Engineering for Women Page 46


Operating Systems And Linux Programming Lab

· It is a full screen editor and allows the user to view and edit the

entire document at the same time.

· Vi is case sensitive.

· It has powerful undo features.

Modes of Vi editor

Editor works in 3 modes

Command mode

In this mode all the keys pressed by the user are interpreted to be editor commands. No text

is displayed on the screen even if corresponding keys is pressed on the keyboard.

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

Commands typed at the command line.

Starting with Vi editor

Syntax: vi filename

Moving the cursor

The cursor movement commands are:

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

Editing the file

· Open the file using $ vi filename

Gayatri Vidya Parishad College of Engineering for Women Page 47


Operating Systems And Linux Programming Lab

· To add text at the end of the file, position the cursor at the last character of

the file.

· Switch from command mode to text input mode by pressing ‘a’.

· Here ‘a’ stands for append.

· Inserting text in the middle of the file is possible by pressing ‘i’. The editor accepts and

inserts the typed character until Esc key is pressed.

Saving text

· :w – save the file and remains in edit mode

· :wq – save the file and quits from edit mode

· :q – quit without changes from edit mode

Quitting vi

Press zz or ‘:wq’ in command mode.

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

word is an unbroken set of characters. Spaces and tabs separate words.

Following is a simple example of date command which displays current date and

time:
$date
Thu Jun 25 08:30:19 MST 2009

Gayatri Vidya Parishad College of Engineering for Women Page 48


Operating Systems And Linux Programming Lab

Shell Types:

In UNIX there are two major types of shells:

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:

· Bourne shell ( sh)

· Korn shell ( ksh)

· Bourne Again shell ( bash)

· POSIX shell ( sh)

· C shell ( csh)

· TENEX/TOPS C shell ( tcsh)

The original UNIX shell was written in the mid-1970s by Stephen R. Bourne while

he was at AT&T Bell Labs in New Jersey.

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

The popularity of sh motivated programmers to develop a shell that was compatible

Gayatri Vidya Parishad College of Engineering for Women Page 49


Operating Systems And Linux Programming Lab

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

Bourne shell include command completion and a command history.

csh and tcsh

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.

d) Study of Unix/Linux file system (tree structure).

Gayatri Vidya Parishad College of Engineering for Women Page 50


Operating Systems And Linux Programming Lab

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

binaries are stored.

2. /sbin

This directory is almost exactly like the /bin directory, with one exception.

The binaries here are primarily used by Administrators for system

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

Gayatri Vidya Parishad College of Engineering for Women Page 51


Operating Systems And Linux Programming Lab

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

about system processes.

6. /var

This is where all of the variable files are stored. Most commonly, this is where

log files and web server files are stored.

7. /tmp

These are simply temporary files.

8. /usr

Programs installed by single users get stored here.

9. /home

This is where all of the user home directories are except for the root user’s

home directory which is /root.

10. /boot

The files that make up the boot loader go in /boot. Everything from boot

loader menus, to the actual kernel files are stored here.

11. /lib

All of the binary files that are located in /bin and /sbin are supported by the

library files located in /lib.

12. /opt

/opt is short for “optional”. It is the directory where individual vendors can

install optional add-on software for the operating system.

13. /mnt

The /mnt directory is the mount point that system administrators can use to mount

file systems temporarily.

14. /media

Gayatri Vidya Parishad College of Engineering for Women Page 52


Operating Systems And Linux Programming Lab

The /media directory serves the same purpose as the /mnt directory except it

is specifically for removable devices and can be used by non administrators.

15. /srv

The /srv directory contains server specific service files.

e) Study of .bashrc, /etc/bashrc and Environment variables.

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

Just like the /etc/profile is the system wide version of .bash_profile.

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

(aka Login 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.

However, environment variables provide a simple way to share configuration settings

between multiple applications and processes in Linux

Gayatri Vidya Parishad College of Engineering for Women Page 53


Operating Systems And Linux Programming Lab

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>

void typefile (char *filename)


{
int fd, nread;
char buf[1024];
fd = open (filename, O_RDONLY);
if (fd == -1) {
perror (filename);
return;
}
while ((nread = read (fd, buf, sizeof (buf))) > 0)
write (1, buf, nread);
close (fd);
}
int
main (int argc, char **argv)
{
int argno;
for (argno = 1; argno < argc; argno )
typefile (argv[argno]);
exit (0);
}

student@ubuntu:~$gcc –o prg10.out prg10.c


student@ubuntu:~$cat > ff
hello
hai
student@ubuntu:~$./prg10.out ff
hello
hai

Gayatri Vidya Parishad College of Engineering for Women Page 54


Operating Systems And Linux Programming Lab

Experiment#3

3. Write a C program to emulate the UNIX ls –l command

#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

Gayatri Vidya Parishad College of Engineering for Women Page 55


Operating Systems And Linux Programming Lab

Experiment#4

4. Write a C program that illustrates how to execute two

commands concurrently with a command pipe. Ex: - ls –l | sort


Theory
A pipe is created by calling a pipe() function.
int pipe(int filedesc[2]);
It returns a pair of file descriptors filedesc[0] is open for reading and filedesc[1]
is open for writing. This function returns a 0 if ok & -1 on error.
Program
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
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);
}
}

Output

Parent reading from pipe


Total 24
-rwxrwxr-x l student student 5563Aug 3 10:39 a.out

Gayatri Vidya Parishad College of Engineering for Women Page 56


Operating Systems And Linux Programming Lab

-rw-rw-r—l
Student student 340 jul 27 10:45 pipe2.c

-rw-rw-r—l student student


Pipes2.c

-rw-rw-r—l student student 401 34127 10:27 pipe2.c


student

Gayatri Vidya Parishad College of Engineering for Women Page 57


Operating Systems And Linux Programming Lab

Experiment#5

5. Write a C program that illustrates two processes communicating using

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;

Gayatri Vidya Parishad College of Engineering for Women Page 58


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 59


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 60


Operating Systems And Linux Programming Lab

Experiment#6

6. Write a C program to simulate producer and consumer problem using semaphores

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++;

Gayatri Vidya Parishad College of Engineering for Women Page 61


Operating Systems And Linux Programming Lab

printf("\nproducer produces the item%d",x);


mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\n consumer consumes item%d",x);
x--;
mutex=signal(mutex);
}
Output
[root@localhost ~]# ./a.out
1.PRODUCER 2.CONSUMER 3.EXIT
ENTER YOUR CHOICE
1producer produces the item1
ENTER YOUR CHOICE
1producer produces the item2
ENTER YOUR CHOICE
2consumer consumes item2
ENTER YOUR CHOICE
2consumer consumes item1
ENTER YOUR CHOICE
2BUFFER IS EMPTY
ENTER YOUR CHOICE

Gayatri Vidya Parishad College of Engineering for Women Page 62


Operating Systems And Linux Programming Lab

Experiment#7

7. Write C program to create a thread using pthreads library and let it run its function.

Theory

Creating a (Default) Thread


Use the function pthread_create() to add a new thread of control to the current process. It is
prototyped by:
int pthread_create(pthread\_t *tid, const pthread\_attr\_t *tattr,
void*(*start_routine)(void *), void *arg);
When an attribute object is not specified, it is NULL, and the default thread is created
with the following attributes:
· It is unbounded
· It is nondetached
· It has a a default stack and stack size
· It inhetits the parent's priority
You can also create a default attribute object with pthread_attr_init() function,
and then use this attribute object to create a default thread. Program

#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

Gayatri Vidya Parishad College of Engineering for Women Page 63


Operating Systems And Linux Programming Lab

Experiment#8

8. Write a C program to illustrate concurrent execution of threads


using pthreads Library

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

Gayatri Vidya Parishad College of Engineering for Women Page 64


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 65


Operating Systems And Linux Programming Lab

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

printf("\nEnter no. of frames in Physical memory::");


scanf("%d",&f);
for(i=0;i<n;i++) /* initially no frame allocation for pages in physical
mry*/ page[i]=-1;
printf("\nEnter the page table\n");
printf("(Enter frame no as -1 if that page is not present in any frame)\n\n");
printf("\npageno\tframeno\n-------\t-------");
for(i=0;i<n;i++)
{
printf("\n%d\t",i);
scanf("%d",&page[i]);
}
printf("Virtual(logical) address locations Range from 0 to %d",(n*ps)-1);
printf("\n\nEnter the logical address:");
scanf("%d",&laddr);
pno=laddr/ps;
off=laddr%ps;
printf("PageNo:Offset->%d:%d\n",pno,off);
if(page[pno]==-1)
printf("\nThe required page is not available in any of frames.");
else
{
printf("Enter Base Address:");
scanf("%d",&baddr);
printf("\nPhysical address:%d",baddr+(page[pno]*ps+off));
}
getch();
}

Input/Output:

Gayatri Vidya Parishad College of Engineering for Women Page 66


Operating Systems And Linux Programming Lab

Experiment#2

Question: Simulate Single level directory File Organization Technique.

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

echo ‘enter filename:’


read file
if[-f $file]
then
echo $file is regular file
elif[-d $file]
then
echo $file is directory file
elif[-b $file]
then
echo $file is block special file
else
echo $file is not existed
fi

Output
sh ifclause.sh
enter filename: syscall
syscall is regular file

Gayatri Vidya Parishad College of Engineering for Women Page 68


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 69


Operating Systems And Linux Programming Lab

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

Gayatri Vidya Parishad College of Engineering for Women Page 70


Operating Systems And Linux Programming Lab

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

For x in `cat $1`


do
echo $x
grep -c $x $2
grep -c $x $3
done

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

You might also like