Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views29 pages

Assignment of Os

The document outlines a series of practical programming exercises focused on process communication, multithreading, synchronization, and scheduling algorithms, which can be implemented in Java or C. It includes solutions to the producer-consumer problem using both shared memory and message passing, as well as examples of multithreaded programs for summation and prime number generation. Additionally, it covers synchronization problems like the readers-writers problem and the sleeping barber problem, along with scheduling algorithms such as FCFS and SJF.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
18 views29 pages

Assignment of Os

The document outlines a series of practical programming exercises focused on process communication, multithreading, synchronization, and scheduling algorithms, which can be implemented in Java or C. It includes solutions to the producer-consumer problem using both shared memory and message passing, as well as examples of multithreaded programs for summation and prime number generation. Additionally, it covers synchronization problems like the readers-writers problem and the sleeping barber problem, along with scheduling algorithms such as FCFS and SJF.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 29
List of Practicals Practical can be implemented either in JAVA or any other programming language. (Any 8) > Here we use ¢ language 1 Practical + Process Communication (0 Give solution to the producer-consumer problem using shared memory. Solution : Producer consumer problem is also called as bounded buffer problem. Here we take two processes as, producer1 and consumer, who share a fixed size buffer. Producer work is to produce data of items and put in buffer. Consumer work is to remove data from buffer and consume it. Note that producer do not produce data when buffer is full and consumer do not remove data When buffer is empty. #include #include int mutex=1, full=0,empty=3, x=0; int mainQ. { int n; void producer1(); Void consumeriQ; int wait(int); int signal(int); printf("\n1.Producer\n2,Consumer\n3.Exit"); while(1) { printf("\nEnter your choice:"); scanf("%d",8n); switch(n) { )&&(empty!=0)) producer1(); else printf("Buffer is fulll!"); break; 4 case 2: if{(mutex==1)&&(fulll=0)), system consumer (); else Printf("Butfer is empryit, break; case 3 exit(Q); break; return 0; int wait(int s) { return (~~s); } int signal(int s) { return(++s); } void produceri() { mutex=wait{mutex); full=signal(full); empty=wait(empty); xeey printf("\nProducer produces the item %d"x); mutexssignal(mutex); } ¥oid consumer1() { mutex=wait(mutex); full=wait(full); empty=signal(empty); Printf("\nConsumer consumes item %d".x); Xe mutexssignal(mutex); Co eee SS a Oberating system pea radticaly Output 1 Producer 2.Consumer B.Bxit Enter your choice:1 Producer produces the item 1 Enter your choice:2 Consumer consumes item 1 Enter your choice:2 Buffer is empty!! Enter your choice:t Producer produces the item 1 Enter your choice:1 Producer produces the item 2 Enter your choice:1 Producer produces the item 3 Enter your choice:1 Buffer is full! Enter your choice:3 Gi) Give solution to the producer-consumer problem using message passing Solution : Message passing is a method of inter process communication used in parallel programming systems. It uses two function calls: send and receive for sending and receiving messages. In this method, a receiver sends acknowledgement message to the sender when a message is received. The concept of acknowledgement message is used for making sure that the messages are not lost. A mailbox is used for holding the messages. Following code should be further implemented in java or any suitable language. ‘#tdefine MAX 100 void producer(void) { int item; message mesg; while (TRUE) { item = produce_item(); receive{consumer, &mesg); create_message(&mesg, item); send(consumer, &mesg); } } void consumer(vold) 1 Antitem, i; syste aun — mressage mes 12 0:1 < MAK: producer, &mesg); ++) jor send while (TRUE) ( receive(producer, &mesg); item = extract jtem(&mesg); send(producer, &mesg); consume_item(item); } practical 2: Threads {i) The Java version of a multithreaded program that determines the summation of a non-negative integer. ‘The Summation class implements the Runnable interface. Thread creation is performed by creating an object instance of the Thread class and passing the constructor a Runnable object. olution Here we find the sum of negative numbers and Find the sum of positive numbers by using C. tinclude ‘define MAXSIZE 10 void main() { int array[MAXSIZE]; int i, num, negative_sum = 0, positive sum = 0; float total = 0.0, average; printf ("Enter the value of N\n"); scanf("gd", &anuim); printf("Enter %d numbers (-ve, +ve and zero) \n", num); for (i= 0;i< num; i++) { scanf("%d", Sarraylil); } printf("Input array elements \n"}: for (i= 0;i< num; i++) { printi("9o+3d\n", array[i): } = Summation starts */ for (1 0: < num; i++) c If (arrayti] <0) { egative_sum = negative.sum + array{t}; d else if (array) > 0) { ositive_sum = positive sum + arrayli); } else if (array[i] == 0) { } total = total + array{i} ; } average = total / num; printf("\n Sum of all negative numbers Printf("Sum of all positive numbers = printf("\n Average of all. Input array elements 8 ” 100 “212 ofall negative numbers mee all positive numbers = 169 sum age ofall input numbers = 5,9 ye Write a multithreaded java program that Outputs prin mbes The user will run the progra This program should work as follows m and will enter a number on the « create a separate thread that outputs 4 -ommand line. The Program will ther Ml the prime numbers less ‘han or equal to the number entered by the user. solution Here we see C program as prime numbers less than or qual to the number entered by the user include intmainQ){ seanf("%d" 8); int nlist{]; forll=2:i<=li++){ niist{temp} tempts; } for(i=0;i int main() f | {nt in, €1 = 0,t2 = 1, nextTerm; ) printf("Enter the number of terms: "); scanf(“%d", &n); printf("Fibonacci Series: "); for (i= 1; <=n; +4) { printf("%d, ", ¢1); nextTerm = tl + t2; Practical 3 : Synchronization (Give java or C solution to Bounded buffer problem. Here we add and remove items from the bounded buffer (producer /consumer problem). Here we remove, add and initialize a bounded buffer for the consumer/producer problem. #include include #include #include #include “bbuffer.h” P-8 Practicals cert | 1 zs SSS itl ys punt u itt a qrmutert mutex} th jg, 006, i in jd blfer(BOUNDED_BUFFER SIZE into" void inialize bounded. buffer() ts jn stacusi count'= 0; gone ute oek(Smtex satus = pthread mutex ie(muter NULL); if(status != 0) fprintf(stdert, ‘Error creating buffer_mutex\n") } pthread_mutexuntock(@mutex): j : void add to_bufferfint value) { pthread_mutex lock(&mutex)}; while (count == ‘BOUNDED _BUFFER SIZE){ /frmake it wait if (count < BOUNDED_BUFFER SIZE) { bounded_bufferfcount] = value; count++; printf('added"); | Yelse{ printf("buffer full"); y pthread_mutex_unlock(&mutex); | int remove_from_buffer() { for (:){ pthread_mutex_lock(&mutex); | while (count ==0) 1 Re if (count > 0){ bounded. buffer{count] « bounded, buffercount-1]; count printf{"removed"); return 0; Jelse ( printf("could not remove"); return -1; , pthread_mutex_unlock(&mutex); } } bbuffer.h file: Code: #indef BBUFFER H_ #define BBUPFER H_ #define BOUNDED_BUFFER SIZE 4 vold initialize bounded buffer(); void add to_buffer(int); {int remove_from_buffer(); endif. pthread.h Code: pthread_mutex,lock(&mutex); status = pthread_mutex_init(&mutex, NULL); if (status != 0) { fprintf(stderr, "Error creating buffer_mutex\n"); } pthread mutex_unlock(Sanutex); (ii) Give solution to the readers-writers problem using Java synchronization. ‘The header defines the sem_t type, used in performing semaphore operations #include ¢ ey ‘include #include Operating System Hinclude void * reader(void *) ; void *writer (void *) sem_t wsem,mutex int readcount=0 ; main() int system(“clear"); sem init(&wsem,0,1) ; e(&mutex,0,1) ; pthread_t nwyrlw1 ; pthread_create(&r,NULL,reader,(void “Ja); att; sem pthread_create(&w1,NULL,writer,(void *)b); bet pthread_create(&r1,NULL,reader,(void *)a); pthread_create(&w,NULL,writer,(void *)b); pthread _join(r,NULL); pthread_join(w1,NULL); pthread_join(r1,NULL); pthread_join(w,NULL) ; printf("main terminated\n"); } void * reader(void * arg) { int c=(intjarg ; printi("\nreader %d is created",c); sleep(1); sem_wait(&mutex) + readcount++; if(readcount==1) sem_wait(&wsem) ; sem_post(&mutex) ; /*Critcal Section */ printf("\\n\nreader 9d is reading\n ".c); sleep(1) ; printf("\nreader%d finished reading\n".c); /* critical section completa * Operating System sem_wait(Smutex) ; readcount--} if{readcount=#0) sem_post(&wsem) ; sem_post(&mutex) : } void * writer(void * are) { int c=(intjarg ; printf("\nwriter 96d is ereated”,<)s sleep(): ssem_wait(&wsem) printf("\nwriter 96d is writing\n"<) steep(1); printf("\nwriterdéd finished writing\n".¢) es sem_post{&wsem) ; } Output reader 2 is created writer 1 is created reader 1is created writer 2s created writer 2 is writing writer? finished writing writer 1 is writing writer! finished writing reader 2is reading reader 1 is reading reader? finished reading reader! finished reading Operating s ractieal OR (il) The Sleeping-Barher Problem: A barber shop consists of awaiting 1m with n chairs and a barber room with one barber chair. I there are no customers to he served. the harher goes to sleep. If a customer enters the barbershop and all chairs are occupied, then the customer leaves the shop. Ifthe harher is busy but chairs are available, then the customer sits in one af the fi e chairs. the harber is asleep, the customer wakes up the barber, Write a program to coordinate the barber and the customers using Java synchronization. Solution We ase 4 semaphores Semaphore customers counts waiting customers; semaphore barbers is the number of idle barbers (0 oF 1): and mutex is used for mutual exclusion. A shared data variable customers! also counts waiting customers tis a copy of customers, But we need it here because we can't access the value of semaphores directly. We also need a semaphore cutting which ensures that the barber won't cut another customer's hair before the previous customer leaves. ~ Following code should be further implemented in java or any suitable language. 1/ shared data ‘semaphore customers = 0; semaphore barbers int customer ; Semaphore cutting = 0; semaphore mutex = 1; void barber() { while(trae) ( wait(customers); //sleep when there are no waiting customers ‘wait{mutex); //mutex for accessing customers ‘customersi = customersi - 1; signal(barbers); signal{mutex); cut hair); ) 2. void customer) { ‘wait{mutex); //mutex for accessing customerst if (customers #includesconio,h> int main() { int n bt[20],wt{20},tat{20} avwt=0,avtat=0,i,); printf{"Enter total number of processes(maximum 20):"); scanf{"%d",&n); for(i=0;icn;i++) { tat{l]=befi]+we{i); ee Be avwt+=wtt{i]; avtatestat{: printf("\nP{9edl]\t\t%od\ ¢\ td t\ eo bef we tat), recess ge eect gee eee geet ge gre ae ge gr gg gee ge nee get vege see see ECE operating System res a Sn printf("\n\nAverage Waiting Time:%d",avwt); printf("\nAverage Turnaround Time:%d"avtat}; return } Output Enter total number of processes (Maximum 20):3 Enter processes Burst Time Piaj2e PI2}:3 PI3):3 Process BurstTime Waiting Time Turnaround Time Pit] 24 0 24 Pi) 8 24 27 Average Waiting Time:17 ‘Average Turnaround time :27 Practical 5: Implement SJF (with no preemption) scheduling algorithm In Java or C. #include int main) { » ‘intinp[10]={1,2,3,4,5,6,7,8,9,10},min,k=1,btime=0; tnt bt{10],temp,j,at[10},we{1 0} te[10].t \sum=0; float wavg=0,tavg=0,tsum=0,wsum=0; printf(" ------Shortest Job First Scheduling (Non Preemptive ‘printf("\nEnter the No, of processes :"); seanf{"%d",&n); ‘\n"); for(icQ:i=at[i] && bt[i] int mainQ) { int countj,n,time,remain,flag=0,time_quantum; int wait time=0,turnaround time=0,at[10],bt[10},r"{10]; printf("Enter Total Process:\t"); Z scanf{"%d”,8n); remain=n; for{count=0;count0) { timet=rt{count]; _ st[count]=0; oflaget;. ee system Practicals fount -=tme. quanta simevstimequancums } igecount}=-0 88 Hg°=3) { remain prime’ eee 6d counts 4,time-at{count)time-at{count)-befeount): wit tme+=time-ae(count}-befcountl umaround_sime#=time-at{count] flag=0; ) iffcount==0-1) count=0; ats ifatfoounted]<=time) count++i else count=0; } printf("\nAverage iating Time sary" araceme® 0/7) printf(tAvg Tumaround Time = gp eurnaround.time"t0/0): return 0; } Output Enter Total Process : 4 Enter Arrival Time and Burst Time for process and Process Number is 1:0 9 Enter Arrival Time and Burst Time for process and Process Number is 2:1 5 ‘Enter Arrival Time and Burst Time fOr 3 Enter Arrival Time and Burst Time for Proves 4 Enter Time Quantum +5 process and Process Number is 3:2 gs and Process Number 5 43 pay Praicats Operating System a, Process | Turnaround Time | Waiting Tine P[2) 19 1 4 Pi3) Iu nc) Pia] 14 | 10 Pt) Ia 12 Average Waiting Time =8,50 ‘Average Turnaround Time =13.75 Practical 7: Write a Java program that implements the banker's algorithm. #include int main() { Int count = 0, m, n, process, temp, resource; int allocation_table(5] = {0, 0,0, 0, 0}; int available(5}, current(5){5), maximum_claim(5]{5 int maximum_resources[5], running[5], safe_state = 0; printf("\nEnter the Total Number of Processes:\t"); scanf{"%d", &process); for(m = 0; m< process; m+) { running{m] = 1; count++; } printf("\nEnter the Total Number of Resources to Allocate: scanf{("9d", &resource); printf{"\nEnter The Claim Vector:\t"); for(m = 0; m < resource; m++) { Scanf{"%d", &maximum_resources[m]); } Printf{"\nEnter Allocated Resource Table:\n"); for(m = 0; m < process; m++) { for(n = 0; n< resource; n++) £ seanf("%d", ¤t{m){n}); } OTT eee eter eee Tec eee eee eee TTT eee oe a printi("\nEnter The Maximum Claim Tables\ for(m = 0; m< process; m++) { for(n = 0:1 < resource; ne+) { scanf{"%d", &maximum.elaimfm|{n}}: } } printf("\nThe Claim Vector \n"); for(m = 0; m < resource; m+) { Printf("\t9d_°, maximum resources(m}); J printf{("\n The Allocated Resource Table\n"); for(m = 0; m< process; m++) if for(n = 0;n< resource; n++) { printf("\t%d", current{m][n]); } printf("\n"); } printf("\nThe Maximum Claim Table \n for(m = 0; m < process; m++) { for(n = 0; n< resource; n++) { printi("\t% + printf("\n"); aximum_claim[m]{n]); } for(m = 0; m < process; m++) { for(n = 0; n < resource; n++) { allocation table{n] = allocation.table(n] + current{mj{n}; } printf("\nAllocated Resources: \n"); for(m = 0; m < resource; m++) Printi{"\t@od", allocation table|m)): ) form = 0; m < resource; m++) 4 available[m] = maximum_resources(m] - allocation_table[m]; ) printf["\nAvailable Resources: for(m = 0, m < resource; m++) { printf(”\196d", availabie{m)); } prindf{"\n"); while(count '= 0) { safe_state = 0; for(m = 0; m < process; m++) { if{running{m]) { temp=1: for(n = 0; n< resource; n++) { if(maximum_claim[m{n] - current{m][n] > available[n)) { temp = 0; break; ) if{temp) { printf("\nProcess %d Is In Execution \n", m + 1); running{m| = 0; count--; safe_state = 1; for(n = 0; n < resource; n+*) { available{n] = available{n] + current{m)[n]; , break; Operating System . p-22 Practicals } } if{tsafe_state) { printf("\nThe Processes are in An Unsafe State \n"); > break; } else { printf("\nThe Process is in A Safe State \n"); printf("\nAvailable Vector\n"); for(m = 0; m< resource; m++) { printf("\t%d", available[m]); } printf("\n"); 3 return 0; é Output Enter the Total Number of Processes: 2 Enter the Total Number of Resources to Allocation: 2 Enter The Claim Vector: 1 2 ) Enter allocated Resource Table: 123456 Enter The Maximum Claim Table: 234567 ‘The Claim Vector + 2 ‘The Allocated Resources Table 1 2 3 4 “The Maximum Claim Table 5 6 2 3 ‘Allocated Resources: 4 6 ‘available Resources: -3 ~4 “The Processes are in An Unsafe State manera Practicals Hinchadesstdio b> int maing) ‘ int reference.string! 10}, page_faults = 0, m,n, s, pages, frames; print{("\nEnter Total Number of Pages:\t") seant("%d”, Spages): printf("\nEnter values of Reference String:\ for(m = 0; m< pages: m++) { prinef("Value No. (%d]:\t", m + 1); scanf{"%d", &reference_string[i]); } printf("\nEnter Total Number of Frames:\t"); { scanf("%d", &frames); ) int temp[frames]; for(m = 0; m < frames; m++) { temp{m) } for{m = 0; m < pages; m++) { $20; for{n = 0; n < frames; n++) { if(reference_string(m] == temp{n}) { Ste; Page faults--; } Page faulta++; Mf((page faults int main() { int frames{10}, temp(10}, pages{10}; {int total_pages, m, n, position, k,|, total frames; inta=0,b = 0, page fault = 0; printf("\nEnter Total Number of Frames:\t"); scanf("%od”, &total frames); for(m = 0; m < total frames; m++) \n", page faults); ticals replacement algorithm. Ta Operating System ‘ frames(m} © «1 ) printf" Enter Total Number of Pages:\t"); scanf{“%d", &total_pages); print{{"Enter Values for Reference String:\n"); for{m = 0; m < total_pages; m++) ( printf("Value No.{%dJ:\t", m +1); scanf("%d", &pages{m)); ) for(n = 0; n < total_pages; i++) { a=0,b=0; for{m = 0; m < total_frames; m++) { if{frames[m] == pages(n}) { ast; b=; break; d iffa==0) { for(m = 0; m «total frames; m++) { if{frames{m) == -1) { frames{m] * pages|n]; bai; break; ) if(b ==0) { for(m = 0; m< total,frames; m++) som pw tempi] « 0; ) for(k ne 1,1 11 total frames - 15 14, ke) { for{m «0; m «total frames; m++) { {t(tramos{m] =» pages{k]) { temp(m] # 1; b } for(m = 0; m < total,frames; m++) { {f(temp{m] == 0) Position = m; } frames{position] = pages{n]; age faulte+; } printf("\n"); for(m = 0; m < total fram { printf("6d\t", frames{m]); +4) ae Number of Page Faults:\t%d\n", page.fault); return 0; } Output Enter Total Number of Frames: 4 Enter Total Number of Pages: 5 Enter values for Reference String: Value No] :5 Value No,{2]:3 Value No.(3] :1 Value No.{4] :2 Value No.{5]:4 Practicals Ed Practicals 27 — oro 1 a 1 1 1 1 1 2 1 2 Total Number of Page Faults :1 Practical 10 : Design File System in java or C () Here we create a text file name as test.txt. A basic file system can be shown as managmenet of data in Files & Folders. It should also manage the space available. ‘ftinclude #include Hidefine SIZE 1 #define NUMELEM 5, int main(void) { FILE* fd = NULL; char buff{100]; memset(buff.0,sizeof(buff)); fa = fopen("testtet’,"rw+"); ‘if(NULL == fa) { printf("\n fopen() Errorit!\n"); return 1; } printf("\n File opened successfully through fopen()\n"); ‘f(SIZE*NUMELEM != fread(buff SIZE, NUMELEM,fd)) { printf("\n fread() failed\n"); return 1; } | printf('\n Some bytes successfully read through fread()\n"); ed Operating System p28 printf("\n The bytes read are [%s}\n" but) iff(0 I= fseek(fd,11,SBEK.CUR)) { printf("\n fseek() failed\n" return 1; printf("\n fseek() successful\n"); if{SIZE*NUMELEM != fwrite(buff,SIZE,strlen(buff),fd)) { printf("\n fwrite() failed\n"); return 1; } printf("\n fwrite() successful, data written to text file\a"); fclose( fd); printf("\n File stream closed through feloseQ\n"): return 0; } Output File opened successfully through fopenO ‘some bytes successfully read through fread) ad are [operating System] “The bytes re Foeek() successful fwriteO successful, data written to text file ‘pte stream closed through felose0 —_ Practials Operat em eras (il) Here file is created with given name, and information Is stored In that file #includecstdio.h> #includeestringh> void main() { FILE *fptr; char name[20); int age: float salary: /* open for writing */ fptr = fopen("emp.tt”, ‘w"); if (fptr == NULL) { printf{"File does not exists \n"); return; } printf("Enter the name \n"); scanf("%s", name); fprintf(fptr, "Name = %s\n", name); printi("Enter the age\n"); scanf("%d", &age); fprinti(fptr, "Age = %d\n", age); printf{"Enter the salary\n"); scanf("%f", &salary); fprinef(fptr, “Salary = %.2A\n", salary); felose(fptr); + Output Enter the name abe Enter the age 25 Enter the salary 30000 gaa

You might also like