OS Lab Manual
OS Lab Manual
(AUTONOMOUS)
(Affiliated to Osmania University, Approved by AICTE and Accredited
by NAAC)
Hyderabad - 500 001, Telangana, India
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Course Code SPC0404CS Credits: 2 Evaluation: CIE - 40 Marks & SEE – 60 Marks
Roll Number:
PEO1. Graduates shall have enhanced skills and contemporary knowledge in software and hardware
technologies for professional excellence, towards successful employment, advanced learning and
research.
PEO2. Graduates shall have life-long learning attitude, innovation and creativity to master latest
technologies, devise solutions for realistic and social issues in the society.
PEO3. Graduates shall have good attitude and personality skills, ethical values, teamwork and
leadership skill towards professionalism and ethical practices within the organization and the society
STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN
Abids, Hyderabad - 500 001, Telangana
PO7. Ethics: Apply ethical principles and commit to professional ethics, human values, diversity and inclusion;
adhere to national & international laws.
PO8. Individual and Collaborative Team work: Function effectively as an individual, and as a member or leader in
diverse/multi-disciplinary teams.
PO9. Communication: Communicate effectively and inclusively within the engineering community and society at large, such as
being able to comprehend and write effective reports and design documentation, make effective presentations considering
cultural, language, and learning differences.
PO10. Project Management and Finance: Apply knowledge and understanding of engineering management
principles and economic decision-making and apply these to one’s own work, as a member and leader in a team,
and to manage projects and in multidisciplinary environments.
PO11. Life-Long Learning: Recognize the need for, and have the preparation and ability for i) independent and life- long
learning ii) adaptability to new and emerging technologies and iii) critical thinking in the broadest context of
technological change.
Course Objectives:
Understand Unix commands.
Implement process management related techniques.
Implement memory management techniques.
Course Outcomes:
After completing this course, the student will be able to:
Execute the Unix commands.
Implement CPU scheduling algorithms.
Implement producer–consumer problem, reader–writers problem, dining philosophers’ problem.
Apply Banker’s algorithm for deadlock avoidance.
Implement page replacement and disk scheduling techniques.
STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Autonomous)
Abids, Hyderabad - 500 001, Telangana
Department of Computer Science and Engineering
Mapping of Operating Systems Lab Course Outcomes with POs and PSOs
Program
Course Outcomes Specific
Program Outcomes (POs)
(COs) Outcomes
(PSOs)
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PSO1 PSO2
1. Execute the Unix
commands. 1 3 3 2 1 1 1 1 1 3 3
[Link] CPU
scheduling algorithms. 2 3 3 2 1 1 1 1 1 3 3
3 Implement producer–
consumer problem, 2 3 3 2 1 1 1 1 1 3 3
reader–writers
problem, dining
philosophers’ problem.
4. Apply Banker’s
algorithm for deadlock 2 3 3 2 1 1 1 1 1 3 3
avoidance
5. Implement page
replacement and 2 3 3 2 1 1 1 1 1 3 3
disk scheduling
techniques
STANLEY COLLEGE OF ENGINEERING & TECHNOLOGY FOR WOMEN
(Autonomous)
Abids, Hyderabad - 500 001, Telangana
Department of Computer Science and Engineering
Mapping of Operating Systems Lab with SDGs
Roll No:
Name:
Class, Semester & Section: B.E, VII & A, B and C
Academic Year: 2025-2026
1. Execute the Unix SDG 4 – Quality Learning and executing Unix commands builds
commands. Education strong foundational computing and problem-
solving skills, directly supporting quality technical
education (SDG 4). Unix systems are widely used in
SDG 9 – Industry,
servers, cloud platforms, and research
Innovation and infrastructure; thus, this outcome contributes to
Infrastructure robust digital infrastructure and innovation (SDG 9).
4. Apply Banker’s algorithm SDG 9 – Industry, Deadlock avoidance ensures system reliability and
for deadlock avoidance Innovation and continuous availability of computing resources,
Infrastructure strengthening resilient infrastructure (SDG 9).
Banker’s algorithm promotes optimal allocation
and prevents resource wastage, aligning with
SDG 12 – Responsible responsible resource management (SDG 12).
Consumption and
Production
5. Implement page SDG 9 – Industry, Memory and disk management techniques
replacement and disk Innovation and enhance system performance and scalability,
scheduling techniques Infrastructure which are vital for modern digital infrastructure
(SDG 9). Efficient page replacement and disk
SDG 12 – Responsible scheduling reduce unnecessary I/O operations,
Consumption and leading to lower energy consumption (SDG 7) and
Production sustainable use of hardware resources (SDG 12).
Mapping of Operating Systems Lab Programs with POs, PSOs and SDGs
2. Write C programs to demonstrate various process related concepts. 1,2,5,8 1,2 9,8
3. Write C programs to demonstrate various thread related concepts. 1,3,5,8,9, 1,2 9,12
11
4. Write C programs to simulate CPU scheduling algorithms: FCFS, SJF, Round 1,3,5,8,9 1,2 9,12
Robin
EXPERIMENT 1 :Write a C programs to implement UNIX system calls and file management
AIM : To write the program to printing file flags for specified descriptor.
PROGRAM DESCRIPTION:
h is the header in the C POSIX library for the C programming language that contains constructs
that refer to file control, e.g. opening a file, retrieving and changing the permissions of file,
locking a file for edit, etc.
The sys/types.h header file defines a collection of typedef symbols and structures.
The stat data structure in the /usr/include/sys/stat.h file returns information for
the stat, fstat, lstat, statx, and fstatx subroutines.
PROGRAM CODING :
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(int argc,char *argv[]) /*command line argument . argc counts the number
of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the
file name always. */
if(argc != 2)
exit(1);
else
Stat(argv[1],&str);
} return (0);
OUTPUT:
AIM: To write the program to print recursively descend a directory hierarchy counting file
types.
PROGRAM CODING
#include<stdio.h>
#include<dirent.h> //dirent.h - format of directory entries
#include<errno.h>
/*The <errno.h> header file defines the integer variable errno,which is set by system
calls and some library functions in the event of an error to indicate what went wrong.
*/
#include<fcntl.h>
main(int argc,char *argv[])
{
struct dirent *direntp;
DIR *dirp;
if(argc != 2)
{
printf("Usage: %s directory name\n",argv[0]);
return 1;
}
if((dirp=opendir(argv[1]))==NULL)
{
perror("Failed to open directry\n");
return 1;
}
while((direntp=readdir(dirp))!= NULL)
printf("%s\n",direntp->d_name);
while((closedir(dirp)==-1) && (errno==EINTR));
return 0;
}
OUTPUT:
[swapna@linuxstuserver ses4]$ cc 5dirfiltyp.c
[swapna@linuxstuserver ses4]$ ./[Link] dir
[Link]
1
3
..
2 [Link]
2.1) Fork()
2.2) Factorial of a number using fork()
2.3) Process Heirarchy
2.4) wait()
2.5) exec()
2.6) sleep()
PROGRAM DESCRIPTOR:
1. fork( ) Used to create new processes. The new process consists of a copy of the
address space of the original process. The value of process id for the child process is
zero, whereas the value of process id for the parent is an integer value greater than
zero.
Syntax : fork( )
2. execlp( ) Used after the fork() system call by one of the two processes to replace the
process‟ memory space with a new program. It loads a binary file into memory
destroying the memory image of the program containing the execlp system call and
starts its [Link] child process overlays its address space with the UNIX
command /bin/ls using the execlp system call.
Syntax : execlp( )
3. wait( ) The parent waits for the child process to complete using the wait system
call. The wait system call returns the process identifier of a terminated child, so that
the parent can tell which of its possibly many children has terminated.
Syntax : wait( NULL)
4. exit( ) A process terminates when it finishes executing its final statement and asks
the operating system to delete it by using the exit system call. At that point, the
process may return data (output) to its parent process (via the wait system call).
Syntax: exit(0)
ALGORITHM :
PROGRAM CODING:
#include<stdio.h>
#include<sys/types.h>
main()
int id,childid;
id=getpid();
if(childid = fork()>0)
else
OUTPUT:
#include<stdio.h>
#include<sys/types.h>
void main()
int pid,f=1,n;
printf("enter a number\n");
scanf("%d",&n);
pid=fork();
if(pid==0)
while(n>0)
f=f*n;
n--;
printf("\nfactorial of a number%d",f);
else {
OUTPUT:
enter a number
my pid now is 0
i am in child process
factorial of a number120
#include<stdio.h>
#include<sys/types.h>
main()
int pid,pid1,pid2,pid3,pid4;
pid=fork();
if(pid==0)
printf("i am A%d\n",getpid());
printf("i am parentA%d\n",getppid());
pid1=fork();
if(pid1==0)
printf(" i am B%d\n",getpid());
pid3=fork();
if(pid3==0)
printf("i am c %d\n",getpid());
printf("parent of c %d\n",getppid());
else
pid2=fork();
if(pid2==0)
printf("i am D%d\n",getpid());
pid4=fork();
if(pid4==0)
}}
OUTPUT:
i am A5184
i am parentA5183
i am B5185
parent of B5184
i am c 5186
parent of c 5185
i am D5187
parent of D1
iam E5188
parent of E 5187
#include<stdio.h>
#include<sys/types.h>
void main()
int i=0,pid;
pid=fork();
if(pid==0)
for(i=0;i<5;i++)
printf("\n%d",i);
else
{ printf("parent process\n");
for(i=10;i<15;i++)
wait();
printf("process ends\n");
OUTPUT:
child process
parent process
process ends
[Link]()
#include<stdio.h>
#include<sys/types.h>
printf("before execv\n");
execv("/bin/date",argv);
printf("after execv\n");
OUTPUT:
before execv
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
void main()
int pid,i;
pid=fork();
switch(pid)
sleep(4);
for(i=0;i<5;i++)
printf("\n%d",i);
break;
case -1:printf("error");
break;
default:
for(i=6;i<10;i++)
printf("\n%d",i);
break;
OUTPUT:
child process
i am parent process
9[sireesha@localhost lab2]$
PROGRAM DESCRIPTION
Thread is an execution unit which consists of its own program counter, a stack, and a set of
registers. Threads are also known as Lightweight processes. Threads are popular way to
improve application through parallelism. The CPU switches rapidly back and forth among the
threads giving illusion that the threads are running in parallel.
Types of Thread
There are two types of threads :
User Threads
Kernel Threads
User threads, are above the kernel and without kernel support. These are the threads
that application programmers use in their programs.
Kernel threads are supported within the kernel of the OS itself. All modern OSs
support kernel level threads, allowing the kernel to perform multiple simultaneous
tasks and/or to service multiple kernel system calls simultaneously.
When multiple threads are running they will invariably need to communicate with each other
inorder synchronize their execution. One main benefit of using threads is the ease of using
synchronization facilities
#include <pthread.h>
pthread_t pthread_self(void);
#include <pthread.h>
void pthread_exit(void *value_ptr);
pthread_create() : This function creates a new thread of control that executes concurrently
withthe calling thread. The new thread applies the function start_routine passing it arg as
firstargument. The new thread terminates either explicitly, by calling pthread_exit(), or
implicitly, byreturning from the start_routine function. The latter case is equivalent to calling
pthread_exit()with the result returned by start_routine as exit [Link] attr argument
specifies thread attributesto be applied to the new thread.
#include <pthread.h>
int pthread_create(pthread_t * thread, pthread_attr_t * attr, void *(*start_routine)(void *),
void * arg);
pthread_join()
pthread_join suspends the execution of the calling thread until the thread identified by
th terminates, either by calling pthread_exit() or by being cancelled. If thread_return is not
NULL, the return value of th is stored in the location pointed to by thread_return. The return
value of th is either the argument it gave to pthread_exit(), or PTHREAD_CANCELED if
th was [Link] joined thread th must be in the joinable state.
#include <pthread.h>
int pthread_join(pthread_t th, void **thread_return);
ALGORITHM :
PROGRAM CODE:
#include<stdio.h>
#include<pthread.h>
#include<sys/types.h>
#include<unistd.h>
int s;
pthread_attr_t attr;
pthread_t tid;
if(argc!=2)
printf(stderr,"usage:[Link]<integervalues>\n");
return -1;
pthread_attr_init(&attr);
pthread_create(&tid,&attr,runner,argv[1]);
pthread_join(tid,0);
printf("sum=%d",s);
int i,upper;
upper=atoi(param);
s=0;
for(i=0;i<=upper;i++)
s+=i;
pthread_exit(0);
OUTPUT
sum=55[sireesha@server ~]$
PROGRAM CODE:
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
void* th(void*);
int main()
pthread_t t1;
int c;
void* r;
c=pthread_create(&t1,NULL,th,NULL);
if(c!=0)
printf("not created\n");
exit(0);
sleep(3);
printf("canceling thread\n");
if(c!=0)
exit(0);
c=pthread_join(t1,&r);
if(c!=0)
printf("cant be joined\n");
exit(0);
return 0;
void* th(void* p)
int i,r;
if(r!=0)
exit(0);
r=pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED,NULL);//setting type of
cancellation to be deferred
for(i=0;i<10;i++)
sleep(1);
OUTPUT:
PROGRAM CODE:
#include <unistd.h>
#include<stdio.h>
#include<pthread.h>
void* th(void*);
int main()
pthread_t t1,t2;
int c;
void* r;
pthread_create(&t1,NULL,th,NULL);
pthread_create(&t2,NULL,th,NULL);
pthread_join(t1,&r);
pthread_join(t2,&r);
void* th(void* p)
{++i;
pthread_exit(NULL);}
OUTPUT:
EXPERIMENT 4 : Implement CPU scheduling algorithms (A) Round Robin (B) SJF (c)
FCFS
PROGRAM DESCRIPTION:
CPU scheduler will decide which process should be given the CPU for its execution. For
this it use different algorithm to choose among the process. One among that algorithm is
Round robin algorithm. In this algorithm we are assigning some time slice .The process is
allocated according to the time slice, if the process service time is less than the time slice
then process itself will release the CPU voluntarily. The scheduler will then proceed to the
next process in the ready queue .If the CPU burst of the currently running process is longer
than time quantum, the timer will go off and will cause an interrupt to the operating system.
A context switch will be executed and the process will be put at the tail of the ready queue.
ALGORITHM:
PROGRAM CODE:
#include<stdio.h>
#include<stdio.h>
void main()
intfrom,wt[20],tt[20],b[20], twt=0,ttt=0;
int dur;
float awt,att;
scanf("%d",&nop);
scanf("%d",&ts);
for(i=0;i<nop;i++)
wt[i]=tt[i]=0;
printf("P%d\t: ",i+1);
scanf("%d",&b[i]);
rem[i]=b[i];
tbt+=b[i];
flag[i]=0;
from=0;
i=0;
while(from<tbt)
if(!flag[i])
if(rem[i]<=ts)
dur=rem[i];
flag[i]=1;
tt[i]=dur+from;
wt[i]=tt[i]-b[i];
else
dur=ts;
printf("%7d%15d%15d\n",i+1, from,from+dur);
rem[i] -= dur;
from += dur;
i=(i+1)%nop;
for(i=0;i<nop;i++)
twt+=wt[i];
ttt+=tt[i];
for(i=0;i<nop;i++)
printf("\n\t%d\t\t%d\t\t%d",i+1,wt[i],tt[i]);
awt=(float)twt/(float)nop;
att=(float)ttt/(float)nop;
AIM: B) To write a C program to implement the CPU scheduling algorithm for shortest job
first.
PROGRAM DESCRIPTION
Cpu scheduler will decide which process should be given the CPU for its execution. For this
it uses different algorithm to choose among the process. One among that algorithm is SJF
algorithm. In this algorithm the process which has less service time given the cpu after
finishing its request only it will allow cpu to execute next other process.
ALGORITHM:
Step 5: Waiting time of one process is the total time of the previous process.
Step 6: Total time of process is calculated by adding the waiting time and service time of
each process.
Step 7: Total waiting time calculated by adding the waiting time of each process.
Step 8: Total turn around time calculated by adding all total time of each process.
Step 9: Calculate average waiting time by dividing the total waiting time by total number of
process. Step 10: Calculate average turn around time by dividing the total waiting time by
total number of process.
Step 11: Display the result.
PROGRAM CODING:
#include<stdio.h>
int main()
int n,w[100],tot[100],i,j,awt,atot;
float avwt,avtot;
struct
int p,bt;
sjf[10],temp;
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&sjf[i].bt);
sjf[i].p=i;
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(sjf[j].bt>sjf[i].bt)
temp=sjf[i];
sjf[i]=sjf[j];
sjf[j]=temp;
w[1]=0;
tot[1]=sjf[1].bt;
for(i=2;i<=n;i++)
tot[i]=tot[i-1]+sjf[i].bt;
awt=0;
atot=0;
for(i=1;i<=n;i++)
w[i]=tot[i]-sjf[i].bt;
awt+=w[i];
atot+=tot[i];
avwt=(float)awt/n;
avtot=(float)atot/n;
for(i=1;i<=n;i++)
printf("\n\t%d\t\t%d\t\t%d",sjf[i].p,w[i],tot[i]);
AIM: C ) To write a C program to implement the CPU scheduling algorithm for first come
first serve.
PROGRAM DESCRIPTION:
Cpu scheduler will decide which process should be given the CPU for its [Link] this it
uses different algorithm to choose among the process. One among that algorithm is FCFS
algorithm. In this algorithm the process which arrive first is given the cpu after finishing its
request only it will allow cpu to execute other process.
ALGORITHM:
PROGRAM CODING:
#include<stdio.h>
int main()
{
int n,b[10],t=0,i,w=0,r=0,a=0;
float avg,avg1;
printf("\nEnter number of processes:");
scanf("%d",&n); printf("\nEnter the burst times : \n");
for(i=1;i<=n;i++)
scanf("%d",&b[i]);
printf("\n Gantt chart ");
for(i=1;i<=n;i++)
printf("P%d\t",i);
printf("\n\nProcess BurstTime WaitingTime TurnaroundTime\n");
for(i=1;i<=n;i++)
{
t=t+w;
r=r+b[i];
printf("P%d\t\t%d\t\t%d\t\t%d\t\t\n",i,b[i],w,r);
w=w+b[i];
a=a+r;
}
avg=(float)t/n;
avg1=(float)a/n;
printf("\n Average WaitingTime is %f",avg);
printf("\n Average TurnaroundTime is %f\n",avg1);
return(0);
}
OUTPUT:
[cse6@localhost Pgm]$ cc prog9a.c -o [Link]
[cse6@localhost Pgm]$ ./[Link]
Enter number of processes : 3
Enter the burst times :
24
5
3
Gantt chart P1 P2 P3
A client process sends a request message to a server process. The server process sends a
response to the request back to the client. The client echoes the server response at it side. This
type of communication is called echoserver and it is used for trouble shooting.
The client server processes share a hierarchical relationship [Link] child. The parent process
is the server and the child process is created using the fork() it could be vice versa
fork() to create a child process. One (the parent process) reads write to the pipe and child
process
reads the data from the pipe ans then prints the data to the screen.
Pipe provide unidirectional from of communication 2 pipes are used 1 process reads from 1
pipe and wirtes to 2nd
P[1],p1[1]//write descriptor
in order to communicate the client and server using message queue to read and write
msgsnd() and mgsrcv() calls are used respectively
ALGORITHM :
PROGRAM CODE :
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <string.h>
#define MAX 60
main()
a = pipe(fdclient);
b = pipe(fdserver);
if( a == 0 && b == 0)
{ pid = fork();
if (pid > 0)
close(fdserver[0]);
close(fdclient[1]);
printf("Server Process\n");
scanf("%s", server);
sleep(2);
else if (pid == 0)
printf("Client Prcoess\n");
scanf("%s", client);
close(fdclient[0]);
close(fdserver[1]);
sleep(2);
else
printf("Error\n");
OUTPUT:
PROGRAM CODE :
#include <sys/types.h>
#include <sys/ipc.h>
#include <stdio.h>
#include <string.h>
#define MAX 60
main()
a = pipe(fdclient);
b = pipe(fdserver);
if( a == 0 && b == 0)
pid = fork();
if (pid > 0)
close(fdserver[0]);
close(fdclient[1]);
printf("Server Process\n");
scanf("%s", server);
sleep(2);
else if (pid == 0)
else
printf("Client Prcoess\n");
scanf("%s", client);
close(fdclient[0]);
close(fdserver[1]);
sleep(2);
printf("Error\n");
OUTPUT:
Client process
Server Process
PROGRAM DESCRIPTION:
Shared Memory - is an efficeint means of passing data between programs. One program will
create a memory portion which other processes (if permitted) can access.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
addressspace using shmat(). It can be detached using shmdt() The attaching process must have
theappropriate 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 attachedmultiple times by the same process. A shared memory segment is described by a
controlstructure with a unique ID that points to an area of physical memory. The identifier of
thesegment is called the shmid. The structure definition for the shared memory segment
controlstructures and prototype can be found in <sys/shm.h>
One shmid data structure for each shared memory segment in the system. */
struct shmid_ds {
struct ipc_perm shm_perm; /* operation perms */
int shm_segsz; /* size of segment (bytes) */
time_t shm_atime; /* last attach time */
time_t shm_dtime; /* last detach time */
time_t shm_ctime; /* last change time */
unsigned short shm_cpid; /* pid of creator */
unsigned short shm_lpid; /* pid of last operator */
short shm_nattch; /* no. of current attaches */
`}
shmget () - allocates a System V shared memory
segment Syntax:
#include <sys/ipc.h>
#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg);
PROGRAME CODE :
#include<stdio.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<sys/ipc.h>
static int pid,semid,shmid,cntid;
char *ptr,*ctr;
struct sembuf sop;
main()
{
int i;
semid=semget((key_t)10,1,IPC_CREAT|0666);
shmid=shmget((key_t)11,100,IPC_CREAT|0666);
cntid=shmget((key_t)12,2,IPC_CREAT|0666);
semctl(semid,0,SETVAL,1);
ptr=(char*)shmat(shmid,0,0);
ctr=(char*)shmat(cntid,0,0);
ctr[i];
pid=fork();
if(pid==0)
{
printf("producer starts \n");
producer();
{
sop.sem_num=0;
sop.sem_op=1;
sop.sem_flg=0;
}
producer()
{
int i=0;
for(i=0;i<5;i++)
{
code1();
semop(semid,&sop,1);
printf("\n producing %d",i);
ptr[i]=i;
ctr[i]++;
code2();
semop(semid,&sop,1);
sleep(4);
}
}
consumer()
{
int i,j=0,var=0;
for(i=0;i<5;i++)
{
code1();
semop(semid,&sop,1);
j=ctr[i];
if(j<=0)
{
code2();
semop(semid,&sop,1);
printf("buffer empty");
sleep(4);
}
else
{
var=ptr[i];
j--;
printf("\n consumer %d",var);
code2();
semop(semid,&sop,1);
sleep(4);
}
}
}
OUTPUT:
[sudha@linuxserver semaphores]$ ./[Link]
producer starts
consumer starts
producing 0
consuming 0
producing 1
consuming 1
producing 2
consuming 2
producing 3
consuming 3
producing 4
producer ends
consuming 4
consumer ends
PROGRAME CODE :
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <pthread.h>
#define SIZE 1024
#define SHMKEY1 (key_t)24
#define SHMKEY2 (key_t)25
#define SEMKEY1 (key_t)26
#define SEMKEY2 (key_t)27
struct databuf
{
int n;
char buf[SIZE];
};
static int wrt, shmidl, readcount, mutex;
struct sembuf sp1,sp2,sv1,sv2;
struct databuf *buff;
char *count;
void writer()
{
semop(wrt,&sp1,1);
printf("\n In the writer process, pid is : %d\n", getpid());
strcpy(buff->buf,"Hello this is writer");
/*strcat(buff->buf,(char*)getpid());*/
printf("\n Writer ended");
semop(wrt,&sv1,1);
}
void reader()
{
char str[100];
semop(mutex,&sp2,1);
printf("\n In reader process, pid is : %d\n", getpid());
count[0]+=1;
if(count[0]==1)
{
semop(wrt,&sp1,1);
}
semop(mutex,&sv2,1);
strcpy(str,buff->buf);
printf("\n no. of readers in critical section are %d ", count[0]);
printf("\n read message is %s, my id =%d",str, getpid());
semop(mutex,&sp2,1);
count[0]-=1;
printf("\n no. of readers in critical section are %d", count[0]);
if(count[0]==0)
{
semop(wrt,&sv1,1);
}
semop(mutex,&sv2,1);
}
int i = 0;
void * threadfunctionread(void* param)
{
printf("\nChild Thread with id %u started\n",pthread_self());
++i;
printf("Now threads are: %d\n", i);
reader();
printf("\nChild Thread with id %u ended\n\n",pthread_self());
pthread_exit(0);
}
void * threadfunctionwrite(void* param)
{
printf("\nChild Thread with id %u started\n",pthread_self());
++i;
printf("Now threads are: %d\n", i);
writer();
printf("\nChild Thread with id %u ended\n\n",pthread_self());
pthread_exit(0);
}
main()
{
int p1,p2;
wrt=semget(SEMKEY1,1,IPC_CREAT|0666);
mutex=semget(SEMKEY2,1,IPC_CREAT|0666);
semctl(wrt,0,SETVAL,1);
semctl(mutex,0,SETVAL,1);
shmidl=shmget(SHMKEY1,sizeof(struct databuf),IPC_CREAT|0666);
readcount=shmget(SHMKEY2,2,IPC_CREAT|0666);
count=(char *)shmat(readcount,0,0);
count[0]=0;
buff=(struct databuf*)shmat(shmidl,0,0);
sp1.sem_num=0;
sp1.sem_op=-1;
sp1.sem_flg=0;
sv1.sem_num=0;
sv1.sem_op=1;
sv1.sem_flg=0;
sp2.sem_num=0;
sp2.sem_op=-1;
sp2.sem_flg=0;
sv2.sem_num=0;
sv2.sem_op=1;
sv2.sem_flg=0;
pthread_t t1, t2, t3, t4, t5;
printf("\nMain thread id is %u\n\n",pthread_self());
pthread_create(&t1, NULL, threadfunctionread, NULL);
pthread_create(&t2, NULL, threadfunctionwrite, NULL);
pthread_create(&t3, NULL, threadfunctionread, NULL);
pthread_create(&t4, NULL, threadfunctionread, NULL);
pthread_create(&t5, NULL, threadfunctionread, NULL);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_join(t4, 0);
pthread_join(t5, 0);
semctl( wrt, 0, IPC_RMID, NULL );
semctl( mutex, 0, IPC_RMID, NULL );
shmctl( shmidl, IPC_RMID, NULL );
shmctl( readcount, IPC_RMID, NULL );
printf("\nMain Thread with id %u ended\n",pthread_self());
}
OUTPUT:
[sudha@linuxserver ~]$ cc rewriters.c -pthread
[sudha@linuxserver ~]$ ./[Link]
Main thread id is 3086821056
Child Thread with id 3086818192 started
Now threads are: 1
In reader process, pid is : 12307
Child Thread with id 3044858768 started
Now threads are: 2
In reader process, pid is : 12307
no. of readers in critical section are 2
read message is , my id =12307
no. of readers in critical section are 1
Child Thread with id 3044858768 ended
Child Thread with id 3055348624 started
Now threads are: 3
In reader process, pid is : 12307
no. of readers in critical section are 2
read message is , my id =12307
no. of readers in critical section are 1
Child Thread with id 3055348624 ended
Child Thread with id 3076328336 started
Now threads are: 4
Child Thread with id 3065838480 started
Now threads are: 5
In reader process, pid is : 12307
no. of readers in critical section are 2
read message is , my id =12307
no. of readers in critical section are 1
Child Thread with id 3065838480 ended
no. of readers in critical section are 1
read message is , my id =12307
no. of readers in critical section are 0
Child Thread with id 3086818192 ended
In the writer process, pid is : 12307
Writer ended
Child Thread with id 3076328336 ended
Main Thread with id 3086821056 ended
PROGRAM DESCRIPTION:
The program implements Dining philosopher problem which is a circular permutation based
synchronization problem using Semaphores and shared [Link] dining-philosophers
problem is considered a classic synchronization because it is an example of a large class of
concurrency-control problems. It is a simple representation of the need to allocate several
resources among several processes in a deadlock-free and starvation-free manner. Consider
five
philosophers who spend their lives thinking and eating. The philosophers share a circular
tablesurrounded by five chairs, each belonging to one philosopher. In the center of the table is
a bowlof rice, and the table is laid with five single chopsticks .When a philosopher thinks, she
does notinteract with her colleagues. From time to time, a philosopher gets hungry and tries to
pick upthe two chopsticks that are closest to her (the chopsticks that are between her and her
left andright neighbors). A philosopher may pick up only one chopstick at a time. Obviously,
she cannotpick up a chopstick that is already in the hand of a neighbor. When a hungry
philosopher hasboth her chopsticks at the same time, she eats without releasing her chopsticks.
When she isfinished eating, she puts down both of her chopsticks and starts thinking again.
One simplesolution is to represent each chopstick with a semaphore. A philosopher tries to grab
a chopstickby executing a wait () operation on that semaphore; she releases her chopsticks by
executing thesignal() operation on the appropriate semaphores. Thus, the shared data are
semaphorechopstick[5]; where all the elements of chopstick are initialized to 1. Use an
asymmetricsolution; that is, an odd philosopher picks up first her left chopstick and then her
right chopstick,
whereas an even philosopher picks up her right chopstick and then her left chopstick
ALGORITHM :
PROGRAME CODE :
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
static int chopstick;
struct sembuf sop;
int main()
{
int p1,p2,p3;
chopstick=semget((key_t)0X25,5,IPC_CREAT|0666);
semctl(chopstick,0,SETVAL,1);
semctl(chopstick,1,SETVAL,1);
semctl(chopstick,2,SETVAL,1);
semctl(chopstick,3,SETVAL,1);
semctl(chopstick,4,SETVAL,1);
p1=fork();
p2=fork();
// printf("%d%d",p1,p2);
if(p1==0)
{
if(p2==0)
{
p3=fork();
if(p3==0)
{
sleep(2);
philosopher(2);
}
else
{
sleep(3);
philosopher(3);
}
}
else
{
sleep(1);
philosopher(4);
}
}
else
{
if(p2==0)
{
sleep(2);
philosopher(1);
}
else
{
sleep(4);
philosopher(0);
}
}}
philosopher(int i)
{
while(1)
{
if(i==0||i==2||i==4)
{
printf("\n philosopher %d is thinking",i);
sleep(5);
wait_b(chopstick,i);
wait_b(chopstick,((i+1)%5));
printf("\n philosopher %d has acquired chopsticks",i);
sleep(5);
printf("\n philosopher %d is eating",i);
sleep(5);
signal_b(chopstick,i);
signal_b(chopstick,((i+1)%5));
printf("\n philosopher %d has released or returned the chopstick",i);
sleep(5);
}
else
{
printf("\n philosopher %d is thinking",i);
sleep(5);
wait_b(chopstick,((i+1)%5));
wait_b(chopstick,i);
printf("\nphilosopher %d has acquired both chopstick",i);
sleep(5);
printf("\nphilospher %d is eating");
sleep(5);
signal_b(chopstick,((i+1)%5));
signal_b(chopstick,i);
printf("\n philosopher %d has released chopsticks",i);
sleep(5);
}
}
}
wait_b(int semid,int semnum)
{
sop.sem_num=semnum;
sop.sem_op=-1;
sop.sem_flg=0;
semop(semid,&sop,1);
}
signal_b(int semid,int semnum)
{
sop.sem_num=semnum;
sop.sem_op=1;
sop.sem_flg=0;
semop(semid,&sop,1);
}
OUTPUT:
[sudha@linuxserver ~]$ ./[Link]
philosopher 4 is thinking
philosopher 2 is thinking
philosopher 2 has acquired chopsticks
philosopher 2 is eating
philosopher 2 has released or returned the chopstick
philosopher 1 is thinking
philosopher 1 has acquired both chopstick
philospher 1 is eating
philosopher 1 has released chopsticks
philosopher 0 is thinking
philosopher 0 has acquired chopsticks
philosopher 0 is eating
philosopher 0 has released or returned the chopstick
philosopher 4 has acquired chopsticks
philosopher 4 has released or returned the chopstick[sudha@linuxserver ~]$
philosopher 3 is thinking
AIM: To write a program to implement Bankers algorithm for Deadlock detection and
avoidance
PROGRAM DESCRIPTION:
ALGORITHM:
Step 2:Obtain the required data through char and int datatypes.
PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
intmain()
count = 0;
scanf("%d", &p);
completed[i] = 0;
scanf("%d", &r);
scanf("%d", &Max[i][j]);
scanf("%d", &alloc[i][j]);
scanf("%d", &avail[i]);
do
printf("\t\t");
printf("\n");
process = -1;
process = i ;
process = -1;
break; } } }
if(process != -1)
break;
if(process != -1)
safeSequence[count] = process + 1;
count++;
avail[j] += alloc[process][j];
alloc[process][j] = 0;
Max[process][j] = 0;
completed[process] = 1;
} }}
if(count == p)
printf(">\n");
} else
OUTPUT
AIM: To write a C program to implement page replacement FIFO (First In First Out)
algorithm
PROGRAM DESCRIPTION
Page replacement is basic to demand paging. It completes the separation between logical
memory and physical memory. With this mechanism, an enormous virtual memory can be
provided for programmers on a smaller physical memory. There are many different page-
replacement algorithms. Every operating system probably has its own replacement scheme. A
FIFO replacement algorithm associates with each page the time when that page was brought
into memory. When a page must be replaced, the oldest page is chosen. If the recent past is
used as an approximation of the near future, then the page that has not been used for the longest
period of time can be replaced. This approach is the Least Recently Used (LRU) algorithm.
LRU replacement associates with each page the time of that page's last use. When a page must
be replaced, LRU chooses the page that has not been used for the longest period of time. Least
frequently used (LFU) page-replacement algorithm requires that the page with the smallest
count be replaced. The reason for this selection is that an actively used page should have a large
reference count.
ALGORITHM:
PROGRAM CODE
#include<stdio.h>
int main()
int i,j,n,a[50],frame[10],no,k,avail,count=0;
scanf("%d",&n);
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
scanf("%d",&no);
for(i=0;i<no;i++)
frame[i]= -1;
j=0;
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\n");
return 0;
output:-
20
7 0 1 2 030423 0321 20 1 7 0 1
7 7 -1 -1
0 7 0 -1
1 7 0 1
2 2 0 1
3 2 3 1
0 2 3 0
4 4 3 0
2 4 2 0
3 4 2 3
0 0 2 3
1 0 1 3
2 0 1 2
7 7 1 2
0 7 0 2
1 7 0 1
Page Fault Is 15
B ) LRU
AIMTo write a C program to implement page replacement LRU (Least Recently Used)
algorithm.
ALGORITHM:
Step 2:Obtain the required data through char and int datatypes.
PROGRAM CODE
#include<stdio.h>
minimum = time[i];
pos = i;
return pos;
int main()
faults = 0;
scanf("%d", &no_of_frames);
scanf("%d", &no_of_pages);
scanf("%d", &pages[i]);
frames[i] = -1;
flag1 = flag2 = 0;
if(frames[j] == pages[i]){
counter++;
time[j] = counter;
flag1 = flag2 = 1;
break;
if(flag1 == 0){
if(frames[j] == -1){
counter++;
faults++;
frames[j] = pages[i];
time[j] = counter;
flag2 = 1;
break;
}} }
if(flag2 == 0){
counter++;
faults++;
frames[pos] = pages[i];
time[pos] = counter;
printf("\n");
printf("%d\t", frames[j]);
}}
return 0;
OUTPUT:
4 -1
-1
47
-1
47
17
17
17
17
12
12
12
C) LFU
#include<stdio.h>
void print(int frameno,int frame[])
{
int j;
for(j=0;j<frameno;j++)
printf("%d\t",frame[j]);
printf("\n");
}
int main()
{
int i,j,k,n,page[50],frameno,frame[10],move=0,flag,count=0,count1[10]={0},
repindex, leastcount;
float rate;
printf("Enter the number of pages\n");
scanf("%d",&n);
printf("Enter the page reference numbers\n");
for(i=0;i<n;i++)
scanf("%d",&page[i]);
printf("Enter the number of frames\n");
scanf("%d",&frameno);
for(i=0;i<frameno;i++)
frame[i]=-1;
printf("Page reference string\tFrames\n");
for(i=0;i<n;i++)
{
printf("%d\t\t\t",page[i]);
flag=0;
for(j=0;j<frameno;j++)
{
if(page[i]==frame[j])
{
flag=1;
count1[j]++;
printf("No replacement\n");
break;
}
}
if(flag==0&&count<frameno)
{
frame[move]=page[i];
count1[move]=1;
move=(move+1)%frameno;
count++;
print(frameno,frame);
}
else if(flag==0)
{
repindex=0;
leastcount=count1[0];
for(j=1;j<frameno;j++)
{
if(count1[j]<leastcount)
{
repindex=j;
leastcount=count1[j];
}
}
frame[repindex]=page[i];
count1[repindex]=1;
count++;
print(frameno,frame);
}
}
rate=(float)count/(float)n;
printf("Number of page faults is %d\n",count);
printf("Fault rate is %f\n",rate);
return 0;
}
Output:
7 7 -1 -1
4 7 4 -1
1 7 4 1
2 2 4 1
3 3 4 1
b) FCFS
#include<stdio.h>
#include <stdlib.h>
int main(){
float avg;
scanf("%d", &q_size);
scanf("%d",&queue[i]);
scanf("%d", &head);
queue[0]=head;
avg = seek/(float)q_size;
return 0;
OUTPUT-
23 1 5 20
Totalseek time is 63
B) SSTF
#include<stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int queue[100], queue2[100], q_size, head, seek=0, temp;
float avg;
printf("%s\n", "-----SSTF Disk Scheduling Algorithm ----- ");
printf("%s\n", "Enter the size of the queue");
scanf("%d", &q_size);
printf("%s\n", "Enter queue elements");
for(int i=0; i<q_size; i++){
scanf("%d",&queue[i]);
}
printf("%s\n","Enter initial head position");
scanf("%d", &head);
//get distance from head of elems in queue
for(int i=0; i<q_size; i++){
queue2[i] = abs(head-queue[i]);
}
//swap elems based on their distance from each other
for(int i=0; i<q_size; i++){
for(int j=i+1; j<q_size;j++){
if(queue2[i]>queue2[j]){
temp = queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
temp=queue[i];
queue[i]=queue[j];
queue[j]=temp;
}
}
}
for(int i=1; i<q_size; i++){
seek = seek+abs(head-queue[i]);
head = queue[i];
}
printf("\nTotal seek time is %d\t",seek);
avg = seek/(float)q_size;
printf("\nAverage seek time is %f\t", avg);
return 0;
}
Output:
-----SSTF Disk Scheduling Algorithm-----
Enter the size of the queue
5
Enter queue elements
20
55
76
43
90
Enter initial head position
35
WEEK 1 QUESTIONS
ASSIGNMENT QUESTIONS
1. Write a C program to implement round robin CPU scheduling algorithm for the
following given scenario. All the processes in the system are divided into two
categories – system processes and user processes.
2. System processes are to be given higher priority than user processes. Consider the
time quantum size for the system processes and user processes to be 5 msec and 2
msec respectively.
3. Write a C program to simulate pre-emptive SJF CPU scheduling algorithm.
WEEK 2 QUESTIONS
1. What is multi-level queue CPU Scheduling?
2. Differentiate between the general CPU scheduling algorithms like FCFS, SJF etc and
multi-level queue CPU Scheduling?
3. What are CPU-bound I/O-bound processes?
4. What are the parameters to be considered for designing a multilevel feedback queue
scheduler?
5. Differentiate multi-level queue and multi-level feedback queue CPU scheduling
algorithms?
6. What are the advantages of multi-level queue and multi-level feedback queue CPU
scheduling algorithms?
ASSIGNMENT QUESTIONS
1. Write a C program to simulate multi-level queue scheduling algorithm considering the
following scenario.
2. All the processes in the system are divided into two categories – system processes and
user processes. System processes are to be given higher priority than user processes.
Consider each process priority to be from 1 to 3. Use priority scheduling for the
processes in each queue.
WEEK 3 QUESTIONS
1. Define file?
2. What are the different kinds of files?
3. What is the purpose of file allocation strategies?
4. Identify ideal scenarios where sequential, indexed and linked file allocation strategies
are most appropriate?
5. What are the disadvantages of sequential file allocation strategy?
6. What is an index block?
7. What is the file allocation strategy used in UNIX?
ASSIGNMENT QUESTIONS
1. Write a C program to simulate a two-level index scheme for file allocation?
WEEK 4 QUESTIONS
1. What is the purpose of memory management unit?
2. Differentiate between logical address and physical address?
3. What are the different types of address binding techniques?
4. What is the basic idea behind contiguous memory allocation?
5. How is dynamic memory allocation useful in multiprogramming operating systems?
6. Differentiate between equal sized and unequal sized MFT schemes?
7. What is the advantage of MVT memory management scheme over MFT?
ASSIGNMENT QUESTIONS
1. Write a C program to simulate MFT memory management scheme with unequal sized
partitions.
WEEK 5 QUESTIONS
1. Differentiate between the memory management schemes MFT and MVT?
2. What is dynamic memory allocation?
3. What is external fragmentation?
4. Which of the dynamic contiguous memory allocation strategies suffer with external
fragmentation?
5. What are the possible solutions for the problem of external fragmentation?
6. What is 50-percent rule?
7. What is compaction?
8. Which of the memory allocation techniques first-fit, best-fit, worst-fit is efficient?
Why?
ASSIGNMENT QUESTIONS
1. Write a C program to implement compaction technique.
WEEK 6 QUESTIONS
1. What are the advantages of noncontiguous memory allocation schemes?
2. What is the process of mapping a logical address to physical address with respect to
the paging memory management technique?
3. Define the terms – base address, offset?
WEEK 7 QUESTIONS
1. Differentiate between paging and segmentation memory allocation techniques?
2. What is the purpose of page table?
3. Whether the paging memory management technique suffers with internal or external
fragmentation problem. Why?
4. What is the effect of paging on the overall context-switching time?
ASSIGNMENT QUESTIONS
1. Write a C program to simulate two-level paging technique.
2. Write a C program to simulate segmentation memory management technique.
WEEK 8 QUESTIONS
1. Define directory?
2. Describe the general directory structure?
3. List the different types of directory structures?
1. Which of the directory structures is efficient? Why?
2. Which directory structure does not provide user-level isolation and protection?
3. What is the advantage of hierarchical directory structure?
ASSIGNMENT QUESTIONS
1. Write a C to simulate acyclic graph directory structure?
2. Write a C to simulate general graph directory structure?
WEEK 8 QUESTIONS
1. Define resource. Give examples.
2. What is deadlock?
3. What are the conditions to be satisfied for the deadlock to occur?
1. How can be the resource allocation graph used to identify a deadlock situation?
2. How is Banker’s algorithm useful over resource allocation graph technique?
3. Differentiate between deadlock avoidance and deadlock prevention?
ASSIGNMENT QUESTIONS
1. Write a C program to implement deadlock detection technique for the following
scenarios?
a. Single instance of each resource type
b. Multiple instances of each resource type
WEEK 9 QUESTIONS
ASSIGNMENT QUESTIONS
1. Write a C program to implement SSTF disk scheduling algorithm?
WEEK 10 QUESTIONS
1. Define the concept of virtual memory?
2. What is the purpose of page replacement?
3. Define the general process of page replacement?
4. List out the various page replacement techniques?
5. What is page fault?
6. Which page replacement algorithm suffers with the problem of Belady’s
anomaly?
7. Define the concept of thrashing? What is the scenario that leads to the situation of
thrashing?
ASSIGNMENT QUESTIONS
1. Write a C program to simulate LRU-approximation page replacement algorithm?
a. Additional-Reference bits algorithm
b. Second-chance algorithm
WEEK 11 QUESTIONS
1. What are the benefits of optimal page replacement algorithm over other page
replacement algorithms?
ASSIGNMENT QUESTIONS
1. Write a C program to simulate producer-consumer problem using message-passing
system.
WEEK 12 QUESTIONS
1. Differentiate between a monitor, semaphore and a binary semaphore?
2. Define clearly the dining-philosophers problem?
3. Identify the scenarios in the dining-philosophers problem that leads to the deadlock
situations?
ASSIGNMENT QUESTIONS
1. Write a C program to simulate readers-writers problem using monitors