You are on page 1of 28
Savitribai Phule Pune University Ss Systems Pr, emester V (Computer Engineering) ‘gramming and Operating System (Code : 404182) is loader 2 a wa ler 7 basic functions and features of a a LTT ‘on Explain the terms : Loader, Linker. SPPU - Dec. 14. 4 Marks ‘on Explain functions of a Loader. SETS (OR Discuss four different functions of loader. SPPU - April 18, 2 Marks (OR Define following system software components with suitable diagram : Loader EQQUSTSTP ORME Ans A source program is converted to object program by assemblers and compilers. The loader is a program which accepts object codes and prepares them for execution and initiates execution. ‘As many as four functions are performed by a loader. ‘These functions are : 1 Allocation of space in main memory for the programs. 2. Linking of object modul involves resolving of symbolic references between object modules. les with each other. Linking Fig. 3.1 : General loading scheme 3. Adjust all address dependent address constants, to correspon space. [tis also called retocation- —— locations, such as .d to the allocated 4. Physically loading the machine instructions and data into the main memory. A general loading scheme is shown in the Fig. 3.1 Q.2 What is linker ? Ans.: © Any usable program written in any language has to use functions/ subroutines. These functions could be either user defined functions or they can be library functions. © For example, consider a program written in C- language. Such a program may contain calls to functions like printf) and scanf(). During program execution the main program as well as functions must reside in the main memory. In addition, every time a function is called, the control should get transferred to the appropriate function. © The linking process makes address of modules known to each other so that transfer of control takes place during execution «Passing of parameters is handled by the linker. Parameters can be passed by value or by reference. Avalue returned by a function must be handled. + Every public variable should have the same address in every module. An external variable can be defined in one module and can be used in another module. The address of an external variable should be same in every module. Resolving of addresses of symbolic references is handled by the linker. @.3 Why program relocation is required and how is it performed? SET eE : Relocation is the process of modifying the ns of a Ans. addresses used in the address sensitive instru program such that the program can execute correctly from any designated area of memory. W systems Programming & Operating System (SPUD ‘The statement MOVER AREG, X This is an address sensitive instruction. For this instruction to execute correctly, the actual address of X should be put in the instruction. ‘assume that a program written in C-language (let us call it A) calls a function Fi. The program A and the function Fimust be linked with each other. But when in main storage shall we load A and F1 ? A possible solu would be to load them according to the addre assigned when they were translated. Case: At the time of translation, A has been given storage area from 100 to 250 while Floccupies area between 400 to 500. If we were to load these programs at their translated addresses, a lot of storage lying between them will be wasted. 9 100-4 A 250 7}. — wasted area Fig. 3.2(a) : Case I of relocat Case: At the time of translation, both A and f, may have been translated with the identical start address 100. A goes from 100 to 250 and f,goes from 100 to 200. ‘These two modules cannot co-exist at same storage locations. The loader must relocate A and Fito avoid address conflict or storage waste A possible relocation is shown in Fig, 3.2(b). Main 0, storage ‘Translation Relocated lime address address given by the loader Fig. 3.2(b) : Relocation to avoid address conflict or storage waste 32 Quick tesa Te noted that relocation Is more than simply from one area to another in the djustment of address fields and no, Ie may moving a program storage. It refers to a ‘ovement of a program. ted origin, Link origin, Load origin, .4 Explain Transial LET RAL Ans. : ated origin : It is the address specified by in an ORIGIN statement. This ¥y the translator For code generator this address of the origin assigned ,ducing the machine code, «Transl the programmer address is used b «Linked origin: T by the linker while pro «Load origin : Address of the origin assigned by the loader wt 1g the program for execution. ee @.5 Explain any one type of loa e Seo Explain compile and go-loader scheme. SEER ed Explain compile and go loader scheme wih advantages and disadvantages _using suitable diagram, Soa) OR Discuss four different functions of loaders. oR OR ‘Ans. : A compile-and-go loader scheme is shown in Fig. 33. «Assembler is loaded in one part of the memory and it places the assembled program (machine instructions) directly into their assigned memory locations. «After the loading process is complete, the assembler transfers the control to the starting instruction of the loaded program. ‘Source Program Compile-and-go i assembler W syotems Programming & Operating system (SPPUs advantages of compile and-go-loader Its easy to implement. Itisa very simple scheme. pisadvantages of compile and-go-loader 1. A portion of the memory is wasted as itis occu by the assembler. ee 2, Itis required to re-translate the fe user program eve time it is run. poem every 3, Itis difficult to handle multiple segments, Thus, it becomes very difficult to develop a modular program under compile-and-go assembler. 0.6 Explain "General loading scheme (using diagram)"with advantagesandaisadvantages, Sa Discuss four different functions of loaders. Explain working of “General Loading Scheme" with ‘advantages and disadvantages. ‘SPPU : March 20,5 Mark on Ans. : Output of assembler is saved in a file. This output can be loaded and executed whenever the user wants to run the program. The output of the assembler is known as the object program. ‘+ With the use of output of assembler as intermediate file, the disadvantages of “compile-and-go” scheme can be removed : 1. Retranslation of program every time it is run is avoided. 2. The assembler need not reside in the main memory at the time of execution, Only the loader need to be in the memory but it is much smaller compare to a compile-and-go loader. 3. Itis possible to write a modular program under general loading scheme. + In this scheme, the loader accepts object files and places machine instructions and data in the memory for execution. Advantages : 1. Source program can contain multiple modules and these modules can be written in multiple languages. Loader occupies a small portion of memory, instead of placing the assembler in the memory the loader 33 Quick eas resides in the memory which loads the executable program. A loader is smaller than assembler su there is litle wastage of memory. 3. There is no need to retranslate the source program each time itis to be executed. An executable module of a source program is generated only once. Disadvantages 1. Ifthe program is modified it has to be retranslated. 2, Some portion of the memory is occupied by the loader. ‘Absolute Loaders loading scheme. SEE Q.7 Expl OR Give complete design of Absolute Loader with suitable example. (OR Discuss four ferent functions of loaders SOT OR Whatis absolute loader? OR Explain flowing term : Absolute Loader ‘Ans. : The task of an absolute loader is virtually trivial ‘The loader simply accepts the machine language code produced by an assembler and places it into main ‘memory at the location specified by the assembler. Fig. 3.4 illustrates the operation of an absolute loader, The main program is assigned to locations 100 to 250 and the function Flis assigned locations 400 to 500. ‘The programmer should be careful not to assign ‘overlapping locations to modules to be linked. 100 WAIN 250 (ioonmm]_ 12d a MAIN oa ahr seo eM Fi 804 Fig. 3.4: Absolute loader example ‘The four loading functions are accomplished in an absolute loading scheme 1. Allocation - by programmer 2, Linking - by programmer 3. Relocation - by assembler 4. Loading- by loader Advantages of absolute loading scheme 1. No relocation information is required, so the size of the object module is comparatively small This scheme is very simple to implement. 3 This scheme makes more memory available for loading since the assembler is not in memory at the time of loading. No modification of address sensitive entities i Fequired atthe time ofoading. 5. This scheme supports multiple object modules t0 reside in memory Disadvantages of absolute loader 4. Since the linking is handled by the programmer, Programmer has to remember the address of each Module and use that absolute address explicitly for linking. 2% The programmer has to be careful not to assign overlapping locations to modules to be linked. 3. Lot of memory lying between modules will be wasted. 4 I changes are made to one module that increases it size then it can overlap the start of another module. Ie may require manual shifting of module. This manual shifting can become very complex and tedious. SPPU - Dec. 13, 4 Marks OR Discuss four different functions of loaders, OR What are subroutine linkages? What are benefits using it ? ‘Ans. : * A program consisting of main program and a set of functions (subroutines) could reside in several files, ‘These program units are assembled separately, ‘©The problem of subroutine linkage is this : a main program A wishes to call the subroutine B and if the subroutine B resides in another file then the assembler will not know the address of B and declare itas an undefined symbol. To realize such interactions, A and B must contain public definitions and external references, ments state e syml exTRN ny statement USts HE SYMDOTS toy The Ls e made in the current pry external refereners tr jefined in other program unis tit These symbol ts catement are taterent ts he publ tains, PORTE et ehich may be referenced iN other prop” program unit ants ample, the following sequence OF instruciy, For exi * e to anot ay bea simple calling sequence f0 another Program, MAIN START EXTAN Ft ‘Main program making a call o Subroutine F1 CALL FI END Fi START Subroutine Ft END Fig. 3.5 * _ Inthis example, the subroutine F1 is declared as zn external symbol in the main program. * Assembles cannot provide the addresses of exter! symbols. Their addresses are fixed at the time of linking. Thus, an external reference is said to be Untesolved until linking is performed for it. Itis sad ‘0 be resolved when its linking is completed Benefits of Subroutine Linkages 1 FON fi Subroutines can Feside in several files, 2 Asubrout fi \dently. ine can be modified independently. subi routine can be written in a different language : —__™ Mniften ina diferent language 9 ©lain relocation loaders OR 5, le ou Working of Binary ‘Symbolic Subroutine (855) ina with example, SE To a . when a ae Possible assembling of all subroutines tasks of allocane tne 's changed and to perform th? ion . | deneral class of relonnn inking for the programmes. th loader was introduced ee memory. Binary symbolic loader (Bss) is relocating loader. an example of one data segment. The output of the assembler usinga BSS loader is: Object program Reference about other programs to be accessed. Information about address sensitive entities, The relocation requirements of a program are influenced by the addressing structure of the computer system on which itis to execute. Many computer systems provide hardware support for relocation, Use of segment registers reduces the relocation requirement of a program. Let us consider a program segment as shown in Fig. 3.6(a). ig. 3.6(a) : A sample program segment considered for relocation In the above program segment the address of variable X in the instruction ADD AREG, X will be 30 a If this program is loaded from the memory loca = 500 for execution them the address of X in instruction ADD AREG, X must become 530, itis shown in Fig. 3.6(b)- a Quick Read ADD ARES, x ADO ARG, x — program Fig. 3.6(b) : Relocation of the program Use of segment registers make a program address insensitive. Here all memory addressing is performed using displacement (offset). Starting memory address is stored in the segment register and the actual address is given by Contents of the segment register + address of the operand in the instruction. ‘The address of the variable X can be found as given below: 500+30 = 530 7 NN Segment register offset Actual address ‘The BSS loader allows many code segments and one common data segment. The assembler assembles each code segment independently and passes on to the loader the following Object program prefixed by a transfer vector that consists of addresses containing names of subroutines referenced by the source program. 2. Relocation information, ie. locations in the program that must be changed if it is loaded in an arbitrary location in the main memory. 3. Length of the source program and the length of the transfer vector. ‘The loader loads the transfer vector and the object code into memory, then the loader loads each subroutine identified in transfer vector. The transfer vector is used to solve the problem of linking and the program length information is used to solve the problem of allocation, Q.10 In case of a: Direct Linking Loader, what is the information required to be passed by a translator to the loader. Ans. : It is a general relocatable loader, and is perhaps the most popular loading scheme presently used. ar tis a relocatable loader + Itallows multiple procedure segments and multiple data segments The assembler must give the loader the following information with each procedure or data segment : 1. The length of segment. 2. Allist of symbols defined in the current segment that may be referenced by other segments - public declaration, 3. A list of all symbols not defined in the segment but referenced in the segment - external variables. Information about address constants 5. The machine code translation of source program and the relative addresses assigned. 2.11 What is linkage editor 7 What is the essential difference between linkage editor and linking loader ? Ans. : A linkage editor is a linker that links assembled Programs. The linker resolves references between Program modules and libraries of subroutines, * The output of a linkage editor is load module, which is executable code ready to run. ‘* This executable module can be loaded by a loader in the main memory after allocation and relocation. ‘+ On the other hand, a linking loader performs both linking and loading. ‘+ The major disadvantage of linking loader is that every time you want to run the program, linking must be carried out. This step is performed only ‘once in linkage editor. © The two schemes are shown in the Fig. 3.7(a). Soest roto Object f Loador | Bozam * | execution | sa ZA rose Loader woman Fig. 3.7(a) : Linking loader scheme peara 13.7(0): Linkage editor scheme = a oR Balan Se pats SHOW OM ed oar cota sare a egading chem the PORE i rm the following tasks ‘a.12 Eqiain ab Ans. = the assembler perfor 1. Allocation 2, Relocation 3. Linking ‘The absolute loader reads the object program line by line and moves the text of the program into the memory at the location specified by the assembler. + The object program generated by the assembler ‘must communicate the following information to the loader: 1. It must convey the machine instructions that the assembler has created along with the memory address. It must convey the starting execution point Program execution will start at this point after the Program is loaded. ‘The object program is a sequence of object records. ce object record specifies some specific aspect of © Program in the object module. There are two types of records: Te rae cFd containing binary image of the assembly Program, 2. Transfer ansfer record containin entry) Point of exceann, 1 the starting ( The formats Fig. 3.8 of text and transfer records are given it Record 4 Type — Of | Memory | Binary image wi Of | address | of data of —amation L instruction @)Textrecord és Common jamming & Operating 5 Number ofbytesof | eae Address of the (0) Transfer record entry point cord type = 0 for Text record Re jecord type = 1 for Transfer record Fig. 3.8: Formats of object records gorse she algorithm for absolute loader is very simple. The inder rads the object file record by record and moves ipebinary image at the locations specified in the record ‘pe lst record is the transfer record. On reaching the ransfer record the control is transferred to the entry paint for execution. flowchart: Flowchart is given in Fig, 3.8(c). Wore Binary mae TTransor he Sait adaress. conte the Specie the ‘entry pont | ecard EE 0.13 Explain design of direct linking loader. Also explain the required data structures. OR Explain pass — | of direct linking loader with ‘flowchart, oF Give complete design of Direct linking Loader. OR Explain formats of ESD. RLD, TXT and END records king loader with suitable With respect to direct lin example ? ETRE OR What are the databases used by Pass: 1 and pass «2 of assembler. Explain them, with their format. An, The design of a direct linking loader 1s more “mplicated than that ofthe absolute loader tem (SPPU) 3-7, Quick Read The input to the loader is set of object programs (generated by assembler/compiler) to be linked together. Each object module is divided into 4 sections 1. External symbol directory (ESD). 2. Actual assembled program containing the binary code (TXT) 3. Relocation directory (RLD}. 4. Fd ofthe object module (END). =A direct linking loader requires two passes to complete the linking process (i) Pass 1,assigns addresses to all external symbols (i) Pass 11, performs actual loading, relocation and linking. ‘* In pass 1, a global external symbol table (GEST) 1s prepared. It contains every external symbol and the corresponding absolute address value. ‘©The two-pars direct linking loader scheme in shown inFig.39. rane a cape E~] aA NN Py Tarp rn cn | aie oes \ Za oo “symbol table "y Fig, 3.9 : Two pass direct linking loader scheme Q.14 Write the entries of ESD, TXT, ALD and Global External Symbol Table (GEST), for PGI and PG2 sven below : Object [Relative Source 1 record | address | program | Progr No. | ___|strat 2 | __|ENTRY PGIENT,PGTENT2 3 ___| exten pazenTt, PG2 Fi 7 ENT EGS 5 Do _A(PGIENT!) YL |____ |e arPatenta + 15) _ [De A(PGtENT2 — aman PGIENTI~ 9) | —-_| oc arraas || | met | —_———— DC A(PGZENT || | 90 {| |e pae- parents + ‘address of PGYENT! is 20 | t——+ END ‘address of PGTENT2 + 15 [Sant 23015 pp} | ferry pazentt a EXTRN PGIENT!. — | ___[patent2 PG1ENT2- PGIENT! -3 | 2=30-20-3 | DC A(PGIENT?) =7 i DC A(PGIENT? + 15) paaress of PG2 is nat DC A(PGIENT2 — known. Itistaken as0. | an PG2ENTI+PG2- oe ENT1 +4 ‘Ans. : Object records for the module PG1 PGIEN 1 | 1. ESD records 040-204 | ‘Source | Name | Type | ID | Relative | Length ue | object address ‘Addresses of PG2ENT! record and PG2 are not known Now 3. RLD rd 1 PGI sD 01 {0 60 . records evn fe | = |20 = ‘+ Relocation of variables can be handled through 2 ee segment registers. They do not appear in RLD 2 PGIENT2|LD | - | 30 : records. RLD records are for address constants. Is po2 | BR | 02 |- - . pire of two relative addresses is a constant fs | pazenra | eR | 03 | - ; erefore, the entry _—_—_—— 48 DC A (PGIENT2 - ‘sp ~ Segment definition DPE a ‘2 - PG1ENT1 - 3) will not Lp ~ Local definition, declared in the current * used by other segments. Source object segment but can be use +] es | ten ri External definition, declared fn other segments anil Flag+| Relative put can be used in this segment. or- | address «Length of the segment PG1 is 60 4 + 40 {external symbols PG2 and . Relative addresses 0” 4 is pozeNTt wire not known as yet. They are not 4 declared in the current: ‘segment. 4 + 52 sp and ER symbol is given @ unique number 4 ; 0 eo oo ) by the assembler. This ID willbe used Be “ is + 56 __ ; ar > v conject ree sp records cords for module PG2 += cms Programming & Operating System (SPPU) _3.9 length External symbol Quick Read Assigned memory add} Relative PGIENT1 address — —— - | PGIENT2 nL | _ | — 1 PG2 PG2ENT1| LD | - L-] _ | — T PG2ENT1 po1enti| ER |o2 J, - |} L_ poenth _| ____— | @.15 Draw and explain flowchart of Pass-| of two pass PGiENT2| ER [03 ; a ~ | assembler with suitable example. 2. TEXT records Pero xo Ans. = | source object record Relative | Contents No. address 16 24-27 0 17 28-31 15 18 32-35 RUD records Source object | ESD | Length (in | Flag+| Relative recordNo. | 1D | bytes) | or- | address 16 02 4 + 24 | 17 03 4 + 28 w | o3 | 4 + | 3 18 02 4 - 32 Global External Symbol Table (GEST) ‘The GEST contains every external symbol and its corresponding assigned memory address. If we assume that PG1 is loaded at location 204 and PG2 is loaded at location 268. It is shown in Fig. 3.10. 204 Pat 284 288 Pa2 0a Fig. 3.10 @.16 Draw and expl assembler. Fig. 3.11, flowchart of Pass-2 of two pass a 10 Description ® 55 stems Programming & Operating System (SPPULS td rip Recor (Hey) Ans. ms / _ Liss [ava] ter - 90 Public definition EF pusD! ‘ao. Translated instructions ang, TA ee gc Fixup records for relocation PP wo D ga Module end record. ‘MoDEN! fies the name of th ER record speci aaa ea ‘ofthe record is given below, module. The format [ans | ns | eal name | Checks SEND record marks the end of the mode MODEN! mn aotontan a reference to the entry Poin oth roerat “The format of the record is given below, gon | Length | Type (1) | Start addr (5) | Checksum | the LNAMES record contains 2 list of all the egments. A SEGDEF record designates a segne .e using an index into this Tist_ vara 1 remare] Fezl| gout | vength | Name ist | Checksum | | pitin| — [cil| I | LNAMES record 98H | Length | Attributes ‘Segment Name | Check ' (1-4) | length (2) | index (1) | Sun 17 Eiplain MS-DOS inkrin deta SGDEF record ‘Ans. : MS DOS compilers and assembler produce object modules, ‘The object module is a sequence of object records. ‘There are 14 types of object records. These records contain the following three basic categories of information : 1, Binary image (machine instructions) 2. External references 3, Public definitions. ‘The names and purpose of the object record types is given below: Record id Description type (Hey) HEADER -80._—_‘Translatorheader LNAMES 96 List of names record SEGDEF 98 — Segment definition EXTDEF 8c External definition © The EXTDEF record contains a list of exter symbols that are used in this module. Length ‘The PUBDEF record contains a list of symbols define! in the current module that can be used by other modules 90H | Length | Base ftset (2) |... ] Check Sut e-4) J Check-Sum 8cH External reference list Name the me LEDATA record contains the binary image ini ‘ Senerated by the assembler/compiler. See™*™ ard ataantifes the segment to which the code belo I Seamens eenies the location of the code witha the AO Leng | Segonnao ox These" | |‘enath| Segment index, Data otset (2) | Data |r (1-2) {sue FIXUPP records are nang a to carry: cae ‘cords are used to resolve references ant address modifications that are 25500" Brouping of segments withi® with relocation and Program. gsm conn OH TM: Ove Su 4 san overly iS 2 part ofa program where m pad origin a Some other pareof nema tee sly used 9 9 398tom Which memory does not support in static Hinking/loading, itis necessary that all the caavotines needed for execution are loaded into the jain memory at the same time. Ifthe total amount of feemory required by all these subroutines « Fount available, as is common with snall COMPULETS, We CaN get rid Of this helpof overlays. xceeds the ge Programs on Problem with the Usually the subroutines of a program are needed at diferent times. By finding which subroutines call other abroutines itis possible to produce an overlay structure gatidentifies mutually exclusive subroutines. +The Fig. 3.13 illustrates a program consisting of five subprograms (A, B, C, D and E) that require 100k iytes of memory. «The arrow indicates that subprogram A only calls B, D and E, The subprogram B only calls C and E. The subprogram D only calls E. + Procedures B and D are never in use at the same time. Similarly, C and E are never in use at the same time. + Wecan create an overlay structure as shown in the Fig. 3.13, It will require 70 k of memory. ‘A(20%) “Ae (20%) 1004] C1904) | (10%) (20%) (22h) (without overlays {b) Dynamic loading 70% 0% llocation with overlays (0 Possible storage al ) Possible storage al aaenaiore Fig, 3.13 : Storage allocation w! 5 & Operating 5, mE Operating System (SPPU) 3.14 Quick Read + In order for the overlay structure to work it is necessary for the module loader to dynamically load the various subroutines as they are needed. ‘© The portion of the loader that actually intercepts the calls and loads the necessary subroutines is called overlay manager. This scheme is called dynamic loading 0.19 Explain in datas design of editor OR Defina folowing system sofware components with suitable diagram : Editor Ans. : Editors a computer program that allows a user to create and revise a target document. The document includes objects such as computer programs, text, equations, tables, diagrams, lines and photographs. A text editor is @ program in which the primary elements being edited are character strings of the target strings. The document editing process is an. interactive user_computer dialogue designed to accomplish four tasks : 1. Select the part of the document to be viewed and manipulated. 2. Determine two to format this view on line and how todisplay it 3. Specify and execute operations that modify the target document. 4. Update the view appropriately. ‘Text editors come in the following forms. | Forms of text editors ig. 3.14 : Forms of text editors 1. Line editors It is a primitive form of editor: It requires you to specify a specific line of text before you can make changes to it. A line editor does not display the text in the manner it would appear if printed. + Ina line editor, the cursor cannot be used to move around and select a portion of the document. Stems Programming & Operating Syst APY modification is restricted 1o current line Interaction with the editor ie through a set of fer ntn4s. This makes a line editor a less USer friendly 2 Screen editors asreeh editor enables one to modify any text that Treats 08 the display screen by moving the cursor tO toe, SFE ocation The eto dole a sere al oF nett @ time, The user can seu the effect of edi fem t0n on the screen, This is very useil while Xormating the text to produce printed decuments. 3. Word processors {Lord processor recognises word as a basic enti IC's Possible tsupporta spellcheck option. A word Processor has the concept of Paragraph. A typical Word processor has the following options: y Movinga section of text from one place to another. 2. Deleting a section of text. 3. Searching a word. 4. Merging oftext 5. Replacement of word 6 Spell-check, 4. Structure editors A structure editor has awareness of the structure of document. The structure is specified by the user while creating or modifying the document. Syntax directed editor is an example of structure editor, @. 20 Explain the need of a linker in program development. What is linker ? SEAT Explain the term linker. ‘SPPU - Dec. 14, March 20, 4 Marks Ans. : Any usable program written in any language has to use functions/ subroutines. These functions could be either user defined functions or they can be library OR oR functions. For example, consider @ program written in ¢- language. Such a program may contain calls to functions like printf) and scanf(). During program execution the main program as well as functions must reside in the memory. In addition, every time a function is eo the control should get transferred to the called, ropriate function. mes makes addFess Of ny, Prieer so that transfer Of Contra} 1" sxecution: place dure ers 1s handled by the linker Passing Of Pe passed bY value OF by referene Parameters C0" Vg function must be handled ue returne — vali pie variable should have the same ada. Every publi ule. in every mod can be defined in one may, teal variable le An external ule. another modi be used in and can fan external variable should be sam, Te adres Resolving of addres of sme inevery ferences are handled by the linker. references at ————_ relocation is required and how iy, Se ee UE performe + Relocation is the process of modifying the ca ssses used in the address sensitive instructions of ; fom any designated area of memory. ‘The statement MOVER AREG, X This is an address sensitive instruction. For this instruction to execute correctly, the actual address of should be put in the instruction. Assume that a program written in C-language (let us call it A) calls a function F1. The program A and the function Fimust be linked with each other, But when in main storage shall we load A and F1 ? A possible solution J Would be to load them according to the adresse: assigned when they were translated, Case 1 translated addresses, a lot of ¢ will be wasted, torage lying between them pp wy & Operating system (sppy ell uc the time of translation, both A and Fy may hav lentical start address 100, een translated with the id. tad address goes from 100 to 250 and Figoes from 100% 7 these two modules cannot co-exist at sam: er jocations. The loader must relocate A wa ren, avoid address conflict or storage waste A, Sa relocation is shown in Fig. 3,15(b), pene + Itmay be noted that relocation is more than simph ring 2 program fFom one aren to anomie storage. It refers to adjustment of address fields not to movement of a program, ne in o © sorage A 2s0 so] 4 A 100 Ft Te 200 Translation Relocated time address address given bythe loader Fig. 3.15(b) : Relocation to avoid address conflict or storage waste 0.22 Explain the need of program relocatabilty. Rae Program relocatability refers to the ability to load and execute a given program into an arbitrary place in inemory as opposed to a fixed set of locations specified at program translation time. Depending on how and ‘when the mapping from virtual address space to the physical address space takes place in given relocation scheme, there are two basic types of relocation : 1. Static 2, Dynamic A self relocating program is 2 program which can beriorm the relocation itself. Itcontains the followings LA table of information about addres instructions in the program 2 Relocating logic that can pet the address sensitive instructions. \ Self relocating program contain the relocating eee ‘hat can perform the relocation ofthe address sensitive “structions. So there is 90 need of a linker in st ‘locating programs. ss. sensitive form the relocation of 13 ick Read Q.23. Explain dynamic loading and linking. Dynamic linking defers much of the linking Process until a program starts running. Dynamic linking involves the following steps 1 Ans. : A reference to an external module during run time causes the loader to find the target module and load it Perform relocation during run time. There are several advantages to this approach 1. Dynamically linked shared libraries are easier to create, 2. Dynamically linked shared libraries are easier to update. 3. Dynamic linking provides automatic sharing of code. If multiple applications require the same routine, ‘operating system loads a single copy of the routine and links it with multiple applications. 4. Itis easy to add new functionality to existing library. ‘These functions could be useful in a variety of applications. 5. Dynamic linking permits a program to load and unload routines at runtime. (@.24 Comment on the statement “Static binding leads to more efficient execution of a program than dynamic bindings” ‘Ans. : Static binding is created before execution of the program. It is carried out by the linkage editor which produces an executable file. Since, there is.no need for linking before calling a function during run time, it is ‘more efficient on the contrary, static binding requires more memory as linked routines are part of the executable program, a 1@.25 Why are library routines usually relocatable ? What ‘would happen if these routines are made non- relocatable ? ‘Ans, : Non-relocatable program must be loaded at a fixed place in the memory. This is a serious limitation in multiprogramming environment. In addition a swapped cout process can be swapped in at a different memory location, If multiple programs use the same library routine then it will be impossible to run them together. 0.1 What is an operating system ? SE Explain the term : Operating System. Ese OR Ans. : An operating system isan interface between Use'S and the hardware of a computer system. Itis a system software which may be viewed as an organised collection of software consisting of procedures for operating a computer and providing an environment for execution of programs (©.2 Epa uncer of an Operating Syste (OR Eien sens oteed by operating syste ome ‘© The operating system provides services in the following area: ‘Services of operating ‘yet Program development 9 Acouning ig. 4.1 : Services of operating system 1. Program development Operating system provides a set of utility programs which are necessary for program development, ‘These utilities include 1. Editor 2 Debugger 3, Compiler 4. Interpreter 5, Linker Loader 3. sn handles Toaditg 24 Schein era petites a2 INVOIVEAinpropns . instructions and data ization of files and 1/0 devices 2 ‘Allocation of other resources. 3. /0 operations 7 en program may require 1/0. Uses are owed to control 1/0 devices direct. Operating fystem provides 2 uniform interface and hy details of 1/0 devices from the user. ‘Therefore ay peraing system must provide means for doing File system manipulation ‘An operating system provides various system cals for manipulation of files. Details of the underlying secondary storage remain hidden from the user. addition, in a multiuser environment, the operating system must provide protection mechanism to control access to the files. Communication Under many situations a process has communicate with another process. Communication 's required for exchange of information. Sutt communications may occur between two process Tunning on the same computer or diferett” ‘mputers. The communication between? Processes is imy plemented by the operating syste™ ‘through the following. techniques 1. Shared memory 2 Pipe 3 Message passing ch “ree sharing and protection ati proces, at Protection of resources alloted? | ultiprogre 424 by the operating system. [8 | iter nk # Process is not allowed ® | ensuri rer proces rrotection invol¥™ Ping that ae ese, Protection i controlled, ‘eSSe5 to system resources frror detection pillerent "Pes of errors may occur while a computer system is running. These errors could be due to memory error, connection failure, error in 10 devices et For each type of error, the operating system should take appropriate action to ensure consistent computing. Resource allocation Computer resources are managed by the operating system, These resources include : 1. Processor 2. Memory 1/0 devices When multiple users run their programs, resources must be allocated to them. 3. Filestorage 4, 9. Accounting Each operating system is required to keep track of which users use how much and what kinds of computer resources. Usage statistics are useful in fine tuning computer services. 3 List different types of operating systems with examples, SEEN ns. : + Operating system has evolved over a period of time. In particular, these are Evolution of operating =a} Smaregannna | Evolution of operating systems * An operating system may process its tasks serially or concurrently (several tasks simultaneously), In serial execution, the entire system remains dedicated to a single program. Inconcurrent processing, operating system executes "nultiple programs in interleaved fashion. Seial Processing ual intervention after ff development and Serial processing involves man every step. The process 0! tonne Programing & Operating System (SPPU) 3-15 Quick Read slow due to serial processing and manual intervention. In atypical sequence 1. Editor is called to create source code of user program written in a programming language. 2. Compiler is called to convert a source code into binary code. 3. Loader is called to load the executable program into main memory for execution. © The serial mode of execution is not efficient. Time is, wasted after every step due to manual intervention. This results in low utilization of resources. * In early computer systems, instructions and data used to be entered through hexadecimal keyboard. Advent of input/output devices, such as punched cards, paper tape and language translators brought a significant step in computer system utilization, ‘+ The next development was the replacement of card- decks with standard input (keyboard) / output (monitor). > Batch Processing ‘+ Im batch processing, the sequence of operations involved in program execution is automated. In addition, programs with similar requirements are batched together and run through the computer as a group. ‘+The central idea behind the simple batch processing scheme was the use of a piece of software known as ‘monitor. The monitor is always resident in memory. [tautomatically sequences one job to another job. ‘+ Resident monitor acts as per the control statements given by a programmer. ‘+ Thecontrol statements are for: 1. Compiling a program 2. Loading a program 3. Executing a program ‘+ Control statements are specified using job control language. ‘An example of job control language is given below $JOB - First card of a job $TC - Execute the C-compiler SLOAD - Load program into memory SRUN - Execute the user program SEND - Last card of the job ammo Systems Programming & Operating System (SPPU)_3-16 in for input/OUutput operatio, Multiprogramming ant job waits for input/OUtPUt Operation, fe cure i + Mutiprogramming increases resource utization. When the CUT TT atyays keep CPU OF input/outyy complete, the CPU can take up next job for execution. A sina devices busy at al times ing approach allow mi torre nee ao, stems Serene meting fra + In order to increase the resource ulization, systems SU st programs C. (Or syst one job (program) to tize CPU time at any moment. More the number oP mn resources, the better willbe resource utilization. Me f sa number of programs (Fig: 43) + Inmultiprogramming, the main memory ofa system contain Monitor Program 1 Program 2 Program N Fig. 4.3: A multiprogramming system with N jobs ‘+ The operating system takes one of the programs and start executing, Let us consider a system executing two programs. * During execution of program 1, it may require input/output operation. In sequential execution (Fig, 4.4), the CPU will sit idle, In multiprogramming system (Fig, 45), the operating system will simply switch over to the next ay SS a Program Program 2 Fig. 4.4: Sequential execution P2 Pa. Biya Execution in multiprogramming environment © Multiprogramming increases resource utilization, Q.4 List the var various ‘ypes of a functions. a ‘+ [can support multiple simultaneously interactive users (terminals) ‘Ans. : * Compare to sequential operating system, multi- programming operating systems are complex. + Memory sharing, memory _ protection, synchronization are some of the important issues in ‘multi-programming environment. There are di ‘These include ferent types of operating system® Fig. 4.6 : Types of operating systems 0.5 Whatis real time operating system? oR What is real time operating system?Expain its types with suitable examples? + In this form of operating system, a large number of events mostly external to computer systems, must be accepted and processed in a short time or within certain deadlines. ‘+ Examples of such applications are flight control, real time simulation, process industry ete. + Primary objective of real-time system is to provide quick response time. Resource utilisation is of secondary concern in a real-time system. + In real-time system there is a little swapping of programs between primary and secondary memory. Most of the time, processes remain in primary memory in order to provide quick response. + Time-critical device management is one of the main characteristics of real-time system. It also provides sophisticated form of interrupt management and input/output buffering. * The primary objective of file management in real- time systems is usually the speed of access rather than efficient utilization of secondary storage. ‘system ? List types of system callsand explain any OR List the categories of system calls and orci stem awh an exe. OR Write short notes on : System Call Soe explain Spe List the different categories of system calls and explain in briet any two of them. Ans. : System calls provide an interface to the services made available by an operating system. User program interact with operating system through system cails. These calls are normally available as. library functions in a high level language such as C + Inn assembly language, necessary parameters are stored in specified CPU-registers and then it issues a software interrupt instruction. System calls in DOS are availed by using “INT 21H”. + Execution of the following instruction to read n bytes from a file = Count read (filepointer, buffer, n}; ‘+ will internally make a system call to read n bytes from the specified file and the data will be stored in the array buffer. + The number and type of system calls varies from operating system to operating system. * In general, system calls are available for the following operations 1. Process management 2. Memory management 3. File operations 4. Input/Output operations Advantages of system calls * Most of the programming languages have a built-in library. These library functions work as the link to system calls made available by the operating system, It provides a level of abstraction. The caller need know nothing about how the system call is implemented or what it does during execution. Details of the operating-system interface are hidden from the programmer. ‘+ Different hardware services can be availed through system calls. ene @.7 Draw and explain layered approach with advantages and cisadvantages. ‘Ans. : The operating system architecture based on layered approach consists of number of layers, each built on top of lower layer. A typical layered architecture is shown in Fig, arom & systems Programming & operaung system (sppu)_ 318 a Wick Hey 8[_User pmarame a] Bateman HO dewwes Fig. 4.7: A typical layered operating system * Layer 0 deals with hardware. * Layer I deals with allocation of CPU to processes. Layer 2 implements memory management such as Paging, segmentation ete. Layer 3 deals with device drivers. Device drivers Provide device independent interaction with devices. * Layer 4 deals with input/output buffering ‘The highest layer 5 deals with user interfaces. Advantages of layered approach 1 Layered approach provides modularity. It helps in debugging and verification of the system, Higher layer utilizes services provided by lower layers. A higher layer need not know how these operations are implemented only what these operations do. 3. Any layer can be written and debugged without any concern about the rest of the layers, Disadvantages of layered approach 1. The major difficulty with the layered approach is how to differentiate one layer from another. 2. Since a layer can use services of a layer below it, it should be designed carefully. For example, the device driver for secondary memory must be at a lower level than memory management routine, Q. Draw and explain client server model with and disadvantages, vantages Ans. : Client-Server computing has become very popular. Ithas been replacing both main-frame systems and other computing environments based on centralized approach. In a client-server operating system the kernel part (core of the operating system) is very small. the operating, system functions Most gunted using USEF PFOCESS This Mogg service, such as reading a file," cinds a request to a Server process ree gig), the serverprocess does the oe 1s hack the answer, implement request 8 at om Teauireg work and send: “Fig. 48: In this model, the kernel handles the communication between clients and servers. Independent serve, processes handle different aspects of operating systems. These processes are: 1. File server. 2, Process server. 3. Terminalserver. 4 ‘These servers run asuser-mode processes ‘The client server model can also be used in g distributed environment as shown in Fig, 4.9, Memory server, Machine! Machine 2 = Machine3.—=s Machne 4 File Process Terninal aw server sever server Kern Kemet Kernel | Komet Message irom client to server A client server model provides 1. High scalability, 2, Reliability 3. Faulttolerance, 4, Security. 5: Reduces toad on network, ne NWork 2-9 Explain process in deta OR Whatis Process, Ans, SPPU ~Dec. 15, 3 Mars TES A process is by, asicall is bel executed, 'Y @ Program while it is being Process is more than program code. It the followings also include: 1. Value of program counter, 2 Contents of cpyy register. oo @ommmoD process stacks contai ig temporary data (a Jocal variables). aman 1. bata section containing global varabies, «Program code 4 Dynamically allocated memory during runt untie. A program in itself is not a process A program is a passive entity, whereas a process isan active entity A program becomes a process when an execatable programs loaded into memory. ™ 9.10 Draw and explain process state transitions on olen various states ofa process wih diagram oa aa What cs to varows stn cf prasenaoe ie ce is managed by operating system ? om Draw and explain ve state model fprocosssats, See an «The lifetime of a process can be divided into several stages as states, each with certain characteristics that describe the process. + It means that as a process starts executing, It goes through one state to another state. Each process may be in one of the following state: Ready Blocked 1. New 2. 3. Running 4. 5. Terminated. +A general form of process state diagram Is shown in Fig, 4.10. (4) Time slab over () Admit (5) Blocked for 1/0 (6) 1/0 activity is over ©) Dispateh for @)Retease Fig, 4.10 : Process state transition diagram ick Read 1. New “The process has been created. 2. Ready © The process is waiting to be allocated to a processor. Process comes to this state immediately after it is created. All ready processes are kept in a queue © A program called scheduler, which is a part of the operating system, picks up one ady process for execution by passing control to it 3. Running + ACPU is currently allocated to the process and the process is getting executed © A running process is blocked if there is an 1/0 request during execution. + Arunning process is sent to the ready queue after the time slab is over. After the time slab, the scheduler may schedule another process from the ready queue for execution. 4. Blocked «The process is waiting for completion of some 1/0 activity. © Such processes are normally not considered for execution until the related blocking condition is fulfilled. «The running process becomes blocked by invoking 1/0 routines, whose result is needed during execution. ;. Terminated : The process has finished its execution. @.12 Explain various process states with suitable process state diagram. SEE ‘Ans. : A seven state process model has the following states: New Ready Running Blocked Blocked suspended Ready suspended Exit ‘A T-state process state transition diagram is shown, in the Fig. 4.11. Fig. 4.12: The process state transition diagram (7-state) 1. New : It contains process which have newly come for execution, 2. Ready : Contains the processes which are in main memory and ready for execution 3. Running : Process which is executing 4. Blocked : Contains the processes which are in main memory and awaiting an event occurrence. Blocked suspended : Contains the processes which are in secondary memory and awaiting an event occurrence, 6. Ready suspended : Contains the processes which are in secondary storage but is available for execution as soon as itis loaded in main memory. 7. Exit : Contains the processes which are completely executed. Q. 13 Write short notes on : Process Control Blook. OR Draw and explain process control block. SEALE ENT OR Explain use of process contro! block and all fields in brief. Ans. : A data structure called the process control block (PCB) is used by the operating system to keep track of all, information concerning a process. The operating system maintains a table of process control blocks with one entry per process. The process control block contains many pieces of information associated with a specific process, including: 1, Process number : Each process is identified by its process number, called process ID. 2, Priority. proces stat vss may be in any Of thes, fe Fach pro states () Ready (a) New (a) Blocked ning (Ru inated (e) Term or : Itgives the address of the next jon to be exe instruction they include accumulator, genera, Registers * , index registers, SeBment registers prose reisters 1 gsor switches Over fFOm one ete. Whenever acess to anol Pi current status of that the process may The proce ‘ner process, information about frthe old process is saved in PCB so be restarted later on. .¢5 scheduling consists of the following sub-functions : Scheduling : Select the process to be executed next on the CPU. Dispatching : Set up execution of the selected process on the CPU. Context save : Save the status of a running process when its execution is to be suspended. Passing of CPU control from process to process? and then back to process1 is shown in Fig. 4.13. Exocuting Process 1 oload context of Process 2 trom Pcs Exocuting Save context of Process 2 in| ans. certain kind of concurrent applications. SPPU Dec. 14, May 15, detail, i ag Explain threads in EEE ‘What is thread. ‘Compare thread and proce Marks SEPU Nay 18.2 Marks 88, | SPU - Dec. 19,2 Marks : Threads are low cost alternative 0 processes for Each process has an address space and thread of control. In many case a single it is desirable to have multiple threads of control that share address space, but run in quasi-parallel, a were in fact separate processes (except fo address space). a single if they shared Traditionally, there is single thread of execution per process (Fig. 4.14). | = Inston S| os Fig. 4.14: One process one thread In multithreading environment, multiple threads process (Fig. 4.15). 0S. supports of execution within a single Fig. 4.15: One process multiple threads A process is defined as the unit of resource allocation and a unit of protection, The followings are associated with a process Avirtual address space holding the process image. Protected access to processors, files and 1/0 resources. Within a process, there may be one or more threads, ‘each with the following A. thread execution suspended, etc.) {A process control block (PCB) for each thread for saving the thread context. Let us consider a web server application. A web server may have several clients accessing it. One Solution isto have the server run as a single process that accepts requests. state (Running, ready, * When the server receives a request it creates 2 separate process to service the request. + This approach is quite slow as each process has its own code, data and files. It is more efficient to create a thread to service the request. + Multiple threads created by a process share code, data and files, Itis shown in Fig. 4.16, com [om] vonsen [sack rena Je threaded process tm ie saer | Regs | Roosters reed preoetes |e stuck _| sock | sacs (b) Multithreaded process Fig. 4.16 : Single threaded and multithreaded process . 15 List down benefits of thread. ‘Ans. : It takes less time to create a thread in an existing process than to create a new process, It improves responsiveness. 2. Ittakes less time to terminate thread than a process. It takes less time to switch between two threads within the same process. 4 ‘Threads share the memory and the resources of the Process to which they belong. It allows an application to have several different threads of activity within the same address space. ‘Threads enhance efficiency in communication. They can interact’ with each other the without intervention of operating system. 16 Explain process scheduling with neat diagram. EEE Process scheduling is a fundamental operating system function, ‘Ans. : W gens opening opera geen and_mechanisms + Scheduling is a set of poli supported by operating system that controls the order in which the work to be done is completed. +A scheduler is an operating system program that selects the next job to be admitted for execution. ‘There are performance criteria that are frequently used by schedulers to maximize system performance, © Theseare Performance criteria tor process scheduling Response amo] Fig. 4.17 : Performance criteria for process scheduling In addition to maximization of system performance, operating system should take into account fairness. That is, each process gets its fair share of the CPU. 1. CPU utilization The idea is to keep the CPU busy 100 percent of the time. 2. Throughput It refers to the number of processes executed per unit time. Turnaround time It is defined as interval from the time of submission ofa process to the time of its completion, 4. Waiting time + The waiting time may be expressed as turnaround time, less the actual processing time * waiting time = turnaround time - processing time, ‘+ In multiprogramming operating system several jobs reside at a time in memory. CPU executes only one job ata time. The rest of jobs wait for the CPU, 5. Response time ‘+ Response time is an important parameter in time sharing system. It is defined as interval from the time the last character of a command line of a Treo the last result APPEAES on ty js enter program reriminal py utilisation may be increaseg 4 ThroughPat 4 ge number of processes, but then py executing 2 IY suffer. Therefore, the schedule, ress CMe Oye erent require ap balance must Keer) nd constraints — . r dulers cing pes of Se PEEL ea 1 schedulers? Explain them wit Poe REE lers : €@.17 Explain te fl {shor Term {iy tong Tem {uy Medium Term what are the types O suitable diagram”? are three types of schedul types of schedulers oR ‘Ans. : There 3. Shon term 4.18 : Types of schedulers 1. Long term scheduler ‘+ Long term scheduler is also called job schedule ‘This determines which job shall be admitted for processing. Long term scheduler Short term. ‘scheduler Reac on End of joo Fig. 4.19: Long term and short term scheduler There are oo ere More processes than it can be are kept pee by CPU in memory. These processes 1B in large storage devices like disk uuming & Operating § /0 bound, the empty. the ready queue wit . processes are CPU bound then sy become poor. ystem response short term scheduler led very often called the end of time stab, Called in case of 1/0 request. 3. Medium term scheduler + Most of the processes require 1/0 operation. in that case, it may become suspended for 1/0 operation sr runninga while 4 It is beneficial to Temove these processes (suspended) from main memory to hard disk to create more memory for other processes, At some later time these processes can be reloaded into memory. The suspended processes are swapped out and swapped in by medium term scheduler. 2:18 Explain scheduling ertera? Belin aliferentypes of scheduling algorithms in bit OR Explain preemptive concept wih example SEE OR Explain non preemptive concept with example. BREE Ans, * CPU scheduling algorithms deals with the problem of deciding which of the processes in the ready queue to be allocated the CPU. Scheduling algorithms can be classified into two categories ‘Scheduling algorithms 7 Preempwve schediiog 420: semting a0 tem (SPPU)_3.23, quick Read 1. Preemptive scheduling Im preemptive scheduling, the CPU can be taken away from the process. A process temporarily suspended due to 1. Request for 1/0. can be 2. Time slab is over. Non-preemptive scheduling In non-preemptive scheduling, a process runs to its, ‘completion. Once a process has been given the CPU, the CPU cannot be taken away from that process. Non-preemptive algorithms are simple and easy to ‘implement. * Nonpreemptive algorithms are not suitable in ‘multi-user environment. @.19 Explain following CPU scheduling techniques with example : FCFS. ‘Ans. : It isa long term scheduling algorithm. It is one of the simplest scheduling algorithms, in which jobs are executed in the order of their arrival (Fig. 4.21). mi] feu} ey aa Tell Fig. 4.21 : First-Come-First-Served scheduling Its implementation involves maintaining a queue of arriving jobs. Whenever the CPU is free, a new job from the ready queue is assigned CPU, Once a process has the CPU, it runs to completion, @.20 Explain following CPU scheduling techniques with ‘example : SUF. Ans.: + In Shortest-Job-First (SJF) scheduling, a job with shortest execution time is selected for execution. Iftwo processes have the same CPU time, FCFS is used. Consider the following example of three processes : Process Burst time / Execution time jes Socution time | | pL 20 P2 5 ie | ps | 4 Using SJF scheduling, we would schedule these processes according to the following Gantt chart | ig the CPU time is divideq Shortest job 2 is selected f 0. |e Inround rece) Each process is allocated one 8 The job P2 finished attimeg. eee one time slice sf 2 Gime for cess is given Finally, the job P1 is selected for execution at time 7. ples execution. Start and finish times of processes + time slice, the PFOCESS 80s to the are after the ond oF Oi process from the front of ‘end of ready ae for execution (as shown in ready queue #5 Fig. 4.22). Completed fa] Ee Aer Proomplion _ . l ‘A new table with turnaround time and waiting time “a2 : Round robin scheduling is shown in Table 4.1, = " ‘Atime slice is usually of 10 to 100 millis . ~ too many [s s) cru leat a —| + setting the quantum too short causes too r Sr. | Process | cpu ‘Start | Finish | Turnaround | We ing | process switches and lowers the CPU efficiency, No.| No. Time Time | time | Tine. | ‘Time Setting the quantum too long may cause poor Pr jaw 7 | a 7 7 response to short interactive requests. 2) abot © Round robin scheduling utilises the system Tt of 8 : : resources in an equitable manner. Small process 3]; pm fala] 7 7 3 may be executed in a single time-slice giving good res yhereas long processes may require Average > ‘7 108 ;ponse time wh * ee aeeeercalt aes es and thus be forced to pass £12.93 | =333 through ready queue a few times before completion, ‘* SIF algorithm is an optimal scheduling algorithm in e 2.22 Consider the following set of processes for round terms of minimizing. robin scheduling 1. The average waiting time. Find waiting time and tumaround time of each 2. The average turnaround time. rocess. Assume time slice = 2 units, © SJF algorithm does not guarantee fairness. If shorter Process Name | Arrival Time Processing Time jobs keep joining the ready then a relatively longer ra job may have to wait infinitely. ° 3 * The optimal performance of SJF scheduling is {1 | 5 dependent upon future knowledge of the 5 Co process/job behaviour. It is very difficult to estimate the exact CPU time requirement of a job/process, ;>—2_| Soe] 21 Wiite short notes on : Round Robin Scheduling Li | Los | aa ns: ‘The round robin scheduling algorithm is primarily used in a time-sharing and a multi-user system, The basic requirement is such systems is to provide = asonably good response time and in general to res system fairly among all system users, Next job to be executed Pi for2 eres 2 time units P2 for 2 time units «stems Programming & Ope Ready Queue “ie ‘ext job to he Ans. : SJF Scheduling {executed « _ J Gantt chart = P38 | > [PIAPB*P2 | PLiort time ng P,| P| Pej Pa _| Pifinishes P3 for 2 time units, 049 15 2 43 finishes Calculation of the average waiting time and average | P2 forztime unas turn-around time |] CD) Short job P2 is selected for execution at time 0. | PA for 2 time units @) | p2k shorter job is selected for execution at time 4. | P2 for 1 time unit The job P2 finished at time 4 | P2 finishes. : || (3) Next shorter job P4 is selected for execution at time mits |] 9. P4 for 2 time | PS for 2 time units (4) Finally the job P3 is selected for execution at ime eu 1s, P4 for 1 time unit. LP4 finishes Start and finish times of processes are PS for 2 time units Table 4.5 re Time | Start Time _ Finish Time PS for 1 time unit. Ervceeres] CEUs) ol [eda ARP] [=[a[a [a [= Step2: A table with turnaround time and waiting sneis shown in Table 4. ‘Anew table with turnaround time and waiting time Table 4.4 is shown in Table Ex. 4.5(a). ‘Process | Arrival | CPU | Finish | Tumaround | Waiting | tir time | time Ho | No. | tne | tene | time Sr. | Processes | CPU | Start | Finish Tumaround) Waiting a | o fsa] s 5 2 No. Tine [Time Time Time Time _ zie [a fsfe[ in 8 1] mh [ols 9 9 4 3) PB 3 [2 [7 4 2 2 4 o ma | 9 fs | wi 8 eS 3 | 2 8 Br p= | zfs | o| 8 Sy 6 | 9 28 Consider the following processes where Arrival and ‘Average —> 504=125 284=7 Burst ti “shown below ne vAmal ume Tum-around Time it the processes are scheduled Waiting time = Turnaround ~ CPU time Using SUF. @.24 Consider the folowing processes where Arval and Process | Burst Time Burst time (in seconds) are as shown below P, 05 Calculate the Average Wating Time and Average Pr of ‘um-around Time it the processes are scheduled Py 7 using FCFS, Pe 06 arm = mer problem ists Programming & operating system (SPU #2 Fi cer / const eee st Tin — ion €0 ~ sige of the buffer * | Process | Burst Time | Arival Time sontion OF sine fer | oe | 1 paerine N 3° je For mutually exclusive oT | utex . }P2 | 4 | semaphore ™ accesso srared uller"/ a nu I number of empty buffer | wy 2Ni 5 semapnore PONE cap tat Na Attiva CPU Star Finis | Waitin e|tim! t | oh gtime : time| time Bi L717 7] 7 ‘Turn around time = Finish - Arrival ‘Turnaround ~ CPU Waiting Time 25 Explain Producer Consumer problem wih sluon. SERENE What is Preducer-ConsumerProiem ? How to sohe itusing SemaPhoce and Mitox? ‘Ans, + Its one of the most common problems found in Concurrent processing, TWo processes share are ‘common, fixed-size buffer for exchange of information : 1. The producer puts some type of data (information) into the buffer. 2. ‘The consumer takes out data from the bute. oR Problems 4. Producer tries to puta new data in the buffer that is already full. Producer should go to sleep. It should be awakened by the consumer after consumer has removed one or more data from the buffer. Consumer tries to remove a data from the empty puffer. Consumer should go to sleep. It should be gwakened by the producer after putting some data inthe buffer. zr number of lled up al . semaphore f puffer slots */ | vid producer O | ( while (true) ( produce 0: wait empty)” wait (mutex) append (0); /* puta data into buffer */ signal (mutex) ; signal (full); } void consumer 0) { while (true) | | wait (Full); | wait (mutex) ; take (); /* take a data from buffer */ signal (mutex); signal (empty) | 4. Buffer should be acessed mutually exclusively That | ?- €™Pty For count slots in the buffer. re only either producer oF consumer should access | 3. mutex ; ING of empty slots in the buffer fer at any given time. To make the buffer atany ai e sure that both prod 1 —hL jucer and pe & Operating 5) stem (SI sons nity 0 PPU) 3:27 wick Read finpty 1S initially equal to numbe Ans ie ber of slots in the | © Database applications are very common, where 4 tte isin many processes try to perform read and write * pel semaphore nse tha he prod ‘operations. Following conditions should be satisfied running when the buffer is ful jer sts 1. Any number of readers may simultaneously |, The empty semaphore a ensures that the consumer read the database sqops running when the buffer is empty. only one write database at any given time. 3. Ifa writer is writing to the dats G8 Eqlain “Readers and Waters Problem Sa ay 16,3 ‘gution to readers / writers problem may read it. Semaphore mutex = 1; /* controls access to readcount controls access to database */ + Semaphore dl 0; /*number of processes reading or waiting to read */ | int readcount void reader Q) ( while (true) { wait (mutex) ; /*get exclusive access to readcount*/ readcount = readcount +1; if (readcount == 1)/*ifitis the first reader*/ wait (db) ; /*wait for exclusive access "/ signal (mutux); /*release exclusive access toreadcount */ read_database () ~ wait (mutex) ;/*8e' Readcount = readcount - 13/* if (readcount =: 0)/*iflast reader*/ signal (db) ; signal (mutex) ; st exclusive access to readcount */ ‘one reader is less*/ sadcount */ release exclusive access tre } |) | oid writer () ( while (true) { wait (db) + /* get ‘exclusive access */ wwrite_database (: /"update database */ signal (ab); /*7!e28" exclusive access */ 1+ is allowed to write the abase, no reader e< fee Mh Quick tea Systems Programming & Operating System (SPPU)_3-28 her acquires two FOFKs successfully, If a philoso * The semaphore mutex provides mutually exclusive access to variable readcount. + The semaphore db provides mutually exclusive access to database. Multiple readers are allowed to perform read operation, simultaneously. * This algorithm gives priority to readers over writers * The first reader entering its critical section has to wait using the semaphore db. Subsequent readers. simply enter their critical sections after incrementing readcount. * As readers leave their critical sections, they decrement readcount. The last reader leaving the critical section, signals awaiting writer. (2. 27 Explain dining philosophers problem with sokution. Ts The dining philosopher problem can be stated as follows : * Five philosophers are seated around a round table. Each philosopher has a plate of spaghetti. There is a fork between every pair of adjacent plates, * Aphilosopher needs two forks to eat spaghetti. Each Philosopher alternately eats and thinks. When a Philosopher gets hungry, he tries to acquire his left and right fork, one ata time, in either order. then puts down the forks 4, ‘the table is shown in Fig. 4.23 Tats for a while, ontinues to think « ‘the algorithm must satisfy” muyay + Problem“ adlock and starvation should 4, exclusive Dea woided. , ‘lock will arise if each philosopher picks up ong Deadlock wil hand waits for another fork. Deadlock cay for ea py allowing only four philosophers, nth, be avers with four philosophers, atleast one dining room. philosopher will have access to two forks. semaphore forks [5] = (1, 2,1. 2, 10 a semaphore room = y; ] | | inti; void philosopher (int i) /*i gives philosopher number 0 to N-1*/ { while (true) { think Q; wait (room) ; wait (fork (i) ; wait (fork ((1+1)%5)) ; eat; signal (fork((i+ 1)%5)) ; signal (fork (i)) ; | Signal (room) ;

You might also like