The document provides an overview of operating systems, specifically focusing on UNIX, its structure, and its various implementations. It details the functions of the UNIX kernel, the shell, and the vi editor, including commands for editing and managing files. Additionally, it covers essential UNIX commands and practical exercises for using commands like cat, sort, cut, and paste.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
18 views42 pages
Operating Systems
The document provides an overview of operating systems, specifically focusing on UNIX, its structure, and its various implementations. It details the functions of the UNIX kernel, the shell, and the vi editor, including commands for editing and managing files. Additionally, it covers essential UNIX commands and practical exercises for using commands like cat, sort, cut, and paste.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42
OPERATING SYSTEMS
Introduction to UNIX and OS Programmiing
Whatt iis OS? An operating system (OS) is a resource manager. It takes the form of a set of software routines that allow users and application programs to access system resources (e.g. the CPU, memory, disks, modems, printers network cards etc.) in a safe, efficient and abstract way. Whatt iis UNIIX? The UNIX Operating System (OS) is a large program (mostly coded in C) that turns the computer into a useable machine. It provides a number of facilities: Multi-user Multi-tasking Stability Portability directory and file system Powerful networking capabilities Loading / Execution / Suspension of programs Flavors of UNIX UNIX is not a single operating system. It has branched out in many different directions since it was introduced by AT&T. The most important `fork()' in its history happened early on when the university of Berkeley, California created the BSD (Berkeley Software Distribution), adding network support and the Cshell. Here are some of the most common implementations of UNIX. BSD : Berkeley, BSD SunOS : Sun Microsystems, BSD/sys 5 Solaris : Sun Microsystems, Sys 5/BSD Ultrix : Digital Equipment Corporation, BSD OSF 1 : Digital Equipment Corporation, BSD/sys 5 HPUX : Hewlett-Packard, Sys 5 AIX : IBM, Sys 5 / BSD IRIX : Silicon Graphics, Sys 5 GNU/Linux : GNU, BSD/ Posix THE UNIX STRUCTURE The Kernell The parrtt off tthe operrattiing systtem tthatt iintterractts diirrecttlly wiitth tthe harrdwarre off a computterr usiing deviice drriiverrs buiilltt iintto tthe kerrnell.. Majjor ffuncttiions manage computterr memory conttrroll access tto tthe computterr maiinttaiin tthe ffiille systtem handlle iintterrrruptts & errrrorrs perrfforrm iinputt and outtputt serrviices allllocatte tthe rresourrces off tthe computterr among userrs The Shellll Reads commands and iintterrprretts tthem as rrequestts tto executte a prrogrram Command IIntterrprretterr Prrogrrammiing Language allllows userr tto conttrroll off how and when commands arre carrrriied outt Sttarttiing // Fiiniishiing your Accountt Each userr has ttheiirr own space on ffiivedotts,, calllled ttheiirr accountt.. Type yourr llogiin IID and passworrd tto entterr yourr accountt.. Onlly iiff tthe llogiin IID and passworrd mattch wiillll you be llett iin.. Logiin tto your Accountt Logiin:: ad you ttype your IID and RETURN.. Password:: You ttype your password and RETURN.. IItt does nott appear.. $ The UNIIX promptt ((or siimiillar)).. You can now entter commands.. Password Tiips NEVER ttellll anyone your password.. Don’’tt wriitte iitt down.. A good password iis:: 8 ((or more)) charactters llong uses a miix off upperrcase and llowerrcase lletttterrs,, numberrs,, and symbolls You can change your password wiitth tthe passwd command ((see llatter)).. Logoutt ffrom your Accountt Logoutt or ^D ((Press CONTROL and D ttogetther)) or exiitt How to Use the VI Editor The vi editor is available on almost all Unix systems. vi can be used from any type of terminal because it does not depend on arrow keys and function keys--it uses the standard alphabetic keys for commands. vi (pronounced "vee-eye") is short for "vi"sual editor. It displays a window into the file being edited that shows 24 lines of text. vi is a text editor, not a "what you see is what you get" word processor. vi lets you add, change, and delete text, but does not provide such formatting capabilities as centering lines or indenting paragraphs. This help note explains the basics of vi: opening and closing a file moving around in a file elementary editing Starting vi You may use vi to open an already existing file by typing vi filename where "filename" is the name of the existing file. If the file is not in your current directory, you must use the full pathname. Or you may create a new file by typing vi newname where "newname" is the name you wish to give the new file. To open a new file called "testvi," enter vi testvi On-screen, you will see blank lines, each with a tilde (~) at the left, and a line at the bottom giving the name and status of the new file: "testvi" [New file] vi Modes vi has two modes: command mode insert mode In command mode, the letters of the keyboard perform editing functions (like moving the cursor, deleting text, etc.). To enter command mode, press the escape &<Esc> key. In insert mode, the letters you type form words and sentences. Unlike many word processors, vi starts up in command mode. Entering Text In order to begin entering text in this empty file, you must change from command mode to insert mode. To do this, type ‘i' Nothing appears to change, but you are now in insert mode and can begin typing text. In general, vi's commands do not display on the screen and do not require the Return key to be pressed. Type a few short lines and press &<Return> at the end of each line. If you type a long line, you will notice the vi does not word wrap, it merely breaks the line unceremoniously at the edge of the screen. If you make a mistake, pressing <Backspace> or <Delete> may remove the error, depending on your terminal type. Moving the Cursor To move the cursor to another position, you must be in command mode. If you have just finished typing text, you are still in insert mode. Go back to command mode by pressing <Esc>. If you are not sure which mode you are in, press <Esc> once or twice until you hear a beep. When you hear the beep, you are in command mode. The cursor is controlled with four keys: h, j, k, l. Key Cursor Movement h left one space j down one line k up one line l right one space When you have gone as far as possible in one direction, the cursor stops moving and you hear a beep. For example, you cannot use l to move right and wrap around to the next line, you must use j to move down a line. See the section entitled "Moving Around in a File" for ways to move more quickly through a file. Basic Editing Editing commands require that you be command mode. Many of the editing commands have a different function depending on whether they are typed as upper- or lowercase. Often, editing commands can be preceded by a number to indicate a repetition of the command. Deleting Characters To delete a character from a file, move the cursor until it is on the incorrect letter, then type ‘x’ The character under the cursor disappears. To remove four characters (the one under the cursor and the next three) type 4x To delete the character before the cursor, type X (uppercase) Deleting Words To delete a word, move the cursor to the first letter of the word, and type dw This command deletes the word and the space following it. To delete three words type 3dw Deleting Lines To delete a whole line, type dd The cursor does not have to be at the beginning of the line. Typing dd deletes the entire line containing the cursor and places the cursor at the start of the next line. To delete two lines, type 2dd. To delete from the cursor position to the end of the line, type D (uppercase) Replacing Characters To replace one character with another: 1. Move the cursor to the character to be replaced. 2. Type r 3. Type the replacement character. The new character will appear, and you will still be in command mode. Replacing Words To replace one word with another, move to the start of the incorrect word and type cw The last letter of the word to be replaced will turn into a $. You are now in insert mode and may type the replacement. The new text does not need to be the same length as the original. Press <Esc> to get back to command mode. To replace three words, type 3cw Replacing Lines To change text from the cursor position to the end of the line: 1. Type C (uppercase). 2. Type the replacement text. 3. Press <Esc>. Inserting Text To insert text in a line: 1. Position the cursor where the new text should go. 2. Type i 3. Enter the new text. The text is inserted BEFORE the cursor. 4. Press <Esc> to get back to command mode. Appending Text To add text to the end of a line: 1. Position the cursor on the last letter of the line. 2. Type a 3. Enter the new text. This adds text AFTER the cursor. 4. Press <Esc> to get back to command mode. Opening a Blank Line To insert a blank line below the current line, type o (lowercase) To insert a blank line above the current line, type O (uppercase) Joining Lines To join two lines together: 1. Put the cursor on the first line to be joined. 2. Type J To join three lines together: 1. Put the cursor on the first line to be joined. 2. Type 3J Undoing To undo your most recent edit, type u To undo all the edits on a single line, type U (uppercase) Undoing all edits on a single line only works as long as the cursor stays on that line. Once you move the cursor off a line, you cannot use U to restore the line. Moving Around in a File There are shortcuts to move more quickly though a file. All these work in command mode. Key Movement w forward word by word b backward word by word $ to end of line 0 (zero) to beginning of line H to top line of screen M to middle line of screen L to last line of screen G to last line of file 1G to first line of file <Control>f scroll forward one screen <Control>b scroll backward one screen <Control>d scroll down one-half screen <Control>u scroll up one-half screen Moving by Searching To move quickly by searching for text, while in command mode: 1. Type / (slash). 2. Enter the text to search for. 3. Press <Return>. The cursor moves to the first occurrence of that text. To repeat the search in a forward direction, type n To repeat the search in a backward direction, type N Closing and Saving a File With vi, you edit a copy of the file, rather than the original file. Changes are made to the original only when you save your edits. To save the file and quit vi, type ZZ The vi editor is built on an earlier Unix text editor called ex. ex commands can be used within vi. ex commands begin with a : (colon) and end with a <Return>. The command is displayed on the status line as you type. Some ex commands are useful when saving and closing files. To save the edits you have made, but leave vi running and your file open: 1. Press <Esc>. 2. Type :w 3. Press <Return>. To quit vi, and discard any changes your have made since last saving: 1. Press <Esc>. 2. Type :q! 3. Press <Return>. ESSENTIAL UNIX COMMANDS These are the commands that you really need to know in order to get started with UNIX. Practicing of Basic UNIX Commands. Exercise 1 : 1. CAT command General Syntax cat [OPTION] [FILE]... Create a File with Cat Command We will create a file called test2 file with below command. # cat >test2 Awaits input from user, type desired text and press CTRL+D (hold down Ctrl Key and type ‘d‘) to exit. The text will be written in test2 file. Displaying Contents of File In the below example, it will show contains of /etc/passwd file. # cat /etc/passwd root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/sbin/nologin narad:x:500:500::/home/narad:/bin/bash Use Cat Command with More & Less Options If file having large number of contains that won’t fit in output terminal and screen scrolls up very fast, we can use parameters more and less with cat command as show above. # cat song.txt | more # cat song.txt | less Display Line Numbers in File With -n option you could see the line numbers of a file song.txt in the output terminal. # cat -n song.txt 1 "Heal The World" 2 There's A Place In 3 Your Heart 4 And I Know That It Is Love 5 And This Place Could 6 Be Much 7 Brighter Than Tomorrow 8 And If You Really Try 9 You'll Find There's No Need Use Standard Output with Redirection Operator We can redirect standard output of a file into a new file else existing file with ‘>‘ (greater than) symbol. Careful, existing contains of test1 will be overwritten by contains of test file. # cat test > test1 Appending Standard Output with Redirection Operator Appends in existing file with ‘>>‘ (double greater than) symbol. Here, contains of test file will be appended at the end of test1 file. # cat test >> test1 Redirecting Multiple File contents in a Single File This will create a file called test3 and all output will be redirected in a newly created file. # cat test test1 test2 > test3 Sorting Contents of Multiple Files in a Single File This will create a file test4 and output of cat command is piped to sort and result will be redirected in a newly created file. # cat test test1 test2 test3 | sort > test4 Sort Command This command is used for sorting the lines of text files Synatx sort [OPTION]... [FILE]... Options: Mandatory arguments to long options are mandatory for short options too. -d, --dictionary-order consider only blanks and alphanumeric characters -f, --ignore-case fold lower case to upper case characters -n, --numeric-sort compare according to string numerical value -r, --reverse reverse the result of comparisons -c, --check check whether input is sorted; do not sort -k, --key=POS1 Sorts the text based on the given key position -o, --output=FILE write result to FILE instead of standard output Example Sorting ls command output $ ls -al | sort -n -k5 This results in the following ls command sorted output, which as you can see, is a directory listing, sorted by filesize (the 5th column): -rw-r--r-- 1 al al 0 Aug 17 2007 CreateAPodcast.idx total 992 -rw-r--r-- 1 al al 240 Aug 17 2007 files drwxr-xr-x 11 al al 374 Jul 5 17:50 .. -rw-r--r-- 1 al al 535 Aug 18 2007 CreateAPodcast.out drwxr-xr-x 18 al al 612 Aug 18 2007 images drwxr-xr-x 20 al al 680 Aug 27 2007 . 2. Cut and Paste Commands cut command selects a list of columns or fields from one or more files. Options -c - specify a number for columns to cut -f - specify a number for fields to cut. Example If a file named testfile contains this is firstline that is secondline what is thirdline Examples: cut -f1 testfile will print this to standard output (screen) this that what paste command merge the lines of one or more files into vertical columns separated by a tab. Example if a file named testfile contains this is firstline and a file named testfile2 contains this is testfile2 then running this command paste testfile testfile2 > outputfile will put this into outputfile this is firstline this is testfile2 It contains contents of both files in columns. Example of combining both cut and paste commands on a table cut -f 1 mytable.txt > col1.txt cut -f 2 mytable.txt > col2.txt cut -f 3 mytable.txt > col3.txt cut -f 4- > colrest.txt Now, use the paste command to glue the parts together in the proper order. paste col1.txt col3.txt col2.txt colrest.txt > mytable.txt 3. SED command SED command in UNIX is stands for stream editor and it can perform lot's of function on file like, searching, find and replace, insertion or deletion. Sed is a Stream Editor used for modifying the files in unix (or linux). Whenever you want to make changes to the file automatically, sed comes in handy to do this. Syntax: Following is the general syntax for sed sed [options] /pattern/action filename Here, pattern is a regular expression, and action is one of the commands given in the following table. If pattern is omitted, action is performed for every line as we have seen above. The slash characters ( /) that surround the pattern are required because they are used as delimiters.
Regular Expressions in SED command
A regular expression is a pattern that is matched against a subject string from left to right. Most characters are ordinary: they stand for themselves in a pattern, and match the corresponding characters in the subject.
The Substitution Command:
The substitution command, denoted by s, will substitute any string that you specify with any other string that you specify. The following command substitutes the first occurrence on a line of the string root with the string amrood. $ cat /etc/passwd | sed 's/root/amrood/' amrood:x:0:0:root user:/root:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh It is very important to note that sed substitutes only the first occurrence on a line. If the string root occurs more than once on a line only the first match will be replaced. To tell sed to do a global substitution, add the letter g to the end of the command as follows: $ cat /etc/passwd | sed 's/root/amrood/g' amrood:x:0:0:amrood user:/amrood:/bin/sh daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh Examples: Write the commands to the following a)Login into the system admin@svecwcsed211:~$ [email protected] Output: ituser23.0.20.240’s password:ituser23 last login :Thu Dec 8 14:24:31 2016 from 10.0.21.143 b)use the command to create a file comtaining the following data.call it mytable uses tabs to separate the fields. 1425 Ravi 15.65 4320 Ramu 26.27 6830 Sita 36.15 1450 Raju 21.86 $cat >mytable Output: 1425 Ravi 15.65 4320 Ramu 26.27 6830 Sita 36.15 1450 Raju 21.86 c)use the cat command to display the file ,my table $cat mytable Output: 1425 Ravi 15.65 4320 Ramu 26.27 6830 Sita 36.15 1450 Raju 21.86 d)use the vi command to correct any errors in the file,my table $ vi mytable Output: 1425 Ravi 15.65 4320 Ramu 26.27 6830 Sita 36.15 1450 Raju 21.86 1340 Raji 18.04 1240 Jaya 16.04 e)use the sort command to sort the file my table according to the first field. Call the sorted file my table $ sort mytable Output: 1240 Jaya 16.04 1340 Raji 18.04 1425 Ravi 15.65 1450 Raju 21.86 4320 Ramu 26.27 6830 Sita 36.15 a)Write a sed command that delets the first character in each line in a file. $ sed ‘s/^.//’ f1 Output: xxxxxxx computer echnology b)Write a sed command that deletes the character before the last character in each line in a file. $ sed ‘s/.$//’ f1 Output: computer technolog c)Write a sed command that swaps the first and second words in each line in a file. $ sed ‘s/ \ ([a-z]*\) ([a-z]*\)/ \2, \1/’ f1 Output: XXXX, computer, technology Section A 88888 UNIX operating system calls Exercise 2 : Write programs using the following UNIX operating system calls Fork, exec, getpid, exit, wait, close, stat, opendir and readdir. Fork System Call AIM: To write a program to create a child process using the system calls –fork. ALGORITHM: Step 1: Include the necessary header files. Step 2: Get the ID of the current main processor using the function getpid(). Step 3: Create a child using fork system call Set a=fork() Step 4: The fork() return 0 to a, if a child is created or any other value is returned. Step 5: If a is equal to 0, then print the child ID using getpid(). Step 6: Else if a is not equal to 0, then print the child ID and the parent ID using getpid() . Step 7: Else print error message. OUTPUT: [meera@localhost meera]$ cc -o fork.out fork.c [meera@localhost meera]$ ./fork.out Parent is 10968 HELLO FROM CHILD PROCESS CHILD ID is 10968 Parent is 10967 HELLO FROM PARENT PROCESS 10967 HELLO FROM CHILD PROCESS 10968 EXEC System Call AIM: To write a program to display time and date using exec system call. ALGORITHM: Step 1: Include the necessary header file. Step 2: Using fork () system call, create child process. Step 3: Display the id of the child process and parent process using getpid() and getppid(). Step 4: Using exec system call, display the time and date execl(“/bin/date”, “date”, 0) The first field is directory, 2nd field is syntax, 3rd field is set to null. Step 5: The exec system call will terminate the child process. OUTPUT: [meera@localhost meera]$ cc -o exec.out exec.c [meera@localhost meera]$ ./exec.out Child Id is 10983 Parent Id is 10982 Tue Jan 27 11:17:10 IST 2009 End of file STAT System Call AIM: To write a program to implement STAT system call. ALGORITHM: Step 1: Include the necessary header file. Step 2: Check the status of the given file. Step 3: Store the status as integer value in the variable flag. Step 4: If the argc is not equal to 2 then print filename is not given. Step 5: Else if flag is equal to -1 then print file does not exist. Step 6: Else print the file link, devices, inodes, protection, size, ownership, block size and time. OUTPUT: [meera@localhost meera]$ cc -o stat.out stat.c [meera@localhost meera]$ ./stat.out exec.c File Exists and Filename is givenThe information about the file exec.c exec.c has 1 link exec.c has 770 devices exec.c has 3908662 inodes exec.c has 33204 protection exec.c has 0 inode devices exec.c has 248 size exec.c has 501 owner exec.c has 4096 block size exec.c has 1233035222 time exec.c has 1233035220 time Wait System Call AIM: To write a program using wait system call. ALGORITHM: Step 1: Create child process using fork system call. Step 2: Display the child id and status of the child process. Step 3: Using exec() system call display the time and date. Step 4: Return the child ID as the waiting ID using wait() system call. cid=wait(&status) Step 5: Display waiting ID and status OUTPUT: [meera@localhost meera]$ cc -o wait.out wait.c [meera@localhost meera]$ ./wait.out Parent Id is 11004 Status Id is 134513794 Tue Jan 27 11:27:27 IST 2009 Id is 11004 Status is 0 UNIX OPERATING SYSTEMS (OPENDIR, READDIR, CLOSEDIR) #include <stdio.h> #include <stdlib.h> #include <dirent.h> int main() { DIR *dir; struct dirent *entry; // Open the current directory dir = opendir("."); if (dir == NULL) { perror("opendir"); exit(EXIT_FAILURE); } // Read directory entries printf("Contents of current directory:\n"); while ((entry = readdir(dir)) != NULL) { printf("%s\n", entry->d_name); } // Close the directory if (closedir(dir) == -1) { perror("closedir"); exit(EXIT_FAILURE); } return 0; } Output Contents of current directory: . main main.c .. stdin [Execution complete with exit code 0] UNIX commands Exercise 3 Simulate UNIX commands like cp, ls, grep, etc., 1. Simulation of ls command ALGORITHM : Step 1: Include necessary header files for manipulating directory. Step 2: Declare and initialize required objects. Step 3: Read the directory name form the user. Step 4: Open the directory using opendir() system call and report error if the directory is not available. Step 5: Read the entry available in the directory. Step 6: Display the directory entry ie., name of the file or sub directory. Step 7: Repeat the step 6 and 7 until all the entries were read. /* 1. Simulation of ls command */ #include #include main() { char dirname[10]; DIR *p; struct dirent *d; printf("Enter directory name "); scanf("%s",dirname); p=opendir(dirname); if(p==NULL) { perror("Cannot find dir."); exit(-1); } while(d=readdir(p)) printf("%s\n",d->d_name); } SAMPLE OUTPUT: enter directory name iii . .. f2 f1 2. Simulation of grep command. ALGORITHM: Step 1: Include necessary header files. Step 2: Make necessary declarations. Step 3: Read the file name from the user and open the file in the read only mode. Step 4: Read the pattern from the user. Step 5: Read a line of string from the file and search the pattern in that line. Step 6: If pattern is available, print the line. Step 7: Repeat the step 4 to 6 till the end of the file. /* 2. Simulation of grep command */ #include #include main() { char fn[10],pat[10],temp[200]; FILE *fp; printf("\n Enter file name : "); scanf("%s",fn); printf("Enter the pattern to be searched : "); scanf("%s",pat); fp=fopen(fn,"r"); while(!feof(fp)) { fgets(temp,1000,fp); if(strstr(temp,pat)) printf("%s",temp); } fclose(fp); } SAMPLE OUTPUT: enter file name: file4 enter the pattern to be searched: roll roll no percentage grade CPU Scheduling Algorithms Exercise 4 : Simulate the following CPU Scheduling Algorithms a. FCFS b. SJF c. Priority d. Round Robin CPU scheduling deals with the problem of deciding which of the processes in the ready queue is to be allocated the CPU. There are many different CPU scheduling algorithms First Come First Serve(FCFS) Shortest Job First(SJF) Priority Scheduling Round Robin a) First Come First Served (FCFS) First-come, First served is simplest scheduling algorithm Ready queue is a FIFO queue Longest waiting process at the front of queue New ready processes join the rear Non-preemptive: executes until voluntarily gives up CPU finished or waits for some event Problem: CPU bound process may require a long CPU burst Other processes, with very short CPU bursts, wait in queue Reduces CPU and I/O device utilization Program: // C program for implementation of FCFS // scheduling #include<stdio.h> // Function to find the waiting time for all // processes void findWaitingTime(int processes[], int n, int bt[], int wt[]) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i<n ;i++ ) wt[i] = bt[i-1] + wt[i-1] ; } // Function to calculate turn around time void findTurnAroundTime( int processes[], int n, int bt[], int wt[], int tat[]) { // calculating turnaround time by adding // bt[i] + wt[i] for (int i = 0; i<n ;i++) tat[i] = bt[i] + wt[i]; } //Function to calculate average time void findavgTime( int processes[], int n, int bt[]) { int wt[n], tat[n], total_wt = 0, total_tat = 0; //Function to find waiting time of all processes findWaitingTime(processes, n, bt, wt); //Function to find turn around time for all processes findTurnAroundTime(processes, n, bt, wt, tat); //Display processes along with all details printf("Processes Burst time Waiting time Turn around time\n"); // Calculate total waiting time and total turn // around time for (int i=0; i<n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; printf(" %d ",(i+1)); printf(" %d ", bt[i] ); printf(" %d",wt[i] ); printf(" %d\n",tat[i] ); } int s=(float)total_wt / (float)n; int t=(float)total_tat / (float)n; printf("Average waiting time = %d",s); printf("\n"); printf("Average turn around time = %d ",t); } // Driver code int main() { //process id's int processes[] = { 1, 2, 3}; int n = sizeof processes / sizeofprocesses[0]; //Burst time of all processes int burst_time[] = {10, 5, 8}; findavgTime(processes, n, burst_time); return 0; } Output: Processes Bursttime Waitingtime Turnaround time 1 10 0 10 2 5 10 15 3 8 15 23 Average waiting time = 8.33333 Average turnaround time = 16 b) Shortest Job First(SJF) Shortest job first (SJF) or shortest job next, is a scheduling policy that selects the waiting process with the smallest execution time to execute next. SJN is a non-pre-emptive algorithm. Shortest Job first has the advantage of having a minimum average waiting time among all scheduling algorithms. It is a Greedy Algorithm. It may cause starvation if shorter processes keep coming. This problem can be solved using the concept of aging. It is practically infeasible as Operating System may not know burst time and therefore may not sort them. While it is not possible to predict execution time, several methods can be used to estimate the execution time for a job, such as a weighted average of previous execution times. SJF can be used in specialized environments where accurate estimates of running time are available. Program: #include<stdio.h> #include<conio.h> #include<string.h> void main() { int et[20],at[10],n,i,j,temp,st[10],ft[10],wt[10],ta[10]; int totwt=0,totta=0; float awt,ata; char pn[10][10],t[10]; //clrscr(); printf("Enter the number of process:"); scanf("%d",&n); for(i=0; i<n; i++) { printf("Enter process name, arrival time& execution time:"); //flushall(); scanf("%s%d%d",pn[i],&at[i],&et[i]); } for(i=0; i<n; i++) for(j=0; j<n; j++) { if(et[i]<et[j]) { temp=at[i]; at[i]=at[j]; at[j]=temp; temp=et[i]; et[i]=et[j]; et[j]=temp; strcpy(t,pn[i]); strcpy(pn[i],pn[j]); strcpy(pn[j],t); } } for(i=0; i<n; i++) { if(i==0) st[i]=at[i]; else st[i]=ft[i-1]; wt[i]=st[i]-at[i]; ft[i]=st[i]+et[i]; ta[i]=ft[i]-at[i]; totwt+=wt[i]; totta+=ta[i]; } awt=(float)totwt/n; ata=(float)totta/n; printf("\nPname\tarrivaltime\texecutiontime\twaitingtime\ttatime"); for(i=0; i<n; i++) printf("\n%s\t%5d\t\t%5d\t\t%5d\t\t%5d",pn[i],at[i],et[i],wt[i],ta[i]); printf("\nAverage waiting time is:%f",awt); printf("\nAverageturnaroundtime is:%f",ata); getch(); } Output: Enter the number of process:3 Enter process name, arrival time& execution time:2 5 7 Enter process name, arrival time& execution time:3 6 14 Enter process name, arrival time& execution time:4 7 12 Pnamearrivaltimeexecutiontimewaitingtimetatime 25707 4 7 12 5 17 3 6 14 18 32 Average waiting time is:7.666667 Average turnaround time is:18.666666 c) Priority Scheduling: In priority scheduling algorithm each process has a priority associated with it and as each process hits the queue, it is stored in based on its priority so that process with higher priority are dealt with first. It should be noted that equal priority processes are scheduled in FCFS order. To prevent high priority processes from running indefinitely the scheduler may decrease the priority of the currently running process at each clock tick (i.e., at each clock interrupt). If this action causes its priority to drop below that of the next highest process, a process switch occurs. Alternatively, each process may be assigned a maximum time quantum that it is allowed to run. When this quantum is used up, the next highest priority process is given a chance to run. Program: #include<stdio.h> int main() { int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat; printf("Enter Total Number of Process:"); scanf("%d",&n); printf("\nEnter Burst Time and Priority\n"); for(i=0;i<n;i++) { printf("\nP[%d]\n",i+1); printf("Burst Time:"); scanf("%d",&bt[i]); printf("Priority:"); scanf("%d",&pr[i]); p[i]=i+1; //contains process number } //sorting burst time, priority and process number in ascending order using selection sort for(i=0;i<n;i++) { pos=i; for(j=i+1;j<n;j++) { if(pr[j]<pr[pos]) pos=j; } temp=pr[i]; pr[i]=pr[pos]; pr[pos]=temp; temp=bt[i]; bt[i]=bt[pos]; bt[pos]=temp; temp=p[i]; p[i]=p[pos]; p[pos]=temp; } wt[0]=0; //waiting time for first process is zero //calculate waiting time for(i=1;i<n;i++) { wt[i]=0; for(j=0;j<i;j++) wt[i]+=bt[j]; total+=wt[i]; } avg_wt=total/n; //average waiting time total=0; printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time"); for(i=0;i<n;i++) { tat[i]=bt[i]+wt[i]; //calculate turnaround time total+=tat[i]; printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]); } avg_tat=total/n; //average turnaround time printf("\n\nAverage Waiting Time=%d",avg_wt); printf("\nAverage Turnaround Time=%d\n",avg_tat); return 0; } Output: Enter Total Number of Process: 4 Enter Burst Time and Priority P[1] Burst Time:6 Priority:3 P[2] Burst Time:2 Priority:2 P[3] Burst Time:14 Priority:1 P[4] Burst Time:6 Priority:4
Average Waiting Time =13
Average Turnaround Time=20 d) Round Robin Scheduling. Step 1: Start the process Step 2: Accept the number of processes in the ready Queue and time quantum (or) time slice Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time Step 4: Calculate the no. of time slices for each process where No. of time slice for process(n) = burst time process(n)/time slice Step 5: If the burst time is less than the time slice then the no. of time slices =1. Step 6: Consider the ready queue is a circular Q, calculate (a) Waiting time for process(n) = waiting time of process(n-1)+ burst time of process(n-1 ) + the time difference in getting the CPU from process(n-1) (b) Turn around time for process(n) = waiting time of process(n) + burst time of process(n)+ the time difference in getting CPU from process(n). Step 7: Calculate (a) Average waiting time = Total waiting Time / Number of process (b) Average Turnaround time = Total Turnaround Time / Number of process Step 8: Stop the process /* ROUND ROBIN SCHEDULING ALGORITHM */ #include<stdio.h> #include<conio.h> void main(){ int ts,pid[10],need[10],wt[10],tat[10],i,j,n,n1; int bt[10],flag[10],ttat=0,twt=0; float awt,atat; printf("\t\t ROUND ROBIN SCHEDULING \n"); printf("Enter the number of Processors \n"); scanf("%d",&n); n1=n; printf("\n Enter the Timeslice \n"); scanf("%d",&ts); for(i=1;i<=n;i++) { printf("\n Enter the process ID %d",i); scanf("%d",&pid[i]); printf("\n Enter the Burst Time for the process"); scanf("%d",&bt[i]); need[i]=bt[i]; } for(i=1;i<=n;i++) { flag[i]=1; wt[i]=0; } while(n!=0) { for(i=1;i<=n;i++) { if(need[i]>=ts) { for(j=1;j<=n;j++) { if((i!=j)&&(flag[i]==1)&&(need[j]!=0)) wt[j]+=ts; } need[i]-=ts; if(need[i]==0) { flag[i]=0; n--; } } else { for(j=1;j<=n;j++) { if((i!=j)&&(flag[i]==1)&&(need[j]!=0)) wt[j]+=need[i]; } need[i]=0; n--; flag[i]=0; } } } for(i=1;i<=n1;i++){ tat[i]=wt[i]+bt[i]; twt=twt+wt[i]; ttat=ttat+tat[i];} awt=(float)twt/n1; atat=(float)ttat/n1; printf("\n\n ROUND ROBIN SCHEDULING ALGORITHM \n\n"); printf("\n\n Process \t Process ID \t BurstTime \t Waiting Time \t TurnaroundTime \n "); for(i=1;i<=n1;i++){ printf("\n %5d \t %5d \t\t %5d \t\t %5d \t\t %5d \n", i,pid[i],bt[i],wt[i],tat[i]); } printf("\n The average Waiting Time=4.2f",awt); printf("\n The average Turn around Time=4.2f",atat); } OUTPUT: Enter the number of Processors 4 Enter the Timeslice 5 Enter the process ID 1 5 Enter the Burst Time for the process 10 Enter the process ID 2 6 Enter the Burst Time for the process 15 Enter the process ID 3 7 Enter the Burst Time for the process 20 Enter the process ID 4 8 Enter the Burst Time for the process 25
The average Waiting Time=4.2f
The average Turn around Time=4.2f page replacement algorithms Exercise 9 Simulate the following page replacement algorithms a) FIFO b) LRU c) LFU a) FIFO: In operating systems that use paging for memory management, page replacement algorithm are needed to decide which page needed to be replaced when new page comes in. Whenever a new page is referred and not present in memory, page fault occurs and Operating System replaces one of the existing pages with newly needed page. Different page replacement algorithms suggest different ways to decide which page to replace. The target for all algorithms is to reduce number of page faults. This is the simplest page replacement algorithm. In this algorithm, operating system keeps track of all pages in the memory in a queue, oldest page is in the front of the queue. When a page needs to be replaced page in the front of the queue is selected for removal Step 1: Create a queue to hold all pages in memory Step 2: When the page is required replace the page at the head of the queue Step 3: Now the new page is inserted at the tail of the queue /* FIFO Page Replacement Algorithm */ #include<stdio.h> #include<conio.h> int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1; void main() { printf("\n \t\t\t FIFI PAGE REPLACEMENT ALGORITHM"); printf("\n Enter no.of frames...."); scanf("%d",&nof); printf("Enter number of reference string..\n"); scanf("%d",&nor); printf("\n Enter the reference string.."); for(i=0;i<nor;i++) scanf("%d",&ref[i]); printf("\nThe given reference string:"); for(i=0;i<nor;i++) printf("%4d",ref[i]); for(i=1;i<=nof;i++) frm[i]=-1; printf("\n"); for(i=0;i<nor;i++) { flag=0; printf("\n\t Reference np%d->\t",ref[i]); for(j=0;j<nof;j++) { if(frm[j]==ref[i]) { flag=1; break; }} if(flag==0) { pf++; victim++; victim=victim%nof; frm[victim]=ref[i]; for(j=0;j<nof;j++) printf("%4d",frm[j]); } } printf("\n\n\t\t No.of pages faults...%d",pf); } OUTPUT: FIFO PAGE REPLACEMENT ALGORITHM Enter no.of frames....4 Enter number of reference string..6 Enter the reference string.. 564123 The given reference string: ...................................... 5 6 4 1 2 3 Reference np5-> 5 -1 -1 -1 Reference np6-> 5 6 -1 -1 Reference np4-> 5 6 4 -1 Reference np1-> 5 6 4 1 Reference np2-> 2 6 4 1 Reference np3-> 2 3 4 1 No.of pages faults...6 b) LRU PAGE REPLACEMENT ALGORITHM Least Recently Used (LRU) page replacement algorithm works on the concept that the pages that are heavily used in previous instructions are likely to be used heavily in next instructions. And the page that are used very less are likely to be used less in future. Whenever a page fault occurs, the page that is least recently used is removed from the memory frames. Page fault occurs when a referenced page in not found in the memory frames. AIM: To implement page replacement algorithm LRU (Least Recently Used) LRU (Lease Recently Used) Here we select the page that has not been used for the longest period of time. ALGORITHM: Step 1: Create a queue to hold all pages in memory Step 2: When the page is required replace the page at the head of the queue Step 3: Now the new page is inserted at the tail of the queue Step 4: Create a stack Step 5: When the page fault occurs replace page present at the bottom of the stack /* LRU Page Replacement Algorithm */ #include<stdio.h> #include<conio.h> int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1; int recent[10],lrucal[50],count=0; int lruvictim(); void main() { printf("\n\t\t\t LRU PAGE REPLACEMENT ALGORITHM"); printf("\n Enter no.of Frames...."); scanf("%d",&nof); printf(" Enter no.of reference string.."); scanf("%d",&nor); printf("\n Enter reference string.."); for(i=0;i<nor;i++) scanf("%d",&ref[i]); printf("\n\n\t\t LRU PAGE REPLACEMENT ALGORITHM "); printf("\n\t The given reference string:"); printf("\n……………………………….."); for(i=0;i<nor;i++) printf("%4d",ref[i]); for(i=1;i<=nof;i++) { frm[i]=-1; lrucal[i]=0; } for(i=0;i<10;i++) recent[i]=0; printf("\n"); for(i=0;i<nor;i++) { flag=0; printf("\n\t Reference NO %d->\t",ref[i]); for(j=0;j<nof;j++) { if(frm[j]==ref[i]) { flag=1; break; } } if(flag==0) { count++; if(count<=nof) victim++; else victim=lruvictim(); pf++; frm[victim]=ref[i]; for(j=0;j<nof;j++) printf("%4d",frm[j]); } recent[ref[i]]=i; } printf("\n\n\t No.of page faults...%d",pf); } int lruvictim() { int i,j,temp1,temp2; for(i=0;i<nof;i++) { temp1=frm[i]; lrucal[i]=recent[temp1]; } temp2=lrucal[0]; for(j=1;j<nof;j++) { if(temp2>lrucal[j]) temp2=lrucal[j]; } for(i=0;i<nof;i++) if(ref[temp2]==frm[i]) return i; return 0; } OUTPUT: LRU PAGE REPLACEMENT ALGORITHM Enter no.of Frames....3 Enter no.of reference string..6 Enter reference string.. 654231
C) OPTIMAL (LFU) PAGE REPLACEMENT ALGORITHM
AIM: To implement page replacement algorithms Optimal (The page which is not used for longest time) ALGORITHM: Optimal algorithm Here we select the page that will not be used for the longest period of time. OPTIMAL: Step 1: Create a array Step 2: When the page fault occurs replace page that will not be used for the longest period of time /* Optimal (LFU) page replacement algorithm*/ #include<stdio.h> #include<conio.h> int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1; int recent[10],optcal[50],count=0; int optvictim(); void main() { printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHN"); printf("\n................................."); printf("\nEnter the no.of frames"); scanf("%d",&nof); printf("Enter the no.of reference string"); scanf("%d",&nor); printf("Enter the reference string"); for(i=0;i<nor;i++) scanf("%d",&ref[i]); clrscr(); printf("\n OPTIMAL PAGE REPLACEMENT ALGORITHM"); printf("\n................................"); printf("\nThe given string"); printf("\n....................\n"); for(i=0;i<nor;i++) printf("%4d",ref[i]); for(i=0;i<nof;i++) { frm[i]=-1; optcal[i]=0; } for(i=0;i<10;i++) recent[i]=0; printf("\n"); for(i=0;i<nor;i++) { flag=0; printf("\n\tref no %d ->\t",ref[i]); for(j=0;j<nof;j++) { if(frm[j]==ref[i]) { flag=1; break; } } if(flag==0) { count++; if(count<=nof) victim++; else victim=optvictim(i); pf++; frm[victim]=ref[i]; for(j=0;j<nof;j++) printf("%4d",frm[j]); } } printf("\n Number of page faults: %d",pf); getch(); } int optvictim(int index) { int i,j,temp,notfound; for(i=0;i<nof;i++) { notfound=1; for(j=index;j<nor;j++) if(frm[i]==ref[j]) { notfound=0; optcal[i]=j; break; } if(notfound==1) return i; } temp=optcal[0]; for(i=1;i<nof;i++) if(temp<optcal[i]) temp=optcal[i]; for(i=0;i<nof;i++) if(frm[temp]==frm[i]) return i; return 0; } OUTPUT: OPTIMAL PAGE REPLACEMENT ALGORITHM Enter no.of Frames....3 Enter no.of reference string..6 Enter reference string.. 654231 OPTIMAL PAGE REPLACEMENT ALGORITHM The given reference string: …………………. 6 5 4 2 3 1 memory management. PROGRAM LOGIC Step 1: Read all the necessary input from the keyboard. Step 2: Pages - Logical memory is broken into fixed - sized blocks. Step 3: Frames – Physical memory is broken into fixed – sized blocks. Step 4: Calculate the physical address using the following Physical address = ( Frame number * Frame size ) + offset Step 5: Display the physical address. Step 6: Stop the process. PROGRAM #include <stdio.h> #include <conio.h> struct pstruct { int fno; int pbit; }ptable[10]; int pmsize,lmsize,psize,frame,page,ftable[20],frameno; void info() { printf("\n\nMEMORY MANAGEMENT USING PAGING\n\n"); printf("\n\nEnter the Size of Physical memory: "); scanf("%d",&pmsize); printf("\n\nEnter the size of Logical memory: "); scanf("%d",&lmsize); printf("\n\nEnter the partition size: "); scanf("%d",&psize); frame = (int) pmsize/psize; page = (int) lmsize/psize; printf("\nThe physical memory is divided into %d no.of frames\n",frame); printf("\nThe Logical memory is divided into %d no.of pages",page); } void assign() { int i; for (i=0;i<page;i++) { ptable[i].fno = -1; ptable[i].pbit= -1; } for(i=0; i<frame;i++) ftable[i] = 32555; for (i=0;i<page;i++) { printf("\n\nEnter the Frame number where page %d must be placed: ",i); scanf("%d",&frameno); ftable[frameno] = i; if(ptable[i].pbit == -1) { ptable[i].fno = frameno; ptable[i].pbit = 1; } } getch(); printf("\n\nPAGE TABLE\n\n"); printf("PageAddress FrameNo. PresenceBit\n\ n"); for (i=0;i<page;i+ +) printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit); printf("\n\n\n\tFRAME TABLE\n\n"); printf("FrameAddress PageNo\n\n"); for(i=0;i<frame;i++) printf("%d\t\t%d\n",i,ftable[i]); } void cphyaddr() { int laddr,paddr,disp,phyaddr,baddr; getch(); printf("\n\n\n\tProcess to create the Physical Address\n\n"); printf("\nEnter the Base Address: "); scanf("%d",&baddr); printf("\nEnter theLogical Address: "); scanf("%d",&laddr); paddr = laddr / psize; disp = laddr % psize; if(ptable[paddr].pbit == 1 ) phyaddr = baddr + (ptable[paddr].fno*psize) + disp; printf("\nThe Physical Address where the instruction present: %d",phyaddr); } void main() { clrscr(); info(); assign(); cphyaddr(); getch(); } INPUT AND OUTPUT MEMORY MANAGEMENT USING PAGING Enter the Size of Physical memory: 16 Enter the size of Logical memory: 8 Enter the partition size: 2 The physical memory is divided into 8 no.of frames The Logical memory is divided into 4 no.of pages Enter the Frame number where page 0 must be placed: 5 Enter the Frame number where page 1 must be placed: 6 Enter the Frame number where page 2 must be placed: 7 Enter the Frame number where page 3 must be placed: 2 PAGE TABLE PageA FrameN Presen ddress o. ceBit 0 5 1 1 6 1 2 7 1 3 2 1 FRAME Pag TABLE eNo FrameAd dress 0 32555 1 32555 2 3 3 32555 4 32555 5 0 6 1 7 2 Process to create the Physical Address Enter the Base Address: 1000 Enter theLogical Address: 3 The Physical Address where the instruction present: 1013 Bankers Algorithm for Deadlock avoidance Exercise 11 : Simulate Bankers Algorithm for Deadlock Avoidance. The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests for safety by simulating the allocation for predetermined maximum possible amounts of all resources, then makes an “sstate” check to test for possible activities, before deciding whether allocation should be allowed to continue. Program: // Banker's Algorithm #include <stdio.h> int main() { // P0, P1, P2, P3, P4 are the Process names here int n, m, i, j, k; n = 5; // Number of processes m = 3; // Number of resources int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix { 2, 0, 0 }, // P1 { 3, 0, 2 }, // P2 { 2, 1, 1 }, // P3 { 0, 0, 2 } }; // P4 int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix { 3, 2, 2 }, // P1 { 9, 0, 2 }, // P2 { 2, 2, 2 }, // P3 { 4, 3, 3 } }; // P4 int avail[3] = { 3, 3, 2 }; // Available Resources int f[n], ans[n], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } int need[n][m]; for (i = 0; i< n; i++) { for (j = 0; j < m; j++) need[i][j] = max[i][j] - alloc[i][j]; } int y = 0; for (k = 0; k < 5; k++) { for (i = 0; i< n; i++) { if (f[i] == 0) { int flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]){ flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) avail[y] += alloc[i][y]; f[i] = 1; } } } } printf("Following is the SAFE Sequence\n"); for (i = 0; i< n - 1; i++) printf(" P%d ->", ans[i]); printf(" P%d", ans[n - 1]); return (0); } Output: Following is the SAFE Sequence P1 -> P3 -> P4 -> P0 -> P2 File Allocation Strategies Exercise 12: Simulate the following File Allocation Strategies a. Sequential b. Indexed c. linked a) Sequential File allocation: Files are normally stored on the disks. So, the main problem is how to allocate space to those files. So that disk space is utilized effectively and files can be accessed quickly. Three major strategies of allocating disc space are in wide use. Sequential, indexed and linked. In this allocation strategy, each file occupies a set of contiguously blocks on the disk. This strategy is best suited. For sequential files, the file allocation table consists of a single entry for each file. It shows the filenames, starting block of the file and size of the file. The main problem with this strategy is, it is difficult to find the contiguous free blocks in the disk and some free blocks could happen between two files. Program: #include <stdio.h> #include<conio.h> void main() { int f[50], i, st, len, j, c, k, count = 0; clrscr(); for(i=0;i<50;i++) f[i]=0; printf("Files Allocated are : \n"); x: count=0; printf(“Enter starting block and length of files: ”); scanf("%d%d", &st,&len); for(k=st;k<(st+len);k++) if(f[k]==0) count++; if(len==count) { for(j=st;j<(st+len);j++) if(f[j]==0) { f[j]=1; printf("%d\t%d\n",j,f[j]); } if(j!=(st+len-1)) printf(” The file is allocated to disk\n"); } else printf(” The file is not allocated \n"); printf("Do you want to enter more file(Yes - 1/No - 0)"); scanf("%d", &c); if(c==1) goto x; else exit(); getch(); } Output: Files Allocated are : Enter starting block and length of files: 14 3 14 1 15 1 16 1 The file is allocated to disk Do you want to enter more file(Yes - 1/No - 0)1 Enter starting block and length of files: 14 1 The file is not allocated Do you want to enter more file(Yes - 1/No - 0)1 Enter starting block and length of files: 14 4 The file is not allocated Do you want to enter more file(Yes - 1/No - 0)0 b) Indexed File Allocation: In this scheme, a special block known as the Index block contains the pointers to all the blocks occupied by a file. Each file has its own index block. The ith entry in the index block contains the disk address of the ith file block. Advantages: This supports direct access to the blocks occupied by the file and therefore provides fast access to the file blocks. It overcomes the problem of external fragmentation. Disadvantages: The pointer overhead for indexed allocation is greater than linked allocation. For very small files, say files that expand only 2-3 blocks, the indexed allocation would keep one entire block (index block) for the pointers which is inefficient in terms of memory utilization. However, in linked allocation we lose the space of only 1 pointer per block. Program: #include<stdio.h> #include<conio.h> #include<stdlib.h> void main() { int f[50], index[50],i, n, st, len, j, c, k, ind,count=0; clrscr(); for(i=0;i<50;i++) f[i]=0; x:printf("Enter the index block: "); scanf("%d",&ind); if(f[ind]!=1) { printf("Enter no of blocks needed and no of files for the index %d on the disk : \n", ind); scanf("%d",&n); } else { printf("%d index is already allocated \n",ind); goto x; } y: count=0; for(i=0;i<n;i++) { scanf("%d", &index[i]); if(f[index[i]]==0) count++; } if(count==n) { for(j=0;j<n;j++) f[index[j]]=1; printf("Allocated\n"); printf("File Indexed\n"); for(k=0;k<n;k++) printf("%d-------->%d : %d\n",ind,index[k],f[index[k]]); } else { printf("File in the index is already allocated \n"); printf("Enter another file indexed"); goto y; } printf("Do you want to enter more file(Yes - 1/No - 0)"); scanf("%d", &c); if(c==1) goto x; else exit(0); getch(); } Output: Enter the index block: 5 Enter no of blocks needed and no of files for the index 5 on the disk: 4 1234 Allocated File Indexed 5-------->1 : 1 5-------->2 : 1 5-------->3 : 1 5-------->4 : 1 Do you want to enter more file(Yes - 1/No - 0)1 Enter the index block: 4 4 index is already allocated Enter the index block: 6 Enter no of blocks needed and no of files for the index 6 on the disk : 2 78 A5llocated File Indexed 6-------->7 : 1 6-------->8 : 1 Do you want to enter more file(Yes - 1/No - 0)0 c) Linked Program to perform Linked file allocation mechanism. PROGRAM LOGIC Step 1: Create a queue to hold all pages in memory Step 2: When the page is required replace the page at the head of the queue Step 3: Now the new page is inserted at the tail of the queue Step 4: Create a stack Step 5: When the page fault occurs replace page present at the bottom of the stack Step 6: Stop the allocation. PROGRAM #include<conio.h> #include<stdio .h> void main() { int i,m,n,j,count; int a[100],s[10],e[10],in[10],inn[10][25]; clrscr(); printf("enter the total memory"); scanf("%d",&m); for(i=0;i<m;i++) a[i]=-1; i=0; do{ printf("\n to insert file press : 1 else press : 2"); printf(" \n enter your choice: \n "); scanf("%d",&n); if(n==1) { L1: printf("Enter the starting block of file %d",(i+1)); scanf("%d",&s[i]); if(a[s[i]]==0) { printf("this block was already filled \n"); goto L1; } L2: a[s[i]]=0; printf("Enter the ending block of file %d",(i+1)); scanf("%d",&e[i]); if(a[e[i]]==0) { printf("this block was already filled \n"); goto L2; } a[e[i]]=0; printf("enter the number of intermediate blocks of file %d",(i+1)); scanf("%d",&in[i]); printf("enter the intermediate blicks one by one \n"); for(j=0;j<in[i];j++) { scanf("%d",&inn[i][j]); if(a[inn[i][j]]==0) { printf("this block was already filled \n"); printf("enter another block\ n"); j--; continue; } } }while(n= =1); count=i; } i+ +; a[inn[i][j]]=0; for(i=0;i<count;i++) { printf("the file %d is linked as follows",(i+1)); printf("%d",s[i ]); for(j=0;j<in[i]; j++) { printf("-->%d",inn[i][j]); } printf("-->%d\n",e[i]); } getch(); } 2.2.1 INPUT AND OUTPUT enter the total memory100 to insert file press : 1 else press : 2 enter your choice: 1 Enter the starting block of file 121 Enter the ending block of file 171 enter the number of intermediate blocks of file 14 enter the intermediate blocks one by one 2 78 77 90 to insert file press : 1 else press : 2 enter your choice: 1 Enter the starting block of file 277 this block was already filled Enter the starting block of file 221 this block was already filled Enter the starting block of file 23 Enter the ending block of file 26 enter the number of intermediate blocks of file 22 enter the intermediate blocks one by one 7980 To insert file press: 1 else press: 2 Enter your choice: 2 The file 1 is linked as follows21-->2-- >78-->77-->90-->71 The file 2 is linked as follows3-->79-->80-->6