You are on page 1of 77

TUTORIAL SHEET

[Date]
OPERATING SYSTEM

PRASHANT KUMAR
2018UCO1534
COE 1
PRASHANT KUMAR
2018UCO1534

INDEX

1.Write program for process creation and


termination for unix operating system ( fork() ,
wait() , exit() ,etc ).
2.Implement producer – consumer problem using
bounded and unbounded buffer.
3.Write a program to illustrate Inter – process
Communication.
4.Implement all the CPU scheduling algorithms
( FCFS , SJFS , priority scheduling , Round
Robin , Multilevel queue scheduling etc )
5.Write a program to illustrate all the algorithms of
critical – section problems
6.Write a program for bounded buffer problem ,
reader writers problem , Dining philosopher
problem using semaphores
7.Solution to Banker’s Algorithm
8.Page Replacement Algorithms
9.Threads
10.File operation system calls ( open, read, close,
append etc.)
11.Disk scheduling algorithms
PRASHANT KUMAR
2018UCO1534

Q1).Write program for process creation and termination for


unix operating system ( fork() , wait() , exit() ,etc ).

● fork():

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
int x;
x=fork();
printf(" \n\t\t Process Id = %d", getpid());
printf(" \n\t\t Returned value = %d\n", x);
return 0;
}

● wait():

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
PRASHANT KUMAR
2018UCO1534

int main()
{
int i,pid;
pid = fork();
if(pid < 0)
{
printf("\n\tProcess creation failure\n");
exit(-1);
}
else if(pid > 0)
{
wait(NULL);
printf ("\n\tParent starts\n\tEven Nos:");
for (i=2; i<=10; i+=2)
printf("%3d",i);
printf("\n\tParent ends\n");
}
else if(pid == 0)
{
printf ("\n\tChild starts\n\tOdd Nos:");
for (i=1; i<10; i+=2)
printf ("%3d",i);
printf ("\n\tChild ends\n");
}
return 0;
}
PRASHANT KUMAR
2018UCO1534

● exec():

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h> // for datatypes
#include<sys/types.h> // for standard symbolic
constants & types
int main(int argc, char *argv[])
{
int ret;
printf("\nProcess Id : %d \n",getpid());
ret=execl("/bin/ls","ls","-l",NULL); // path the
command (ls -l )
printf("failed process is %d",ret);
return 0;
}
PRASHANT KUMAR
2018UCO1534

Q2). Implement producer – consumer problem using


bounded and unbounded buffer.

Unbounded buffer: The consumer may have to wait for new items however the
producer can always produce new items an unbounded buffer places no
practical limit on the size of the buffer.
Bounded buffer: A bounded buffer supposed that there is a fixed buffer size. In
this case the consumer should wait if the buffer is empty and the producer
must wait if the buffer is full.

#include<stdio.h>
#include<stdlib.h>

int mutex=1,full=0,empty=3,x=0;

int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1)
{
PRASHANT KUMAR
2018UCO1534

printf("\nEnter your choice:");


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

return 0;
}

int wait(int s)
{
return (--s);
}

int signal(int s)
PRASHANT KUMAR
2018UCO1534

{
return(++s);
}

void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}

void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}
PRASHANT KUMAR
2018UCO1534

Q3). Write a program to illustrate Inter – process


Communication.

● Producer program
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>

#define FileName "data.dat"


#define DataString "Lorem Ipsum is simply dummy
text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text
ever since the 1500s, when an unknown printer
took a galley of type and scrambled it to make a
type specimen book. It has survived not only five
centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It
was popularised in the 1960s with the release of
Letraset sheets containing Lorem Ipsum passages,
PRASHANT KUMAR
2018UCO1534

and more recently with desktop publishing software


like Aldus PageMaker including versions of Lorem
Ipsum."

void report_and_exit(const char* msg) {


perror(msg);
exit(-1); /* EXIT_FAILURE */
}

int main() {
struct flock lock;
lock.l_type = F_WRLCK; /* read/write (exclusive
versus shared) lock */
lock.l_whence = SEEK_SET; /* base for seek
offsets */
lock.l_start = 0; /* 1st byte in file */
lock.l_len = 0; /* 0 here means 'until EOF' */
lock.l_pid = getpid(); /* process id */

int fd; /* file descriptor to identify a file within a


process */
if ((fd = open(FileName, O_RDWR | O_CREAT,
0666)) < 0) /* -1 signals an error */
report_and_exit("open failed...");

if (fcntl(fd, F_SETLK, &lock) < 0) /** F_SETLK


doesn't block, F_SETLKW does **/
report_and_exit("fcntl failed to get lock...");
else {
PRASHANT KUMAR
2018UCO1534

write(fd, DataString, strlen(DataString)); /*


populate data file */
fprintf(stderr, "Process %d has written to data
file...\n", lock.l_pid);
}

/* Now release the lock explicitly. */


lock.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &lock) < 0)
report_and_exit("explicit unlocking failed...");

close(fd); /* close the file: would unlock if needed


*/
return 0; /* terminating the process would unlock
as well */
}

● Consumer Program

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#define FileName "data.dat"


PRASHANT KUMAR
2018UCO1534

void report_and_exit(const char* msg) {


perror(msg);
exit(-1); /* EXIT_FAILURE */
}

