You are on page 1of 41
OPERATING SYSTEM LAB (KCS-451) NDEX ‘ S.NO, TITLE. COURSE OUTCOME (CO) a 7 Biudy of ardvare and software requirements of diferent i oF perating systems (UNIX,LINUX, WINDOWS XP, : : INDOWS7/8 ‘ [Execute various UNIX system calls for 5 : 2 Process management a 59 . File management Inpuvoutpat Systems calls Implement C ci 3 pment CPU Scheduling Pos fe ae ii,_BCRS implement CPU Scheduling Policies 7 i. Round robin a ene ii. Priority cee JWrite aC program to simulate Bankers algorithm for the : 5 purpose of deadlock avoidance. a anni Tmplement file storage allocation techniquer : 7 i. Contiguous(using array) a fea ii, Linked —listusing linked-list) ii, Indirect allocation (indexing) 7 Cakeulation of external and intemal fragmentation, aa cea implementation of contiguous allocation techniques: i : i. Worst-Fit cn a ii, Best- Fit iii, First- Fit : > [implement the solution for Bounded Buffer (producer- con eae -onstumer) problem using inter process communication jechniques-Semaphores. 7 10 kimplementation of resource allocation graph RAG a ete Course Outcome ( CO) : At the end of course , the student will be able to: Con; Lisdetstand and implement basie services and functionalities of the operating system using system et C02: Use modem operating system calls and synchronization libraries in software hardware interfaces. 03: Analyze and simulate CPU Scheduling Algorithms like CFS, Round Robin, SJR, and Priority. CO4; Implement memory management schemes and page replacement schemes and simulate file allocation and organization techniques. COS: Understand the concepts of deadlock in operating systems and implement them in ‘multiprogramming system, \jroved By Er. AKANSHA SINGH HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) EXPERIMENT NUMBER: 1 Objective: - Study of hardware and software requirements of different oper WINDOWS XP, WINDOWS7/8 Content: Hardware requirements: The most common set of requirements defined by any operating system or software application is the physical computer resources, also. known as hardware, A hardware requirements list is often accompanied by a hardware compatibility list (HCL), especially in case of operating systems. ing systems (UNIX, LINUX, Hardware and Software Minimum Requirements 1. Windows 10 ‘ i. Processor: | gigahertz (GHz) or faster processor or SoC. ii. RAM: | gigabyte (GB) for 32-bit or 2 GB for 64-bit iii, _ Hard disk space: 16 GB for 32-bit OS or 20 GB for 64-bit OS iv, Graphics card: DirectX 9 or later with WDDM 1.0 driver v. Display: 800 x 6009 with WDDM driver ‘ 2. WINDOWS XP ‘The minimum hardware requirements for Windows XP Home Edition are: i, Pentium 233-megahertz (MHz) processor or faster (300 MHz is recommended) ii, Atleast 64 megabytes (MB) of RAM (128 MB is recommended) Atleast 1.5 gigabytes (GB) of available space on the hard disk iv. CD-ROM or DVD-ROM drive y. Keyboard and a Microsoft Mouse or some other compatible pointing device vi. Video adapter and monitor with Super VGA (800 x 600)or higher resolution vii, Sound card ‘ viii, Speakers or headphones 3, UNIX OS vi. RAM: 1 GB vii, Processor: IBM 604e processor with a clock speed of 375 MH2 or faster viii, Free disk space: /tmp must have 1 GB free disk space. If Tivoli Identity Manager installs WebSphere Application Server, {WAS_HOME} must have 800 MB free a : space and /va have 300 MB free disk space. Allocate 500 MB for /itim45. must CSE, SRMGPC, LKO Page 3 y INGH HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) 4, LINUX 32-bit Intel-compatible processor running at 2 GHz or greater 512MB RAM Disk space: 2.5 GB for Pipeline Pilot server plus components A DVD-ROM drive Assignment: QL. Study the hardware and software requirements of different operating systems CSE, SRMGPC, LKO Approved By INGH HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) EXPERIMENT NUMBER: 2 Objective: - Execute various UNIX system calls for i. Process management ii, File management . Input/output Systems calls Content: ‘The interface between a process and an operating system is provided by system calls. In general, system calls are available as assembly language instructions. They are also included in the manuals used by the assembly level programmers. Unix System Calls System calls in Unix are used for file system control, process control, interprocess communication etc. Access to the Unix kernel is only available through these system calls. Generally, system calls are similar to function calls, the only difference is that they remove the control from the user process. ‘There are around 80 system calls in the Unix interface currently. Details about some of the important ones are given as follows - System Call Deserip access() ‘This checks if a calling process has access to the required file chdir() ‘The chdir command changes the current directory of the system chmod() The mode of a file can be changed using this command chown() ‘This changes the ownership of a particular file king, ‘This system call sends kill signal to one or more processes link) A new ‘ile name is linked to an existing file using link system call. open() ‘This opens a file for the reading or writing process pause() The pause call suspends a file until a particular signal occurs. stime() ‘This system call sets the correct time. times) Gets the parent and child process times ‘The alarm system call sets the alarm clock of a process fork() A new process is created using this command chroot() ‘This changes the root directory of a file. CSE, SRMGPC, LKO ‘Approved By HOD (CSE) Page 5 OPERATING SYSTEM LAB MANUAL (KCS-451) System Call Deseription exit) ‘The exit system call is used to exit a process. | File Structure Creating @ Channet creat() ' Related Calls open) closet) Input /output read) writec) Rancloa Access Iseek() Chane} Ouplication up. Allasing and Reroving Link() Files unlink) rf File Status stat() Fstat() Access Control access() chrod() chown() umaske) focti() Process Related exec) Gauls Termination Fork) wait) : exit) Process Owner and Group getvia() ‘ geteuid() aetgia() getegic() Process Identity setpi() setpoid() : Process Control signan() xi alann() Change Working Directory chaie() Lnterprocess Pipelines pipeQ) Coraunicat ion Nesseges monget() imsgsna() ‘ megrev() imaget1() Semaphores senget©) senop() Shared slenary shget() brat) shat) /* enrmsgl.c : print all system error messages using "perror()" 7 | #include int main() ( int i; exter int ermo, sys_nerry CSE, SRMGPC, LKO| ‘Aporoved By HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) for (i= 0; 1< sys_nerr; +4i) { fprintf(stdet ermo perror(" } exit 0; } 30"); /* errmsg2.c print all system error messages using the global error message table. +) #include int main) extern int sys_nert; extern char *sys_erttist{}; fprintfi(siderr,"Here are the current 9d error messages:\n\n",sys_nerr); for (i= 0; i < sys_nerr; ++i) fprintf(stderr,"%3d: %s\n", i, sys_enlistfil); } 7 creates #include ¥include —_/* defines types used by sysistat.in */ Hinclude —_/* defines S_IRBAD & S_IWRITE —*/ int main() { int fds fd reat("datafile.dat", S IREAD | S_IWRITE); if (fd == -1) printf("Error in opening datafile.dat\n"); else { intf(’datafile.dat opened for read/write aecess\n"); printf("datafile.dat is currently empty\n"); a } ‘Appre ved By HOD (CSE) CSE, SRMGPC, LKO OPERATING SYSTEM LAB MANUAL (KCS-451) + close(td); exit (0); } ‘The following is a sample of the manifest constants for the mode argument as defined in /ust/inelude/sys/stat h itdefine S_IRWXU 0000700 /* -rwx—---- */ itdefine $_IREAD 0000400 _/* read permission, owner */ itdefine S_IRUSR S_IREAD Hidefine S_IWRITE 0000200 _/* write permission, owner */ Hdefine S_IWUSR S_IWRITE fidefine S TEXEC 0000100 /* execute/search permission, owner */ Hidefine S_IXUSR S_IEXBC define S_IRWXG 0000070 /* —-rwx--- */ fdefine S_IRGRP 0000040 /* read permission, group */ define S_IWGRP 0000020 /* write " "#7 ‘ #idefine S_IXGRP 0000010 /* execute/search" " */ #define S IRWXO 0090007 /* wx #7 #define S_IROTH 0000004 _/* read permission, other */ define S IWOTH 0000002 /* write" " #/ fidefine $_IXOTH 0000001 /* execute/search ""*/ ‘open() Neat is the open() system call, open() lets you open a file for reading, writing, or reading and writing, ‘The prototype for the open() system call is: #inelude int open(file_name, option_flags [, mode) char *file_name; int option_Mags, mode; where file_name is a pointer to the character string that names the file, option_flags represent the type of channel, and mode defines the file's access permissions if the file is being created. ‘The allowable option_flags as defined in "/ust/include/fentLh" are: tHdefine O_RDONLYO —/* Open the file for reading only */ #define O_WRONLY 1 /* Open the file for writing only */ #define O RDWR 2 /* Open the file for both reading and writing*/ #define O_NDELAY 04 /* Non-blocking /O */ “APP IOV: HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) fidefine O_APPEND 010 _ /* append (writes guaranteed at the end) */ fidefine O_CREAT 00400 /*open with file create (uses third open arg) */ define © TRUNC 01000 _/* open with truncation */ #define O_EXCL 02000. /* exclusive open */ Assignment: QL. Execute various UNIX system calls for i. Process management ii, File management iii, Input/output Systems calls CSE, SRMGPC, LKO “Approved By Page 9 \By ‘SINGH HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) EXPERIMENT NUMBER: 3 Objective: -Implement CPU Scheduling Policies: i. SIF ii, FCFS Content: FCFS CPU SCHEDULING ALGORITHM For CES scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. ‘The scheduling is performed on the basis of arrival time of the processes irrespective of their other parameters. Each process will be executed according (0 its arrival time, Calculate the waiting time and tumaround time of each of the processes accordingly SJF CPU SCHEDULING ALGORITHM For SJF scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. Arrange all the jobs in order with respect to their burst times, There may be two jobs in queue with the same execution time, and then ECES approach is to be performed. Each process will be executed according to the length of its burst time. Then calculate the waiting time and turnaround time of each of the processes accordingly. Program: 1, FCPS SCHEDULING 1, Start 2. Declare the array size 3, Read the number of processes to be inserted 4, Read the Burst times of processes 5, calculate the waiting irae of each process welit! |=bt{i]+wtli] 6, caloulate the tumaround time of each process tt{it1]=t{i}#bt{i+L] 7. Calculate the average waiting time and average turnaround time, 8. Display the values 9. Stop Hinclude #include void main() t int ij,bt{10],0,wt{10},tt(10),w1=0,¢ float aw,at clrser(); printi(“enter no. of processes:\n"); seanf("%d" &n); { printi("enter the burst time of processes:"); 7 forli=O;icnsit+) “% : CSE, SRMGPC, LKO- ‘Approved By Er. Al INGH HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) scant("%od" SebtLi); : forti=O;icnii+#) : i}bttitL I; yL+wtlils tstl+ufil; } awewI/n; at=tl/n; printf(\nbt\t wot tt for(i=0;i fineludesconio.h> void main) { int ij,bt{10}, float aw,at; clrser(); printf("enter no, of processes:\n"); seant("%d",Sn); printf("enter the burst time of processes:"); for(i=O;icn;it-+) scanf("%d" ,&bt[i}); for(i=O;icn;i+4) ( for(jmisisnyj++) if(biLap> but) ywt{10},tt[10],w1=0,¢ sisnsi+4) a",btLiDs forti=Oxisnii+4) { wi{0}=0; te{O]=bt{0};, wilit 1=bi{i}+wtli); fit eufiebtlie i); wl=wl+wt[il; tlstl-tt(i; d\t dt Gocl\n" bifi} wel] tei); 9% f\n,at= Fon" aw at); getch(); } INPUT: enter no of processes 3 enter burst time 12 8 OPERATING SYSTEM LAB MANUAL (KCS-451) Approved By HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) 20 OUTPUT: bewent 12820 808 20 20 40 Assignment: Implement CPU Scheduling Policies: i, SIF i FCRS CSE, SRMGPC, LKO roved By By. INGH HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) EXPERIMENT NUMBER: 4 Objective: -Implement CPU Scheduling Policies: i, Round robin ii, Priority Content: ROUND ROBIN CPU SCHEDULING ALGORITHM For round robin scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times, and the size of the time slice, Time slices are assigned to each process in equal portions and in circular order, handling all processes execution. This allows every process to get an equal chance, Calculate the waiting time and turnaround time of each of the processes accordingly. PRIORITY CPU SCHEDULING ALGORITHM, For priority scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times, and the priorities. Arrange all the jobs in order with respect to their priorities. There may be two jobs in queue with the same priority, and then FCFS approach is to be performed. Each process will be executed according to its priority. Calculate the waiting time and turnaround time of each of the processes accordingly. Program: 1. ROUND ROBIN CPU SCHEDULING ALGORITHM ALGORITHM 1. Start 2, Declare the array size 3. Read the number of processes to be inserted 4, Read the burst times of the proce 5. Read the Time Quantum 6. if the burst time of a process is greater than time Quantum then subtract time quantum form the burst time Else Assign the burst time to time quantum, F.calculate the average waiting time and tumaround time of the processes. 8, Display the values 9. Stop PROGRAM: Hinclude #include void main() 7 { / {nt stf10},bt{ 10}, wt{10},tat{10),n,1q; \ int i,count=0,swt=0,stat=0,temp,s¢ = nA’, CSE, SRMGPC, LKO 8 7 ‘Approved By Ec. AKANGHA SINGH HOD (CSE) OPERATING SYS ‘ float awt=0.0,a clrser(); printf("Enter number of processes:"); scanf("Yod", Sen); printf("Enter burst time for sequences:"); forti=0;itq) sifiJ=si{iltg; else if(st{i]>=0) sq=sq+temp; tatli}=sq3 if(n==count) break; } ‘ forli=O;isn;i++) { wefi}stat[i}-bt{i); swt=swt+wtfi); stat=stat+tat{i]; } awt=(float)swi/n; atat=(float)statin; printf("Process_no Burst time Wait time Turn around time"); forGi=O;isnsi++) printi("\nfod\t YodNt Yod\t Sd” i+ 1 bei}, wel i),tattil); printf(’\nAvg wait time is Sof Avg turn ayounghtime is Yof" awt,atat); CSE, SRMGPC, LKO ‘Approved By Page lS HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) getch()s 2 SJF SCHEDULING , ALGORITHM 1. Start 2, Declare the array size ‘ 3, Read the number of processes to be inserted 4, Read the Priorities of processes 5. sort the priorities and Burst times in ascending order 5. calculate the waiting time of each process wifit Hebifi} wel) 6. calculate the turnaround ime of each process a ttfie Hsu fi+btliel) 6, Calculate the average waiting time and average tumaround time. 7. Display the values 8. Stop PROGRAM: #incinde #include void main() { int ij,pno[ 10} prior{ 10} bt{ LO} n,wi{ 10},t{10],w1=0,t1=0,s; float aw,at; clrser()s : printi(“enter the number of processes:"); seanf("%ed" &n); for(i=O;i #include void main() ( int n,t.ijok,p.u=0,s=0,m5 int block| 10},run[10],activel 10] newreql 10}, int max[ 10][10},resalloc{ 10][ 10] resreq[ 10]{10]; int totalloc{ 10] totext{ 10},simalloc{ 10}; Meleser()s print{ ("Enter the no of process. scant("%od",n); printf("Enter the no ofiesource classes:"); CSE, SRMGPC, LKO ‘Approved By HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) seant("%od", der); printi(’Enter the total existed resource in each ch for(kel; k<=r; k++) scanf("%d", &totext[k}); printf("Enter the allocated resources:"), for(i= |; i<=n; i++) for(k=1; k=r; k++) resalloc); rocess making the new request:"); seant("%od" ep); printi("Enter the requested resource:"); for( se) scanf("%d", Scnewreqlk]); print{("Enter the process which are n blocked or running:"); for( int) { if i! { printf("process %d:\n"i+1); scant("%d%d" &eblock [i], Serun i); } } block{p}=0; runfp for(k=1; ks=r; k++) { J Tor(isl; iscn; b+) { totalloc{k}=j+resallocfil{k]; jstotalloc{k}; } } for(iel; isen; i+) { if(block{i]==I|jrunfi}==1) activefil=0; fonk=ts ksary k++) ‘ resalloc{p][k]+=newreq Ik]; . totalloc[k}+=newreq[k]; ( font: ke) ~ CSE, SRMGPC, LKO Pre| ‘Approved By HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) ‘ if(totexi{k]-totalloc{k}<0) for(k=1; ker; k++) simalloc[k}=totalloc{k]; . if((totext{k]-simallocfk])<(maxfil[k}-resallocfiJ{k)) ( isl break; simalloc[k ksar; ket) resreq[p]{k]=newreq[k]; printf(*Dead tock willn't ovcu } else { for(k= ( resalloc{p][kl-newreqlkl; totalloe{k]=newreq(k]; ) printf("Deadlock will occur"); jk mainQ) { int £(50] i,si,j,len,c,k; clrser(); for fli]=0; X: SO;i+4) printf("\n Enter the starting block & length of file” scanf("%ed%d" éest,delen); t,js(st+len) j++) =0) fGilels printt(\ndod->4%d" jf): } else { printi("Block already allocated"); break, } if G==(st+len)) printf("\n the file is allocated to disk" ( printf("\n if u want to enter more files?(y-1/n-0)"); GH f° Fd" Bec), CSE, SRMGPC, LKO Approved By Page 22 HOD (CSE) OPERATING SY: if{c==1) goto X; else exit; getch; } Output Enter the starting block & length of file 4 10 4>1 5->1 61 TDI BOL 921 101 2B 11 121 11 The file is allocated to disk Ifyou want to enter more files? (¥-I/N-O) LINKED FILE ALLOCATION Hinclude main() ( int {[50],p,ij,k,a,st,Jen.n,c; printf(*Enter how many blocks that are already allocated"), scanf("%d",&p); printé("\nEnter the blocks 10. that are already allocated"), scanf("Yod",&a); flal=1; } x printf("Enter the starting index block & length"); M LAB MANUAL (KCS-451) “Approved By HOD ( OPERATING SYSTEM LAB MANUAL (KCS-451) printf("\nded-> od fli): ) else printf("\n %d->file is already allocated" j); kot INDEXED ALLOCATION TECHNIQUE include int £[50] i,k, inde[50],n,c,count=0,p; main() ( clrsex() for(i=0;i %ed: Md" p,indelk],findet kD; printf(" Enter | to enter more files and 0 to exit\t"); scanf("%d" Bc); if(c==1) goto x; else exit); getch(); Assignment: CSE, SRMGPC, LKO) OPERATING SYSTEM LAB MANUAL (KCS-451) Appfoved By. ~~ HOD (CSE) TING SYSTEM LAB MANUAL (KCS-451) EXPERIMENT NUMBER: 7 . Objective Calculation of external and internal fragmentation x Content: There are two types o| Extemal fragmentation. mentation in OS which are given as: Internal fragmentation, and Internal Fragmentation Internal fragmentation happens when the memory is split into mounted sized blocks. Whenever a method request for the memory, the mounted sized block is allotted to the method. just in case the memory allotted to the method is somewhat larger than the memory requested, then the distinction between allotted and requested memory is that the Internal fragmentation, Assigned Fragment Space Used Space | Used Space Assigned Space Internal Fragmentation ‘The above diagram clearly shows the internal fragmentation because the difference between memory allocated and requited space or memory is called Internal fragmentation. External Fragmentation: External fragmentation happens when there’s a sufficient quantity of area within the memory to satisfy the memory request of a method. however the process’s memory request cannot be fulfilled because the memory offered is daring a non-contiguous manner. Bither you apply frst-fit or best-fit memory allocation strategy it’! cause external fragmentation. CSE, SEMGPC, LKO proved By Page 26 Er, AKANSHA SINGH HOD (CSE) Fragment Assigned Space Fragment Assigned Space Fragment OPERATING SYSTEM LAB MANUAL (KCS-451) : Process 07 needs 50KB 40 KB memory space { 10 KB $5 KB In above diagram, we can see that, there is enough space (55 KB) to run a process-O7 (required 50 KB) but the memory (fragment) is not contiguous. Here, the free space to run a process. Difference between Internal fragmentation and External fragmentation: we use compaction, paging or segmentation to use S.NO | Internal fragmentation External fragmentation In intemal fragmentation fixed-sized memory, blocks square measure In external fragmentation, variable-sized memory 1 appointed to process. blocks square measure appointed to method. Internal fragmentation happens when the ‘method or process is larger than the Extemal fragmentation happens when the method or Ee memory. ‘The solution of intemal fragmentation is | Solution of extemal fragmentation is compaction, 3. best-fit block. paging and segmentation. Internal fragmentation occurs when External fragmentation occurs when memory is memory is divided into fixed sized divided into variable size partitions based on the size 4 partitions. of processes. ‘The difference between memory The unused spaces formed between non-contiguous allocated and required space ormemory | memory fragments are too small to serve anew is called Internal fragmentation, process, is called External fragmentation CSE, SRMGPC, LKO OPERATING SYSTEM LAB MANUAL (KCS-451) 7 Assignment: i QL. Calculation of external and intemal fragmentation, Approved B; Page 28 PP! y CSE, SRMGPC, LKO HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) EXPERIMENT NUMBER: 8 Objective: Wor Write a C program to simulate the following contiguous memory allocation techniques a) -fit b) Best-fit c) First-fit Content: One of the simplest methods for memory allocation is to divide memory into several fixed-sized partitions. Each partition may contain exactly one process. In this multiple-partition method, when a partition is free, a process is selected from the input queue and is loaded into the free partition, When the process terminates, the partition becomes available for another process. The operating system keeps a table indicating which parts of memory are available and which are occupied. Finally, when a process arrives and needs memory, 2 memory section large enough for this process is provided. When itis time to load or swap a process into main memory, and if there is more than one free block of memory of sufficient size, then the operating system must decide which free block to allocate. Best-fit strategy chooses the block that is closest in size to the request, First-fit chooses the first available block that is large enough. Wors chooses the largest available block. Program: 1. First Fit algorithm in Memory Management Implementation: 1- Input memory blocks with size and processes with size. 2- Initialize all memory blocks as free. 3- Start by picking each process and check if it can be assigned to current block. 4- If size-of-process <= size-of-block if yes then assign and check for next process. 5- If not then keep checking the further blocks. 1/ C++ implementation of First - Fit algorithm cludesbits/stde++.h> using namespace std 1/ Function to allocate memory to 1/ blocks as per First fit algorithm void firstPit(int blockSize[}, int m, int proces 1, int n) {i Stores block id of the M1 block allocated (0 a process int allocation{n}, {Mnitially no block is as memset(allocation, -1, jigned to any process izeof(allocation)); I/pick each process and find suitable blocks a) /faccording to its i On ‘CSE, SRMGPC, LKO. “Approved By HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) for (int i= 0; i= proc ize) allocate block j to pli] process allocation{i] = j; 1 Reduce available memory in this block blockSize[j] -= processSize[i}; break; } } cout << "\nProcess No.\tProcess Size\'Block no.\n"; for (int i= 0; i processSizefcurrent], if found then assign it to the current process. 5- Ifnot then leave that process and keep checking the further processes. J/ C+ implementation of Best - Fit algorithm Hincladesbits/stde-+4.h> using namespace std; 1 Function to allocate memory to blocks as per Best fit Halgorithm void bestFit(int blockSize|}, int m, int processSizef], int n) ( 1} Stores block id of the block allocated to a 11 process int allocation{n}; {Initially no block is assigned to any process memset(allocation, -1, sizeof(allocation)}; 11 pick each process and find suitable blocks 11 according to its size ad assign to it for (int i=0; isn; i+) 1/ Find the best fit block for current process for (int CSE, SRMGPC, LKO ism; j++) if (blockSize[j] >= processSize[il) eke if (blockSize[bestldx] > blockSize[]) bestldx =j; “Approved By HOD (CSF) Page 31 OPERATING SYSTEM LAB MANUAL (KCS-451) Jf we could find a block for current process if (bestidx != -1) { HHallocate block j to p[i] process allocation[i] = bestldx; 4 Reduce available memory in this block. blockSize[bestldx] -= processSize[i; } } cout << "\nProcess No.\tProcess Size\tBlock no.\n"; for (int i= 0; i re CSE, SRMGPC, LKO Approved By GH HOD (CSB) Page 32 OPERATING SYSTEM LAB MANUAL (KCS-451) processSize{current], if found then assign | it to the current process. fase S- If not then leave that process and keep checking the further processes. 1/ C++ implementation of worst - Fit algorithm #includesbits/sidct+.h> f using namespace std; 1/ Function to allocate memory to blocks as per worst fit Halgorithm void worstFit(int blockSizel]), int m, int processSize{|,, intn) + ' { 1/ Stores block id of the block allocated to a 1 process ’ int allocation[n]; » Initially no block is assigned to any process memseiallocation, -1, sizeof(allocation)); 17 pick each process and find suitable blocks M1 according to its si: 11 Find the best fit block for current process int wstldx = -1; ‘i for (int j=0; j= processSize(i) { if (wstldx ee wstld) else if (blockSizewsttdx} < blockSizefj]) ‘wstldx = js } : If we could find a block for current process if (wstldx != -1) ‘ { HHallocate block j to pli] process allocation(i] = wstldx; 11 Reduce available memory in this block, blockSize[wstldx] = processSize[i}; CSE, SRMGPC, LKO ‘Approved By HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451) cout << "\nProcess No.\tProcess Size\'Block no.\n"; for (int i= 0; i Paciudecsti.n> ine mutex fll-Q,empy imag into, voll producer; voit consumer(}; iw waiting int signal pritf"Wo 1 Producern2.Consumesin3 Exit) while.) i (Banter your choice’); "len svtebo ease 1: il(muter==1)@&¢empry!=0)) produeer(); CSE, SRMGPC, LKO ‘Approved By ‘it HOD (CSE) OPERATING SYSTEM LAB MANUAL (KCS-451)* | prif"Baffer is full) break; 1) &&(Full=0)) ‘consumers cease 2: f(t: ebe fe Buffer is empty!" ease: ' return 0; . ) int waitin) i ’ int signa s) ‘ { 1 void producer() return (3); returns); ‘mutex=vnit(maten); fillesiganl( ful cempry=waitfempsy)s prini("\Producer produces the tem %8" x}, ‘ rmutex=signal(mates), void consumer() ( satex=walt(mutex); fawaital) . cempiy=signal(empty) Consumer consumes tem %d"x), ‘mutex=signal(mutes}; Assignment: QI. - Implement the solution for Bounded Buffer (producer-consumer) problem using inter process communication techniques-Semaphores, — ‘Approved By Page 36 « ROD (CSE) CSE, SRMGPC, LKO OPERATING SYSTEM LAB MANUAL (KCS-451) EXPERIMENT NUMBER: 10 Objective: - Implementation of resource allocation graph RAG Content: ‘The resource allocation graph is the pictorial representation of the state of a system. As its name suggests, the resource allocation graph is the complete information about all the processes which are holding some resources or waiting for some resources Italso contains the information about all the instances of all the resources whether they are available or being used by the processes. 0 RAG also contains vertices and edges. In RAG vertices are two type — 1. Process vertex — Every process will be represented as a process vertex.Generally, the process will be represented with a circle. 2. Resource vertex — Every resource will be represented as a resource vertex. It is also two type ~ © Single instance type resource ~ It represents as a box, inside the box, there will be one dot.So the number of dots indicate how many instances are present of each resource type. : « Multi-resource instance type resource ~ It also represents as a box, inside the box, there will be many dots present : Now coming to the edges of RAG. There are two types of edges in RAG — 1. Assign Edge — If you already assign a resource to a process then it is called Assign edge. 2. Request Edge — It means in future the process might want some resource to complete the execution, that is called request edge. Fuge v - Assign Request Edge Edge | So, if a process is using a resource, an arrow is drawn from the resource node to the process node. If a process is requesting a resource, an arrqw is drawn from the process node to the resource node, CSE, SRMGPC, LKO ‘Approved BY’ Page 37 HOD(GSE) \ OPERATING SYSTEM LAB MANUAL (KCS-451) | Example 1 (Single instances RAG) — Ri PLisholdingnt Le \P2 is waiting for Ra Pie holding R2 PL is waiting for R24 R2 SINGLE INSTANCE RESOURCE TYPE WITH DEADLOCK If there is a cycle in the Resource Allocation Graph and each resource in the cycle provides only one : instance, then the processes will be in deadlock. For example, if process P1 holds resource R1, process P2 holds resource R2 and process P1 is waiting for R2 and process P2 is waiting for R1, then process P1 and process P2 will be in deadlock, ris totsing a \ 2 LP Prvmrivgie nfl raivvatingtorne ee L | iN R41 R2 ‘ SINGLE INSTANCE RESOURCE TYPE WITHOUT DEADLOCK. is waiting to acquire both resources. In this example, there is no deadlock because there is no circular | Here's another example,that shows Processes P'1 and P2 acquiring resources Ri and R2 while process P3 | | | CSE, SRMGPC, LKO Approved By Page 38 OPERATING SYSTEM LAB MANUAL (KCS-451) dependency. So cycle in single-instance resource type is the sufficient condition for deadtock. Example 2 (Multi-instances RAG) ~ RL PL is holdine Rt PR nwattingtor RL ~ 2 [sholalng 2 PL is waiting For 82 Poisholdlng Rt R2 MULTI INSTANCES WITHOUT DEADLOCK From the above example, it is not possible to say the RAG Is ina safe state or in an unsafe state.So to see the state of this RAG, let’s construct the allocation matrix and request Allocation Request Process Resource Resource Ru a2 Rt R2 PL ee: 0 o 1 P2 7 fi f 0 | ° 3 ° 1 0 matrix. ‘* The total number of processes are three; P1, P2 & P3 and the total number of resources are two; R1&R2. Allocation matrix — ae ‘Approved By at HOD (CSE) CSE, SRMGPC, LKO OPERATING SYSTEM LAB MANUAL (KCS-451) + For constructing the allocation matrix, just go to the resources and see to which process it is allocated. + Ri isallocated to P1, therefore write 1 in allocation matrix and similarly, R2 is allocated to P2 as well as P3 and for the remaining element just write 0. Request matrix — + In order to find out the request matrix, you have to go to the process and see the outgoing edges. + Pis requesting resource R2, so write 1 in the matrix and similarly, P2 requesting R1 and for the remaining element write 0. So now available resource is = (0, 0). Checking deadlock (safe or not) ~ Aveilable=0 0 (As P3 does not require any extra resource to complete the execution and after Pa 0 1 completion P3 retease its own resource) New Available =0 1 (As using new availableresource we can satisfy the requirment of process P1 PL 1 0 and Pt also release its prevous resource) New Available=1 1 (Now easily we can satisfy the requirement of process P2) P2 o1 New Available So, there is no deadlock in this RAG.Even though there is a cycle, still there is no deadlock Therefore in multi-instance resource cycle is not sufficient condition for deadlock. PI is holding Ra + | pis waiting for Rt PL ie PAs waiting for R2 we P3 is holding 2 R2 MULTI INSTANCES WITH DEADLOCK CSE, SRMGPC, LKO ‘Approved By iGH HOD (CSE) Page 40 OPERATING SYSTEM LAB MANUAL (KCS-451) ‘Above example is the same as the previous example except that, the process P3 requesting for resource RL. So the table becomes as shown in below. ; Allocation ea 7 Process |_Resource Resource RA Re m1 a ° o L P2 ° z 4 ° 7 ‘ 0 1 o ‘ So,the Available resource is = (0, 0), but requirement are (0, 1), (1, 0) and (1, 0).S0 you can’t fulfill any one requirement.Therefore, it is in deadlock. Therefore, every cycle in a multi-instance resource type graph is not a deadlock, if there has to be a deadlock, there has to be a cycle.So, in case of RAG with multi-instance resource type, the cycle is a necessary condition for deadlock, but not sufficient. Program: : //C program to demonstrate waitpid() #include #include #include #include void waitexampleQ ( pid_t pid{51; for a) if ((pidfi] = fork) sleep(1); \ ' exit(100 + i); A roved By Page 41 \GH HOD (CSE) ‘ ‘CSE, SRMGPC, LKO OPERATING SYS } / Using waitpid( and printing exit status ‘ Hof children, for (i=0; i<5; it) { pid_t cpid = waitpid(pid{i, &stat, 0); : if (WIFEXITED(tat)) printf("Child %d terminated with status: %d\n", epid, WEXITSTATUS(stat)}; } M1 Driver code int mainQ) { waitexample(); retum 0; } Assignment: Q1. Implementation of resource allocation graph RAG, CSE, SRMGPC, LKO Approved By Page 42 Ex NNGH HOD ICEL

You might also like