int main() {
struct flock lock;
lock.l_type = F_WRLCK; /* read/write (exclusive)
lock */
lock.l_whence = SEEK_SET; /* base for seek
offsets */
lock.l_start = 0; /* 1st byte in file */
lock.l_len = 0; /* 0 here means 'until EOF' */
lock.l_pid = getpid(); /* process id */

int fd; /* file descriptor to identify a file within a


process */
if ((fd = open(FileName, O_RDONLY)) < 0) /* -1
signals an error */
report_and_exit("open to read failed...");

/* If the file is write-locked, we can't continue. */


fcntl(fd, F_GETLK, &lock); /* sets lock.l_type to
F_UNLCK if no write lock */
if (lock.l_type != F_UNLCK)
report_and_exit("file is still write locked...");

lock.l_type = F_RDLCK; /* prevents any writing


during the reading */
PRASHANT KUMAR
2018UCO1534

if (fcntl(fd, F_SETLK, &lock) < 0)


report_and_exit("can't get a read-only lock...");

/* Read the bytes (they happen to be ASCII codes)


one at a time. */
int c; /* buffer for read bytes */
while (read(fd, &c, 1) > 0) /* 0 signals EOF */
write(STDOUT_FILENO, &c, 1); /* write one
byte to the standard output */

/* Release the lock explicitly. */


lock.l_type = F_UNLCK;
if (fcntl(fd, F_SETLK, &lock) < 0)
report_and_exit("explicit unlocking failed...");

close(fd);
return 0;
}
PRASHANT KUMAR
2018UCO1534

Q4). Implement all the CPU scheduling algorithms ( FCFS ,


SJFS , priority scheduling , Round Robin , Multilevel
queue scheduling etc ) .

● FIRST COME FIRST SERVE CPU Scheduling

#include<stdio.h>
int main()
{
int p[10],bt[10],st[10],ct[10],tat[10],wt[10],i,n;
float sumtat=0,sumwt=0,avwt,avtat;
printf("\n enter the no of processes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n enter the process no and burst time ");
scanf("%d %d",&p[i],&bt[i]);
}
st[0]=0;
wt[0]=0;
ct[0]=st[0]+bt[0];
for(i=0;i<n;i++)
{
st[i+1]=st[i] + bt[i];
ct[i+1]=st[i+1]+ bt[i+1];
}
for(i=0;i<n;i++)
{
tat[i]=ct[i]-0;
sumtat=sumtat + tat[i];
}
PRASHANT KUMAR
2018UCO1534

for(i=0;i<n;i++)
{
wt[i]=tat[i]-bt[i];
sumwt=sumwt + wt[i];
}
printf("\n\t Pno\tbt\tst\tct\ttat\twt\n");
for(i=0;i<n;i++)
{
printf("\n\t%d\t%d\t%d\t%d\t%d\t
%d",p[i],bt[i],st[i],ct[i],tat[i],wt[i]);
}
avtat=sumtat/n;
avwt=sumwt/n;
printf("\n avearge waiting time is %f\n",avwt);
printf("\n average turnaroundtime is %f\n",avtat);

return 0;
}

● SHORTEST JOB FIRST  CPU Scheduling Algorithm


PRASHANT KUMAR
2018UCO1534

#include<stdio.h>
int main()
{
int
p[10],bt[10],st[10],ct[10],tat[10],wt[10],i,j,temp,n;
float sumtat=0,sumwt=0,avwt,avtat;
printf("\n enter the no of processes");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\n enter the process no and burst time ");
scanf("%d %d",&p[i],&bt[i]);
}
for(i=0;i<n;i++)
{ for(j=0;j<n-1;j++)
{ if(bt[j]>bt[j+1])
{
temp=bt[j];
bt[j]=bt[j+1];
bt[j+1]=temp;
}
}
}
st[0]=0;
wt[0]=0;
ct[0]=st[0]+bt[0];
for(i=0;i<n;i++)
{ st[i+1]=st[i] + bt[i];
ct[i+1]=st[i+1]+ bt[i+1];
}
for(i=0;i<n;i++)
{ tat[i]=ct[i]-0;
PRASHANT KUMAR
2018UCO1534

sumtat=sumtat + tat[i];
}
for(i=0;i<n;i++)
{ wt[i]=tat[i]-bt[i];
sumwt=sumwt + wt[i];
}
printf("\n\t Pno\tbt\tst\tct\ttat\twt\n");
for(i=0;i<n;i++)
{ printf("\n\t%d\t%d\t%d\t%d\t%d\t
%d",p[i],bt[i],st[i],ct[i],tat[i],wt[i]); }
avtat=sumtat/n;
avwt=sumwt/n;
printf("\n avearge waiting time is %f\n",avwt);
printf("\n average turnaroundtime is %f\n",avtat);

return 0;
}

● PRIORITY CPU SCHEDULING


PRASHANT KUMAR
2018UCO1534

#include<stdio.h>
int main()
{
int
bt[10],p[10],priority[10],st[10],ct[10],tat[10],wt[10],n,i,
j,temp;
float sumtat=0,sumwt=0,avwt,avtat;
printf("\nPriority Scheduling");
printf("\nEnter Number of Processes:");
scanf("%d",&n);
printf("\nEnter %d Processes Details\n\n",n);
for(i=0; i<n; i++)
{
printf("\nEnter Process %d ID:",i+1);
scanf("%d",&p[i]);
printf("\nEnter Process %d Burst Time:",i+1);
scanf("%d",&bt[i]);
printf("\nEnter Process %d Priority:",i+1);
scanf("%d",&priority[i]);
}

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


{
for(j=0; j<n-1; j++)
{
if(priority[j]>priority[j+1])
{
//Swapping Processes Based on Priority
temp=priority[j];
priority[j]=priority[j + 1];
priority[j + 1]=temp;
PRASHANT KUMAR
2018UCO1534

//Swapping Process ID Accordingly


temp=p[j];
p[j]=p[j + 1];
p[j +1]=temp;
//Swapping Burst Time
temp=bt[j];
bt[j]=bt[j + 1];
bt[j + 1]=temp;
}

}
}

st[0]=0;
wt[0]=0;
ct[0]=st[0]+bt[0];
for(i=0; i<n; i++)
{
st[i+1]=st[i]+bt[i];
ct[i+1]=st[i+1]+bt[i+1];
}

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


{
tat[i]=ct[i] - 0;
sumtat=sumtat+tat[i];
}

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


{
wt[i]=tat[i]-bt[i];
PRASHANT KUMAR
2018UCO1534

sumwt=sumwt+wt[i];
}

printf("\n\tPNO\tPr\tbt\tst\tct\ttat\twt\n");
for(i=0; i<n; i++)
{
printf("\n\t%d\t%d\t%d\t%d\t%d\t%d\t
%d\n",p[i],priority[i],bt[i],st[i],ct[i],tat[i],wt[i]);
}

avtat=sumtat/n;
avwt=sumwt/n;
printf("\n average waiting time is %f\n",avwt);
printf("\n average tutn around time is
%f\n",avtat);
return 0;
}

● ROUND ROBIN CPU SCHEDULING


PRASHANT KUMAR
2018UCO1534

#include<stdio.h>
int main()
{
int st[10],bt[10],wt[10],tat[10],n,tq;
int i,count=0,swt=0,stat=0,temp,sq=0;
float awt=0.0,atat=0.0;

printf("Enter number of processes:");


scanf("%d",&n);
printf("Enter burst time for sequences:");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
st[i]=bt[i];
}
printf("\nEnter time quantum:");
scanf("%d",&tq);
while(1)
{
for(i=0,count=0;i<n;i++)
{
temp=tq;
if(st[i]==0)
{
count++;
continue;
}
if(st[i]>tq)
st[i]=st[i]-tq;
PRASHANT KUMAR
2018UCO1534

else
if(st[i]>=0)
{
temp=st[i];
st[i]=0;
}
sq=sq+temp;
tat[i]=sq;
}
if(n==count)
break;
}
for(i=0;i<n;i++)
{
wt[i]=tat[i]-bt[i];
swt=swt+wt[i];
stat=stat+tat[i];
}
awt=(float)swt/n;
atat=(float)stat/n;
printf("\n\tPno\tBT\tTAT\tWT\n");
for(i=0;i<n;i++)
printf("\n\t%d\t%d\t%d\t%d",i+1,bt[i],tat[i],wt[i]);
printf("\n Avg wait time is %f \n Avg turn around
time is %f\n",awt,atat);
return 0;
}
PRASHANT KUMAR
2018UCO1534

Q5). . Write a program to illustrate all the algorithms of


critical – section problems.

● Peterson algorithm

#include<pthread.h>
#include<stdio.h>
void *func1(void *);
void *func2(void *);
int flag[2];
int turn=0;
int global=100;
int main()
{
pthread_t tid1,tid2;
pthread_create(&tid1,NULL,func1,NULL);
pthread_create(&tid2,NULL,func2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
}

void *func1(void *param)


{
int i=0;
PRASHANT KUMAR
2018UCO1534

while(i<2)
{
flag[0]=1;
turn=1;
while(flag[1]==1 && turn==1);
global+=100;
printf("\tFT: g: %d\n",global);
flag[0]=0;
i++;
}
}
void *func2(void *param)
{
int i=0;
while(i<2)
{
flag[1]=1;
turn=0;
while(flag[0]==1 && turn==0);
global-=75;
printf("\tSP: g: %d\n",global);
flag[1]=0;
i++;
}
}
PRASHANT KUMAR
2018UCO1534

● Dekker's algorithm

#include <iostream>
#include <pthread.h>

volatile bool flag0;


volatile bool flag1;
volatile int turn;

long count;
long count0;
long count1;
const long limit = 10*1000*1000;

void* f0(void *arg) {


while (true) {
// acquire
flag0 = true;
__sync_synchronize(); // mfence
while (flag1) {
if (turn != 0) {
flag0 = false;
while (turn != 0) {
}
flag0 = true;
}
__sync_synchronize(); // mfence
}
// critical section
++count0;
++count;
PRASHANT KUMAR
2018UCO1534

// yield
turn = 1;
flag0 = false;
__sync_synchronize(); // mfence
// exit
if (count0 == limit)
return 0;
}
}

void* f1(void *arg) {


while (true) {
// acquire
flag1 = true;
__sync_synchronize(); // mfence
while (flag0) {
if (turn != 1) {
flag1 = false;
while (turn != 1) {
}
flag1 = true;
}
__sync_synchronize(); // mfence
}
// critical section
++count1;
++count;
// yield
turn = 0;
flag1 = false;
__sync_synchronize(); // mfence
PRASHANT KUMAR
2018UCO1534

// exit
if (count1 == limit)
return 0;
}
}

int main(int argc, char** argv) {


pthread_t t0, t1;

pthread_create(&t0, 0, f0, 0);


pthread_create(&t1, 0, f1, 0);
pthread_join(t0, 0);
pthread_join(t1, 0);
std::cout << count << std::endl;
return 0;
}

● Bakery Algorithm ( N process solution )

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define COUNT 2
static int Entering[ COUNT ], Number[ COUNT ]; /*
Global variables for Lamport's bakery algorithm. */
PRASHANT KUMAR
2018UCO1534

int max ( int* arr )


{
int i, max = arr[ 0 ];
for ( i = 1 ; i < COUNT ; i++ )
if ( Number[ i ] > max )
return Number[ i ];
return Number[ 0 ];
}

static void* T1 ( void* args )


{
pthread_detach( pthread_self() ); /*
Guarantees that thread resources are deallocated
upon return. */
int i = 0, j;
while ( 1 )
{
/* Request to enter critical section. */
Entering[ i ] = 1;
Number[ i ] = 1 + max( Number );
Entering[ i ] = 0;
for ( j = 0 ; j < COUNT ; j++ )
{
while ( Entering[ j ] ) {}
while ( Number[ j ] != 0 && ( Number[ j ] <
Number[ i ] || ( Number[ j ] == Number[ i ] && j <
i ) ) ) {}
}

/* Critical section. */
printf( "Thread ID: %d START!\n", i );
PRASHANT KUMAR
2018UCO1534

for ( j = 0 ; j < 0xFFFFFF ; j++ ) {}


printf( "Thread ID: %d END!\n", i );

/* End of critical section. */


Number[ i ] = 0;
}
return NULL;
}

static void* T2 ( void* args )


{
pthread_detach( pthread_self() ); /*
Guarantees that thread resources are deallocated
upon return. */
int i = 1, j;
while ( 1 )
{
/* Request to enter critical section. */
Entering[ i ] = 1;
Number[ i ] = 1 + max( Number );
Entering[ i ] = 0;
for ( j = 0 ; j < COUNT ; j++ )
{
while ( Entering[ j ] ) {}
while ( Number[ j ] != 0 && ( Number[ j ] <
Number[ i ] || ( Number[ j ] == Number[ i ] && j <
i ) ) ) {}
}

/* Critical section. */
printf( "Thread ID: %d START!\n", i );
PRASHANT KUMAR
2018UCO1534

for ( j = 0 ; j < 0xFFFFFF ; j++ ) {}


printf( "Thread ID: %d END!\n", i );

/* End of critical section. */


Number[ i ] = 0;
}
return NULL;
}

int main ()
{
int i = 0;
pthread_t t1;

/* Initial Bakery algorithm. */


for ( i = 0 ; i < COUNT ; i++ )
Number[ i ] = Entering[ i ] = 0;

/* Thread Creation. */
if ( pthread_create( &t1, NULL, T1, NULL ) )
exit( -1 );
if ( pthread_create( &t1, NULL, T2, NULL ) )
exit( -1 );

/* Loop forever. */
while ( 1 ) {}
return EXIT_SUCCESS;
}
PRASHANT KUMAR
2018UCO1534

Q6). Write a program for bounded buffer problem , reader


writers problem , Dining philosopher problem using
semaphores.

● Bounded Buffer problem

#include<stdio.h>
#include<stdlib.h>

int mutex=1,full=0,empty=3,x=0;

int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer\n2.Consumer\n3.Exit");
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&n);
PRASHANT KUMAR
2018UCO1534

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

return 0;
}

int wait(int s)
{
return (--s);
}

int signal(int s)
{
return(++s);
PRASHANT KUMAR
2018UCO1534

void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
mutex=signal(mutex);
}

void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}

● Dining philosopher
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include <unistd.h>
#include<iostream>

#define N 5
PRASHANT KUMAR
2018UCO1534

#define THINKING 0
#define HUNGRY 1
#define EATING 2
#define LEFT (ph_num+4)%N
#define RIGHT (ph_num+1)%N

sem_t mutex;
sem_t S[N];

void * philospher(void *num);


void take_fork(int);
void put_fork(int);
void test(int);

int state[N];
int phil_num[N]= {0,1,2,3,4};

int main()
{
int i;
pthread_t thread_id[N];
sem_init(&mutex,0,1);
for(i=0; i<N; i++)
sem_init(&S[i],0,0);
for(i=0; i<N; i++)
{

pthread_create(&thread_id[i],NULL,philospher,&phil
_num[i]);
printf("Philosopher %d is thinkingn",i+1);
}
PRASHANT KUMAR
2018UCO1534

for(i=0; i<N; i++)


pthread_join(thread_id[i],NULL);
}

void *philospher(void *num)


{
while(1)
{
int *i = (int*)num;
sleep(1);
take_fork(*i);
sleep(0);
put_fork(*i);
}
}

void take_fork(int ph_num)


{
sem_wait(&mutex);
state[ph_num] = HUNGRY;
printf("Philosopher %d is Hungryn",ph_num+1);
test(ph_num);
sem_post(&mutex);
sem_wait(&S[ph_num]);
sleep(1);
}

void test(int ph_num)


{
PRASHANT KUMAR
2018UCO1534

if (state[ph_num] == HUNGRY &&


state[LEFT] != EATING && state[RIGHT] !=
EATING)
{
state[ph_num] = EATING;
sleep(2);
printf("Philosopher %d takes fork %d and
%dn",ph_num+1,LEFT+1,ph_num+1);
printf("Philosopher %d is Eatingn",ph_num+1);
sem_post(&S[ph_num]);
}
}

void put_fork(int ph_num)


{
sem_wait(&mutex);
state[ph_num] = THINKING;
printf("Philosopher %d putting fork %d and %d
downn",ph_num+1,LEFT+1,ph_num+1);
printf("Philosopher %d is
thinkingn",ph_num+1);
test(LEFT);
test(RIGHT);
sem_post(&mutex);
}
PRASHANT KUMAR
2018UCO1534

● Reader Writers problem

#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
#include<iostream>
sem_t mutex,writeblock;
int data = 0,rcount = 0;

void *reader(void *arg)


{
int f;
f = *((int*)(&arg));
sem_wait(&mutex);
rcount = rcount + 1;
if(rcount==1)
sem_wait(&writeblock);
PRASHANT KUMAR
2018UCO1534

sem_post(&mutex);
printf("Data read by the reader%d is
%d\n",f,data);
sleep(1);
sem_wait(&mutex);
rcount = rcount - 1;
if(rcount==0)
sem_post(&writeblock);
sem_post(&mutex);
}

void *writer(void *arg)


{
int f;
f = *((int*)(&arg));
sem_wait(&writeblock);
data++;
printf("Data writen by the writer%d is
%d\n",f,data);
sleep(1);
sem_post(&writeblock);
}

main()
{
int i,b;
pthread_t rtid[5],wtid[5];
sem_init(&mutex,0,1);
sem_init(&writeblock,0,1);
for(i=0; i<=2; i++)
{
PRASHANT KUMAR
2018UCO1534

pthread_create(&wtid[i],NULL,writer,(void *)i);
pthread_create(&rtid[i],NULL,reader,(void *)i);
}
for(i=0; i<=2; i++)
{
pthread_join(wtid[i],NULL);
pthread_join(rtid[i],NULL);
}
}
PRASHANT KUMAR
2018UCO1534

7. Solution to Banker’s Algorithm

#include&lt;iostream&gt;
#include&lt;vector&gt;
#include&lt;cmath&gt;
#include&lt;algorithm&gt;
#include&lt;string&gt;
#include&lt;stack&gt;
#include&lt;string.h&gt;
#include&lt;utility&gt;

using namespace std;


const int P = 5,R = 3;
void calculateNeed(int need[P][R],int maxm[P][R],int
allot[P][R])
{
for (int i = 0 ; i &lt; P ; i++)
{
for (int j = 0 ; j &lt; R ; j++)
need[i][j] = maxm[i][j] - allot[i][j];
}
}
bool isSafe(int processes[],int avail[],int maxm[][R],int
allot[][R])
{
int need[P][R];
calculateNeed(need, maxm, allot);
bool finish[P] = {0};
PRASHANT KUMAR
2018UCO1534

int safeSeq[P];
int work[R];
int count = 0;
for (int i = 0; i &lt; R ; i++)
work[i] = avail[i];
while (count &lt; P)
{
bool found = false;
for (int p = 0; p &lt; P; p++)
{
if (finish[p] == 0)
{

int j;
for (j = 0; j &lt; R; j++)
if (need[p][j] &gt; work[j])
break;
if (j == R)
{
for (int k = 0 ; k &lt; R ; k++)
work[k] += allot[p][k];
safeSeq[count++] = p;
finish[p] = 1;
found = true;
}
}
}
if (found == false)
PRASHANT KUMAR
2018UCO1534

{
cout &lt;&lt; &quot;System is not in safe state&quot;;
return false;
}
}
cout &lt;&lt; &quot;System is in safe state.\nSafe
sequence is: &quot;;
for (int i = 0; i &lt; P ; i++)
cout &lt;&lt; safeSeq[i] &lt;&lt; &quot; &quot;;
cout&lt;&lt;&quot;\n&quot;;
return true;
}
int main()
{
int processes[] = {0, 1, 2, 3, 4};

int avail[] = {3, 3, 2};


int maxm[][R] = {{7, 5, 3},{3, 2, 2},{9, 0, 2},{2, 2, 2},{4,
3, 3}};
int allot[][R] = {{0, 1, 0},{2, 0, 0},{3, 0, 2},{2, 1, 1},{0, 0,
2}};
for(int i=0;i&lt;P;i++)
{
cout&lt;&lt;&quot;max resources needed by Process
&quot;&lt;&lt;i&lt;&lt;&quot;:
&quot;;
for(int j=0;j&lt;R;j++)
cout&lt;&lt;maxm[i][j]&lt;&lt;&quot; &quot;;
PRASHANT KUMAR
2018UCO1534

cout&lt;&lt;endl;
cout&lt;&lt;&quot;alloted resources to Process
&quot;&lt;&lt;i&lt;&lt;&quot;: &quot;;
for(int j=0;j&lt;R;j++)
cout&lt;&lt;allot[i][j]&lt;&lt;&quot;
cout&lt;&lt;endl;
}
isSafe(processes, avail, maxm, allot);
return 0;
}
PRASHANT KUMAR
2018UCO1534

8:Page Replacement Algorithms

● LRU
#include<stdio.h>
void main()
{
int
frames[10],n,seq[30],c=0,i,j,n1,x=0,m,k=0,flag=0,l,fc
[10],r;
printf("\n enter number of pages : ");
scanf("%d",&n1);
printf("\n enter the pages : ");
for(i=0;i<n1;i++)
scanf("%d",&seq[i]);
printf("enter the number of frames:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
frames[i]=-1;
fc[i]=0;
}
for(x=0,i=0;x<n;i++)
{
for(j=0;j<n;j++)
{
flag=0;
if(seq[i]==frames[j])
{
PRASHANT KUMAR
2018UCO1534

flag=1;
k++;
fc[j]=k;
break;
}
}
if(flag==0)
{
frames[x]=seq[i];
m=i;
c=c+1;
k++;
fc[x]=k;
x++;
printf("\n \n");
for(l=0;l<x;l++)
printf("\t %d",frames[l]);
}
}
for(i=m+1;i<n1;i++)
{
for(j=0;j<n;j++)
{
flag=0;
if(seq[i]==frames[j])
{
flag=1;
k++;
fc[j]=k;
PRASHANT KUMAR
2018UCO1534

break;
}
}
if(flag==0)
{
r=fc[0];
j=0;
for(l=1;l<n;l++)
{
if(r>fc[l])
{
r=fc[l];
j=l;
}
}
frames[j]=seq[i];
k++;
fc[j]=k;
c=c+1;
printf("\n \n");
for(l=0;l<n;l++)
printf("\t %d",frames[l]);
}
}
printf("\n \n the no of pages faults:%d",c);
}
PRASHANT KUMAR
2018UCO1534

● FIFO
#include<stdio.h>
void main()
{
int frames[10],n,seq[30],c=0,i,j,n1,x=0,m,k,flag=0,l;
printf("\n enter the number of pages : ");
scanf("%d",&n1);
printf("\n enter the pages : ");
for(i=0;i<n1;i++)
scanf("%d",&seq[i]);
printf("enter the number of frames : ");
scanf("%d",&n);
for(i=0;i<n;i++)
frames[i]=-1;
for(x=0,i=0;x<n;i++)
{
for(j=0;j<n;j++)
PRASHANT KUMAR
2018UCO1534

{
flag=0;
if(seq[i]==frames[j])
{
flag=1;
break;
}
}

if(flag==0)
{
frames[x]=seq[i];
m=i;
x++;
c=c+1;
printf("\n\n");
for(k=0;k<x;k++)
printf("\t %d",frames[k]);
}
}
k=0;
for(i=m+1;i<n1;i++)
{
if(k==n)
k=0;
for(j=0;j<n;j++)
{
flag=0;
if(seq[i]==frames[j])
PRASHANT KUMAR
2018UCO1534

{
flag=1;break;
}
}
if(flag==0)
{
frames[k]=seq[i];
k++;
c=c+1;
printf("\n \n");
for(l=0;l<n;l++)
printf("\t %d",frames[l]);
}
}
printf("\n \n the no of page faults = %d",c);
}
PRASHANT KUMAR
2018UCO1534

● OPTIMAL
#include<stdio.h>
main()
{
int
frames[10],n,seq[30],c=0,i,j,nl,x=0,m,k,flag=0,l,mf[1
0];
int c1,c2,c3,m1,m2;
printf("enter number of pages:");
scanf("%d",&nl);
printf("\n enter pages:");
for(i=0;i<nl;i++)
scanf("%d",&seq[i]);
printf("\n enter no of frames:");
scanf("%d",&n);
for(i=0;i<n;i++)
frames[i]=-1;
for(x=0,i=0;x<n;i++)
{
for(j=0;j<n;j++)
{
flag=0;
if(seq[i]==frames[j])
{
flag=1;
break;
}
}
PRASHANT KUMAR
2018UCO1534

if(flag==0)
{
frames[x]=seq[i];
m=i;
x++;
c=c+1;
printf("\n \n");
for(k=0;k<x;k++)
printf("\t %d",frames[k]);
}
}
for(i=m+1;i<nl;i++)
{
for(j=0;j<n;j++)
{
flag=0;
if(seq[i]==frames[j])
{
flag=1;
break;
}
}
if(flag==0)
{
for(k=0;k<n;k++)
mf[k]=0;
c1=0;c2=0;c3=0;
for(j=i+1;j<nl;j++)
{
PRASHANT KUMAR
2018UCO1534

for(k=0;k<n;k++)
{
if(frames[k]==seq[j])
{
mf[k]=mf[k]+1;
if(k==0)
c1=1;
else if(k==1)
c2=1;
else if(k==2)
c3=1;
break;
}
}
if(((c1==1)&&(c2==1))||((c2==1)&&(c3==1))||
((c3==1)&&(c1==1)))
break;
}
m1=0;
m2=mf[0];
for(k=0;k<n;k++)
{
if(mf[k]<m2)
{
m1=k;
m2=mf[k];
}
}
frames[m1]=seq[i];
PRASHANT KUMAR
2018UCO1534

c=c+1;
printf("\n \n");
for(l=0;l<n;l++)
printf("\t %d",frames[l]);
}
}
printf("\n\n\n the n of pages faults=%d",c);
}

Q9).Threads
● Single Thread
#include <pthread.h>
#include <stdio.h>
#include<unistd.h>
void start()
{
printf("In Start()\n");
sleep(2);
}

int main()
PRASHANT KUMAR
2018UCO1534

{
start();
start();
start();
start();
start();
return 0;
}


● Multi Threading
#include <pthread.h>
#include <stdio.h>
#include<unistd.h>
void * start(void *)
{
printf("In Start()\n");
sleep(2);
return NULL;
}
int main()
{
pthread_t thread1;
PRASHANT KUMAR
2018UCO1534

pthread_t thread2;
pthread_t thread3;
pthread_t thread4;
pthread_t thread5;
pthread_create(&thread1, NULL, start, NULL);
pthread_create(&thread2, NULL, start, NULL);
pthread_create(&thread3, NULL, start, NULL);
pthread_create(&thread4, NULL, start, NULL);
pthread_create(&thread5, NULL, start, NULL);

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
pthread_join(thread4, NULL);
pthread_join(thread5, NULL);
return 0;
}

Q10).File operation system calls ( open, read, close,


append etc.)
● Write
PRASHANT KUMAR
2018UCO1534

//This program contains write(), open() and


close file operation
# include <stdio.h>
# include <string.h>

int main( )
{
FILE *filePointer ;
char dataToBeWritten[50]
= "Hello there!";
filePointer = fopen("file.txt", "w") ;

if ( filePointer == NULL )
{
printf( "Failed to open file." ) ;
}
else
{
if ( strlen ( dataToBeWritten ) > 0 )
{

fputs(dataToBeWritten, filePointer) ;
fputs("\n", filePointer) ;
}

fclose(filePointer) ;
printf("Data successfully written in file \n");
printf("The file is now closed.") ;
}
PRASHANT KUMAR
2018UCO1534

return 0;
}

● Read
//This program contains read(),open() and close
file operation
# include <stdio.h>
# include <string.h>

int main( )
{
FILE *filePointer ;
char dataToBeRead[50];
filePointer = fopen("file.txt", "r") ;
if ( filePointer == NULL )
{
printf( "Failed to open file" ) ;
}
else
{
printf("\nData successfully read from file and
the data readed is : \n");
while( fgets ( dataToBeRead, 50, filePointer ) !
= NULL )
{
PRASHANT KUMAR
2018UCO1534

printf( "%s" , dataToBeRead ) ;


}
fclose(filePointer) ;

printf("\nThe file is now closed.") ;


}
return 0;
}

● Append
//This program contains append(),open() and
close file operation
#include <stdio.h>
#include <stdlib.h>
#define BUFFER_SIZE 1000
void readFile(FILE * fPtr);
int main()
{
FILE *fPtr;
char dataToAppend[BUFFER_SIZE];
fPtr = fopen("file.txt", "a");
if (fPtr == NULL)
PRASHANT KUMAR
2018UCO1534

{
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you
have write privilege.\n");
exit(EXIT_FAILURE);
}
printf("\nEnter data to append: ");
fflush(stdin);
fgets(dataToAppend, BUFFER_SIZE, stdin);
fputs(dataToAppend, fPtr);
printf("\nSuccessfully appended data to file.
\n");
fPtr = freopen("file.txt", "r", fPtr);
printf("Changed file contents:\n\n");
readFile(fPtr);
fclose(fPtr);
return 0;
}
void readFile(FILE * fPtr)
{
char ch;

do
{
ch = fgetc(fPtr);

putchar(ch);

} while (ch != EOF);


PRASHANT KUMAR
2018UCO1534

Q11). Disk scheduling algorithms


● C-LOOK
#include <stdio.h>
#include <stdlib.h>

#define LOW 0
#define HIGH 199

int main(){
int queue[20], head, q_size, i,j, seek=0, diff, max,
min, range, temp, queue1[20], queue2[20],
temp1=0, temp2=0;
PRASHANT KUMAR
2018UCO1534

float avg;

printf("%s\t", "Input the number of disk locations");


scanf("%d", &q_size);

printf("%s\t", "Enter initial head position");


scanf("%d", &head);

printf("%s\n", "Enter disk positions to read");

for(i=0; i<q_size; i++){


scanf("%d", &temp);
if(temp >= head){
queue1[temp1] = temp;
temp1++;
} else {
queue2[temp2] = temp;
temp2++;
}
}

for(i=0; i<temp1-1; i++){


for(j=i+1; j<temp1; j++){
if(queue1[i] > queue1[j]){
temp = queue1[i];
queue1[i] = queue1[j];
queue1[j] = temp;
}
}
PRASHANT KUMAR
2018UCO1534

}
for(i=0; i<temp2-1; i++){
for(j=i+1; j<temp2; j++){
if(queue2[i] > queue2[j]){
temp = queue2[i];
queue2[i] = queue2[j];
queue2[j] = temp;
}
}
}

if(abs(head-LOW) <= abs(head-HIGH)){

for(i=1,j=temp2-1; j>=0; i++,j--){


queue[i] = queue2[j];
}

queue[i] = LOW;
queue[i+1] = HIGH;

for(i=temp2+3,j=temp1-1; j>=0; i++,j--){


queue[i] = queue1[j];
}

} else {

for(i=1,j=0; j<temp1; i++,j++){


queue[i] = queue1[j];
}
PRASHANT KUMAR
2018UCO1534

queue[i] = HIGH;
queue[i+1] = LOW;

for(i=temp1+3,j=0; j<temp2; i++,j++){


queue[i] = queue2[j];
}

}
queue[0] = head;

for(j=0; j<q_size; j++){


diff=abs(queue[j+1] - queue[j]);
seek += diff;
printf("Disk head moves from %d to %d with
seek %d\n",queue[j],queue[j+1],diff);

printf("Total seek time is %d\n", seek);


avg = seek/(float)q_size;
printf("Average seek time is %f\n", avg);

return 0;
}
PRASHANT KUMAR
2018UCO1534

● C-SCAN
#include <stdlib.h>
#include <stdio.h>
#define HIGH 199
#define LOW 0

int main(){
int queue[20], q_size, head, i,j, seek=0, diff, max,
temp, queue1[20], queue2[20], temp1=0, temp2=0;
float avg;

printf("%s\t", "Input no of disk locations");


scanf("%d", &q_size);

printf("%s\t", "Enter initial head position");


scanf("%d", &head);

printf("%s\n","Enter disk positions to be read");


for(i=0; i<q_size; i++) {

scanf("%d", &temp);
PRASHANT KUMAR
2018UCO1534

if(temp >= head){


queue1[temp1] = temp;
temp1++;
} else {
queue2[temp2] = temp;
temp2++;
}
}
for(i=0; i<temp1-1; i++){
for(j=i+1; j<temp1; j++){
if(queue1[i] > queue1[j]){
temp = queue1[i];
queue1[i] = queue1[j];
queue1[j] = temp;
}
}
}

for(i=0; i<temp2-1; i++){


for(j=i+1; j<temp2; j++){
if(queue2[i]>queue2[j]){
temp = queue2[i];
queue2[i] = queue2[j];
queue2[j] = temp;
}
}
}

//calculate closest edge


PRASHANT KUMAR
2018UCO1534

if(abs(head-LOW) >= abs(head-HIGH)){

for(i=1,j=0; j<temp1; i++,j++){


queue[i] = queue1[j];
}

queue[i] = HIGH;
queue[i+1] = 0;

for(i=temp1+3, j=0; j<temp2; i++, j++){


queue[i] = queue2[j];
}

} else {

for(i=1,j=temp2-1; j>=0; i++,j--){


queue[i] = queue2[j];
}

queue[i] = LOW;
queue[i+1] = HIGH;

for(i=temp2+3, j=temp1-1; j>=0; i++, j--){


queue[i] = queue1[j];
}
}

queue[0] = head;
PRASHANT KUMAR
2018UCO1534

for(j=0; j<=q_size+1; j++){


diff=abs(queue[j+1] - queue[j]);
seek += diff;
printf("Disk head moves from %d to %d with
seek %d\n",queue[j],queue[j+1],diff);

printf("Total seek time is %d\n", seek);


avg = seek/(float)q_size;
printf("Average seek time is %f\n", avg);

return 0;
}

● FCFS
#include <stdio.h>
#include <stdlib.h>
PRASHANT KUMAR
2018UCO1534

int main(){
int queue[100], q_size, head, seek =0, diff;
float avg;

printf("%s\n", "***FCFS 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=1; i<=q_size; i++){
scanf("%d",&queue[i]);
}

printf("%s\n","Enter initial head position");


scanf("%d", &head);

queue[0]=head;

for(int j=0; j<=q_size-1; j++){


diff = abs(queue[j]-queue[j+1]);
seek += diff;
printf("Move from %d to %d with Seek
%d\n",queue[j],queue[j+1],diff);
}

printf("\nTotal seek time is %d\t",seek);


PRASHANT KUMAR
2018UCO1534

avg = seek/(float)q_size;
printf("\nAverage seek time is %f\t", avg);

return 0;
}

● LOOK
#include <stdio.h>
#include <stdlib.h>
#define LOW 0
#define HIGH 199

int main(){
int queue[20], head, q_size, i,j, seek=0, diff, max,
temp, queue1[20], queue2[20], temp1=0, temp2=0;
float avg;
PRASHANT KUMAR
2018UCO1534

printf("%s\t", "Input the number of disk locations");


scanf("%d", &q_size);

printf("%s\t", "Enter initial head position");


scanf("%d", &head);

printf("%s\n", "Enter disk positions to read");

for(i=0; i<q_size; i++){


scanf("%d", &temp);
if(temp >= head){
queue1[temp1] = temp;
temp1++;
} else {
queue2[temp2] = temp;
temp2++;
}
}

for(i=0; i<temp1-1; i++){


for(j=i+1; j<temp1; j++){
if(queue1[i] > queue1[j]){
temp = queue1[i];
queue1[i] = queue1[j];
queue1[j] = temp;
}
}
}
PRASHANT KUMAR
2018UCO1534

//sort queue2 - decreasing order


for(i=0; i<temp2-1; i++){
for(j=i+1; j<temp2; j++){
if(queue2[i] < queue2[j]){
temp = queue2[i];
queue2[i] = queue2[j];
queue2[j] = temp;
}
}
}

if(abs(head-LOW) >= abs(head-HIGH)){

for(i=1,j=0; j<temp1; i++,j++){


queue[i] = queue1[j];
}

for(i=temp1+1, j=0; j<temp2; i++, j++){


queue[i] = queue2[j];
}

} else {

for(i=1,j=0; j<temp2; i++,j++){


queue[i] = queue2[j];
}

for(i=temp2+1, j=0; j<temp1; i++, j++){


PRASHANT KUMAR
2018UCO1534

queue[i] = queue1[j];
}

queue[0] = head;

for(j=0; j<q_size; j++){


diff=abs(queue[j+1] - queue[j]);
seek += diff;
printf("Disk head moves from %d to %d with
seek %d\n",queue[j],queue[j+1],diff);

printf("Total seek time is %d\n", seek);


avg = seek/(float)q_size;
printf("Average seek time is %f\n", avg);

return 0;
}
PRASHANT KUMAR
2018UCO1534

● SCAN
#include <stdio.h>
#include <stdlib.h>

#define LOW 0
#define HIGH 199

int main(){
int queue[20];
int head, max, q_size, temp, sum;
int dloc;
printf("%s\t", "Input no of disk locations");
scanf("%d", &q_size);

printf("%s\t", "Enter head position");


scanf("%d", &head);

printf("%s\n", "Input elements into disk queue");


for(int i=0; i<q_size; i++){
scanf("%d", &queue[i]);
}
queue[q_size] = head;
q_size++;

for(int i=0; i<q_size;i++){


for(int j=i; j<q_size; j++){
if(queue[i]>queue[j]){
temp = queue[i];
PRASHANT KUMAR
2018UCO1534

queue[i] = queue[j];
queue[j] = temp;
}
}
}
max = queue[q_size-1];
for(int i=0; i<q_size; i++){
if(head == queue[i]){
dloc = i;
break;
}
}

if(abs(head-LOW) <= abs(head-HIGH)){

for(int j=dloc; j>=0; j--){


printf("%d --> ",queue[j]);
}
for(int j=dloc+1; j<q_size; j++){
printf("%d --> ",queue[j]);
}

} else {

for(int j=dloc+1; j<q_size; j++){


printf("%d --> ",queue[j]);
}
for(int j=dloc; j>=0; j--){
printf("%d --> ",queue[j]);
PRASHANT KUMAR
2018UCO1534

}
sum = head + max;
printf("\nmovement of total cylinders %d", sum);

return 0;
}

● 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);
PRASHANT KUMAR
2018UCO1534

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);
for(int i=0; i<q_size; i++){
queue2[i] = abs(head-queue[i]);
}
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]=queue[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;
PRASHANT KUMAR
2018UCO1534

printf("\nAverage seek time is %f\t", avg);


return 0;
}

You might also like