CS2257 Operating System Lab CS 2257 OPERATING SYSTEMS LAB LTPC 0 0 3 2 1. Write programs using the following system calls of UNIX operating system: fork, exec, getpid, exit, wait, close, stat, opendir, readdir 2. Write programs using the I/O System calls of UNIX operating system (open, read, write, etc). 3. Write C programs to simulate UNIX commands like ls, grep, etc. 4. Given the list of processes, their CPU burst times and arrival times. Display/print the Gantt chart for FCFS and SJF. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. 5. Given the list of processes, their CPU burst times and arrival times. Display/print the Gantt chart for Priority and Round robin. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. 6. Develop application using Inter-Process Communication (using shared memory, pipes or message queues). 7. Implement the Producer-Consumer problem using semaphores (using UNIX system calls) 8. Implement Memory management schemes like paging and segmentation. 9. Implement Memory management schemes like First fit, Best fit and Worst fit. 10. Implement any file allocation techniques (Contiguous, Linked or Indexed). www.rejinpaul.com
102
Embed
CS 2257 OPERATING SYSTEMS LAB LTPC 0 0 3 2 ...€¦ · CS2257 Operating System Lab Vijai Anand CS 2257 OPERATING SYSTEMS LAB LTPC 0 0 3 2 1. Write programs using the following system
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
CS2257 Operating System Lab
http://cseannauniv.blogspot.com Vijai Anand
CS 2257 OPERATING SYSTEMS LAB LTPC 0 0 3 2
1. Write programs using the following system calls of UNIX operating system:fork, exec, getpid, exit, wait, close, stat, opendir, readdir
2. Write programs using the I/O System calls of UNIX operating system (open, read,write, etc).
3. Write C programs to simulate UNIX commands like ls, grep, etc.
4. Given the list of processes, their CPU burst times and arrival times. Display/print theGantt chart for FCFS and SJF. For each of the scheduling policies, compute and printthe average waiting time and average turnaround time.
5. Given the list of processes, their CPU burst times and arrival times. Display/print theGantt chart for Priority and Round robin. For each of the scheduling policies, computeand print the average waiting time and average turnaround time.
6. Develop application using Inter-Process Communication (using shared memory, pipesor message queues).
7. Implement the Producer-Consumer problem using semaphores (using UNIX systemcalls)
8. Implement Memory management schemes like paging and segmentation.
9. Implement Memory management schemes like First fit, Best fit and Worst fit.
10. Implement any file allocation techniques (Contiguous, Linked or Indexed).
The fork system call is used to create a new process called child process.o The return value is 0 for a child process.o The return value is negative if process creation is unsuccessful.o For the parent process, return value is positive
The child process is an exact copy of the parent process.Both the child and parent continue to execute the instructions following fork call.The child can start execution before the parent or vice-versa.
getpid() and getppid()
The getpid system call returns process ID of the calling processThe getppid system call returns parent process ID of the calling process
wait()
The wait system call causes the parent process to be blocked until a child terminates.When a process terminates, the kernel notifies the parent by sending the SIGCHLDsignal to the parent.Without wait, the parent may finish first leaving a zombie child, to be adopted by initprocess
execl()
The exec family of function (execl, execv, execle, execve, execlp, execvp) is used by thechild process to load a program and execute.execl system call requires path, program name and null pointer
exit()
The exit system call is used to terminate a process either normally or abnormallyCloses all standard I/O streams.
stat()
The stat system call is used to return information about a file as a structure.
opendir(), readdir()and closedir()
The opendir system call is used to open a directoryo It returns a pointer to the first entryo It returns NULL on error.
The readdir system call is used to read a directory as a dirent structureo It returns a pointer pointing to the next entry in directory streamo It returns NULL if an error or end-of-file occurs.
The closedir system call is used to close the directory streamWrite to a directory is done only by the kernel.
To create a new child process using fork system call.
Algorithm1. Declare a variable x to be shared by both child and parent.2. Create a child process using fork system call.3. If return value is -1 then
a. Print "Process creation unsuccessfull"b. Terminate using exit system call.
4. If return value is 0 thena. Print "Child process"b. Print process id of the child using getpid system callc. Print value of xd. Print process id of the parent using getppid system call
5. Otherwisea. Print "Parent process"b. Print process id of the parent using getpid system callc. Print value of xd. Print process id of the shell using getppid system call.
6. Stop
Result Thus a child process is created with copy of its parent's address space.
if (pid < 0) { printf("Process creation error"); exit(-1); } else if (pid == 0) { printf("Child process:"); printf("\nProcess id is %d", getpid()); printf("\nValue of x is %d", x); printf("\nProcess id of parent is %d\n", getppid()); } else { printf("\nParent process:"); printf("\nProcess id is %d", getpid()); printf("\nValue of x is %d", x); printf("\nProcess id of shell is %d\n", getppid()); }}
To load an executable program in a child processes exec system call.
Algorithm
1. If no. of command line arguments 3 then stop.2. Create a child process using fork system call.3. If return value is -1 then
a. Print "Process creation unsuccessfull"b. Terminate using exit system call.
4. If return value is > 0 thena. Suspend parent process until child completes using wait system callb. Print "Child Terminated".c. Terminate the parent process.
5. If return value is 0 thena. Print "Child starts"b. Load the program in the given path into child process using exec system call.c. If return value of exec is negative then print the exception and stop.d. Terminate the child process.
6. Stop
Result
Thus the child process loads a binary executable file into its address space.
1. Get filename as command line argument.2. If filename does not exist then stop.3. Call stat system call on the filename that returns a structure4. Display members st_uid, st_gid, st_blksize, st_block, st_size, st_nlink, etc.,5. Convert time members such as st_atime, st_mtime into time using ctime function6. Compare st_mode with mode constants such as S_IRUSR, S_IWGRP, S_IXOTH and
display file permissions.7. Stop
Result
Thus attributes of a file is displayed using stat system call.
To display directory contents using readdir system call.
Algorithm
1. Get directory name as command line argument.2. If directory does not exist then stop.3. Open the directory using opendir system call that returns a structure4. Read the directory using readdir system call that returns a structure5. Display d_name member for each entry.6. Close the directory using closedir system call.7. Stop
Result
Thus files and subdirectories in the directory was listed that includes hidden files.
Used to open an existing file for reading/writing or to create a new file.Returns a file descriptor whose value is negative on error.The mandatory flags are O_RDONLY, O_WRONLY and O_RDWROptional flags include O_APPEND, O_CREAT, O_TRUNC, etcThe flags are ORed.The mode specifies permissions for the file.
creat()
Used to create a new file and open it for writing.It is replaced with open() with flags O_WRONLY|O_CREAT | O_TRUNC
read()
Reads no. of bytes from the file or from the terminal.If read is successful, it returns no. of bytes read.The file offset is incremented by no. of bytes read.If end-of-file is encountered, it returns 0.
write()
Writes no. of bytes onto the file.After a successful write, file's offset is incremented by the no. of bytes written.If any error due to insufficient storage space, write fails.
close()
Closes a opened file.When process terminates, files associated with the process are automaticallyclosed.
1. Declare a character buffer buf to store 100 bytes.2. Get the new filename as command line argument.3. Create a file with the given name using open system call with O_CREAT and
O_TRUNC options.4. Check the file descriptor.
a) If file creation is unsuccessful, then stop.5. Get input from the console until user types Ctrl+D
a) Read 100 bytes (max.) from console and store onto buf using read system callb) Write length of buf onto file using write system call.
6. Close the file using close system call.7. Stop
Result
Thus a file has been created with input from the user. The process can be verified byusing cat command.
To read the given file and to display file contents.
Algorithm
1. Declare a character buffer buf to store 100 bytes.2. Get existing filename as command line argument.3. Open the file for reading using open system call with O_RDONLY option.4. Check the file descriptor.
a) If file does not exist, then stop.5. Read until end-of-file using read system call.
a) Read 100 bytes (max.) from file and print it6. Close the file using close system call.7. Stop
Result
Thus the given file is read and displayed on the console. The process can be verified byusing cat command.
1. Declare a character buffer buf to store 100 bytes.2. Get exisiting filename as command line argument.3. Create a file with the given name using open system call with O_APPEND option.4. Check the file descriptor.
a) If value is negative, then stop.5. Get input from the console until user types Ctrl+D
a) Read 100 bytes (max.) from console and store onto buf using read system callb) Write length of buf onto file using write system call.
6. Close the file using close system call.7. Stop
Result
Thus contents have been written to end of the file. The process can be verified by usingcat command.
Using UNIX system calls, most commands can be emulated in a similar manner.Simulating a command and all of its options is an exhaustive exercise.Command simulation harnesses one's programming skills.Command simulation helps in development of standard routines to becustomized to the application needs.Generally file I/O commands are simulated.
1. Store path of current working directory using getcwd system call.2. Scan directory of the stored path using scandir system call and sort the resultant
array of structure.3. Display dname member for all entries if it is not a hidden file.4. Stop.
Result
Thus the filenames/subdirectories are listed, similar to ls command.
1. Get filename and search string as command-line argument.2. Open the file in read-only mode using open system call.3. If file does not exist, then stop.4. Let length of the search string be n.5. Read line-by-line until end-of-file
a. Check to find out the occurrence of the search string in a line by examiningcharacters in the range 1–n, 2–n+1, etc.
b. If search string exists, then print the line.6. Close the file using close system call.7. Stop.
Result
Thus the program simulates grep command by listing lines containing the search text.
1. Get source and destination filename as command-line argument.2. Declare a buffer of size 1KB3. Open the source file in readonly mode using open system call.4. If file does not exist, then stop.5. Create the destination file using creat system call.6. If file cannot be created, then stop.7. File copy is achieved as follows:
a. Read 1KB data from source file and store onto buffer using read system call.b. Write the buffer contents onto destination file using write system call.c. If end-of-file then step 8 else step 7a.
8. Close source and destination file using close system call.9. Stop.
Result
Thus a file is copied using file I/O. The cmp command can be used to verify thatcontents of both file are same
1. Get filename as command-line argument.2. Open the file in read-only mode using read system call.3. If file does not exist, then stop.4. Close the file using close system call.5. Delete the file using unlink system call.6. Stop.
Result
Thus files can be deleted in a manner similar to rm command. The deletion of file can beverified by using ls command.
CPU scheduling is used in multiprogrammed operating systems.By switching CPU among processes, efficiency of the system can be improved.Some scheduling algorithms are FCFS, SJF, Priority, Round-Robin, etc.Gantt chart provides a way of visualizing CPU scheduling and enables tounderstand better.
First Come First Serve (FCFS)
Process that comes first is processed firstFCFS scheduling is non-preemptiveNot efficient as it results in long average waiting time.Can result in starvation, if processes at beginning of the queue have longbursts.
Shortest Job First (SJF)
Process that requires smallest burst time is processed first.SJF can be preemptive or non–preemptiveWhen two processes require same amount of CPU utilization, FCFS is used tobreak the tie.Generally efficient as it results in minimal average waiting time.Can result in starvation, since long critical processes may not be processed.
Priority
Process that has higher priority is processed first.Prioirty can be preemptive or non–preemptiveWhen two processes have same priority, FCFS is used to break the tie.Can result in starvation, since low priority processes may not be processed.
Round Robin
All processes are processed one by one as they have arrived, but in rounds.Each process cannot take more than the time slice per round.Round robin is a fair preemptive scheduling algorithm.A process that is yet to complete in a round is preempted after the time sliceand put at the end of the queue.When a process is completely processed, it is removed from the queue.www.re
To schedule snapshot of processes queued according to FCFS (First Come First Serve)scheduling.
Algorithm
1. Define an array of structure process with members pid, btime, wtime & ttime.2. Get length of the ready queue, i.e., number of process (say n)3. Obtain btime for each process.4. The wtime for first process is 0.5. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
6. Compute average waiting time awat and average turnaround time atur7. Display the btime, ttime and wtime for each process.8. Display GANTT chart for the above scheduling9. Display awat time and atur10. Stop
Result
Thus waiting time & turnaround time for processes based on FCFS scheduling wascomputed and the average waiting time was determined.
struct process{ int pid; int btime; int wtime; int ttime;} p[10];
main(){ int i,j,k,n,ttur,twat; float awat,atur;
printf("Enter no. of process : "); scanf("%d", &n); for(i=0; i<n; i++) { printf("Burst time for process P%d (in ms) : ",(i+1)); scanf("%d", &p[i].btime); p[i].pid = i+1; }
$./a.outEnter no. of process : 4Burst time for process P1 (in ms) : 10Burst time for process P2 (in ms) : 4Burst time for process P3 (in ms) : 11Burst time for process P4 (in ms) : 6
To schedule snapshot of processes queued according to SJF (Shortest Job First)scheduling.
Algorithm
1. Define an array of structure process with members pid, btime, wtime & ttime.2. Get length of the ready queue, i.e., number of process (say n)3. Obtain btime for each process.4. Sort the processes according to their btime in ascending order.
a. If two process have same btime, then FCFS is used to resolve the tie.5. The wtime for first process is 0.6. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
7. Compute average waiting time awat and average turn around time atur.8. Display btime, ttime and wtime for each process.9. Display GANTT chart for the above scheduling10. Display awat and atur11. Stop
Result
Thus waiting time & turnaround time for processes based on SJF scheduling wascomputed and the average waiting time was determined.
struct process{ int pid; int btime; int wtime; int ttime;} p[10], temp;
main(){ int i,j,k,n,ttur,twat; float awat,atur;
printf("Enter no. of process : "); scanf("%d", &n); for(i=0; i<n; i++) { printf("Burst time for process P%d (in ms) : ",(i+1)); scanf("%d", &p[i].btime); p[i].pid = i+1; }
$./a.outEnter no. of process : 5Burst time for process P1 (in ms) : 10Burst time for process P2 (in ms) : 6Burst time for process P3 (in ms) : 5Burst time for process P4 (in ms) : 6Burst time for process P5 (in ms) : 9
To schedule snapshot of processes queued according to Priority scheduling.
Algorithm
1. Define an array of structure process with members pid, btime, pri, wtime & ttime.2. Get length of the ready queue, i.e., number of process (say n)3. Obtain btime and pri for each process.4. Sort the processes according to their pri in ascending order.
a. If two process have same pri, then FCFS is used to resolve the tie.5. The wtime for first process is 0.6. Compute wtime and ttime for each process as:
a. wtimei+1 = wtimei + btimei
b. ttimei = wtimei + btimei
7. Compute average waiting time awat and average turn around time atur8. Display the btime, pri, ttime and wtime for each process.9. Display GANTT chart for the above scheduling10. Display awat and atur11. Stop
Result
Thus waiting time & turnaround time for processes based on Priority scheduling wascomputed and the average waiting time was determined.
struct process{ int pid; int btime; int pri; int wtime; int ttime;} p[10], temp;
main(){ int i,j,k,n,ttur,twat; float awat,atur;
printf("Enter no. of process : "); scanf("%d", &n); for(i=0; i<n; i++) { printf("Burst time for process P%d (in ms) : ", (i+1)); scanf("%d", &p[i].btime); printf("Priority for process P%d : ", (i+1)); scanf("%d", &p[i].pri); p[i].pid = i+1; }
$ ./a.outEnter no. of process : 5Burst time for process P1 (in ms) : 10Priority for process P1 : 3Burst time for process P2 (in ms) : 7Priority for process P2 : 1Burst time for process P3 (in ms) : 6Priority for process P3 : 3Burst time for process P4 (in ms) : 13Priority for process P4 : 4Burst time for process P5 (in ms) : 5Priority for process P5 : 2
To schedule snapshot of processes queued according to Round robin scheduling.
Algorithm
1. Get length of the ready queue, i.e., number of process (say n)2. Obtain Burst time Bi for each processes Pi.3. Get the time slice per round, say TS4. Determine the number of rounds for each process.5. The wait time for first process is 0.6. If Bi > TS then process takes more than one round. Therefore turnaround and waiting
time should include the time spent for other remaining processes in the same round.7. Calculate average waiting time and turn around time8. Display the GANTT chart that includes
a. order in which the processes were processed in progression of roundsb. Turnaround time Ti for each process in progression of rounds.
9. Display the burst time, turnaround time and wait time for each process (in order ofrounds they were processed).
10. Display average wait time and turnaround time11. Stop
Result
Thus waiting time and turnaround time for processes based on Round robin schedulingwas computed and the average waiting time was determined.
main(){ int i,x=-1,k[10],m=0,n,t,s=0; int a[50],temp,b[50],p[10],bur[10],bur1[10]; int wat[10],tur[10],ttur=0,twat=0,j=0; float awat,atur;
printf("Enter no. of process : "); scanf("%d", &n); for(i=0; i<n; i++) { printf("Burst time for process P%d : ", (i+1)); scanf("%d", &bur[i]); bur1[i] = bur[i]; } printf("Enter the time slice (in ms) : "); scanf("%d", &t);
$ ./a.outEnter no. of process : 5Burst time for process P1 : 10Burst time for process P2 : 29Burst time for process P3 : 3Burst time for process P4 : 7Burst time for process P5 : 12Enter the time slice (in ms) : 10
Inter-Process communication (IPC), is the mechanism whereby one process cancommunicate with another process, i.e exchange data.IPC in linux can be implemented using pipe, shared memory, message queue,semaphore, signal or sockets.
Pipe
Pipes are unidirectional byte streams which connect the standard output fromone process into the standard input of another process.A pipe is created using the system call pipe that returns a pair of file descriptors.The descriptor pfd[0] is used for reading and pfd[1] is used for writing.Can be used only between parent and child processes.
Shared memory
Two or more processes share a single chunk of memory to communicaterandomly.Semaphores are generally used to avoid race condition amongst processes.Fastest amongst all IPCs as it does not require any system call.It avoids copying data unnecessarily.
Message Queue
A message queue is a linked list of messages stored within the kernelA message queue is identified by a unique identifierEvery message has a positive long integer type field, a non-negative length, andthe actual data bytes.The messages need not be fetched on FCFS basis. It could be based on type field.
Semaphores
A semaphore is a counter used to synchronize access to a shared data amongstmultiple processes.To obtain a shared resource, the process should:
o Test the semaphore that controls the resource.o If value is positive, it gains access and decrements value of semaphore.o If value is zero, the process goes to sleep and awakes when value is > 0.
When a process relinquishes resource, it increments the value of semaphore by 1.
Producer-Consumer problem
A producer process produces information to be consumed by a consumer processA producer can produce one item while the consumer is consuming another one.With bounded-buffer size, consumer must wait if buffer is empty, whereasproducer must wait if buffer is full.The buffer can be implemented using any IPC facility.
To generate 25 fibonacci numbers and determine prime amongst them using pipe.
Algorithm
1. Declare a array to store fibonacci numbers2. Decalre a array pfd with two elements for pipe descriptors.3. Create pipe on pfd using pipe function call.
a. If return value is -1 then stop4. Using fork system call, create a child process.5. Let the child process generate 25 fibonacci numbers and store them in a array.6. Write the array onto pipe using write system call.7. Block the parent till child completes using wait system call.8. Store fibonacci nos. written by child from the pipe in an array using read system call9. Inspect each element of the fibonacci array and check whether they are prime
a. If prime then print the fibonacci term.10. Stop
Result
Thus fibonacci numbers that are prime is determined using IPC pipe.
To determine number of users logged in using pipe.
Algorithm
1. Decalre a array pfd with two elements for pipe descriptors.2. Create pipe on pfd using pipe function call.
a. If return value is -1 then stop3. Using fork system call, create a child process.4. Free the standard output (1) using close system call to redirect the output to pipe.5. Make a copy of write end of the pipe using dup system call.6. Execute who command using execlp system call.7. Free the standard input (0) using close system call in the other process.8. Make a close of read end of the pipe using dup system call.9. Execute wc –l command using execlp system call.10. Stop
Result
Thus standard output of who is connected to standard input of wc using pipe to computenumber of users logged in.
To exchange message between server and client using message queue.
Algorithm
Server
1. Decalre a structure mesgq with type and text fields.2. Initialize key to 2013 (some random value).3. Create a message queue using msgget with key & IPC_CREAT as parameter.
a. If message queue cannot be created then stop.4. Initialize the message type member of mesgq to 1.5. Do the following until user types Ctrl+D
a. Get message from the user and store it in text member.b. Delete the newline character in text member.c. Place message on the queue using msgsend for the client to read.d. Retrieve the response message from the client using msgrcv functione. Display the text contents.
6. Remove message queue from the system using msgctl with IPC_RMID as parameter.7. Stop
Client
1. Decalre a structure mesgq with type and text fields.2. Initialize key to 2013 (same value as in server).3. Open the message queue using msgget with key as parameter.
a. If message queue cannot be opened then stop.4. Do while the message queue exists
a. Retrieve the response message from the server using msgrcv functionb. Display the text contents.c. Get message from the user and store it in text member.d. Delete the newline character in text member.e. Place message on the queue using msgsend for the server to read.
5. Print "Server Disconnected".6. Stop
Result
Thus chat session between client and server was done using message queue.
To demonstrate communication between process using shared memory.
Algorithm
Server
1. Initialize size of shared memory shmsize to 27.2. Initialize key to 2013 (some random value).3. Create a shared memory segment using shmget with key & IPC_CREAT as parameter.
a. If shared memory identifier shmid is -1, then stop.4. Display shmid.5. Attach server process to the shared memory using shmmat with shmid as parameter.
a. If pointer to the shared memory is not obtained, then stop.6. Clear contents of the shared region using memset function.7. Write a–z onto the shared memory.8. Wait till client reads the shared memory contents9. Detatch process from the shared memory using shmdt system call.10. Remove shared memory from the system using shmctl with IPC_RMID argument11. Stop
Client
1. Initialize size of shared memory shmsize to 27.2. Initialize key to 2013 (same value as in server).3. Obtain access to the same shared memory segment using same key.
a. If obtained then display the shmid else print "Server not started"4. Attach client process to the shared memory using shmmat with shmid as parameter.
a. If pointer to the shared memory is not obtained, then stop.5. Read contents of shared memory and print it.6. After reading, modify the first character of shared memory to '*'7. Stop
Result
Thus contents written onto shared memory by the server process is read by the clientprocess.
To synchronize producer and consumer processes using semaphore.
Algorithm
1. Create a shared memory segment BUFSIZE of size 1 and attach it.2. Obtain semaphore id for variables empty, mutex and full using semget function.3. Create semaphore for empty, mutex and full as follows:
a. Declare semun, a union of specific commands.b. The initial values are: 1 for mutex, N for empty and 0 for fullc. Use semctl function with SETVAL command
4. Create a child process using fork system call.a. Make the parent process to be the producerb. Make the child process to the consumer
5. The producer produces 5 items as follows:a. Call wait operation on semaphores empty and mutex using semop function.b. Gain access to buffer and produce data for consumptionc. Call signal operation on semaphores mutex and full using semop function.
6. The consumer consumes 5 items as follows:a. Call wait operation on semaphores full and mutex using semop function.b. Gain access to buffer and consume the available data.c. Call signal operation on semaphores mutex and empty using semop function.
7. Remove shared memory from the system using shmctl with IPC_RMID argument8. Stop
Result
Thus synchronization between producer and consumer process for access to a sharedmemory segment is implemented.
Enter data for producer to produce : 8Consumer consumes data 5Enter data for producer to produce : 4Consumer consumes data 8Enter data for producer to produce : 2Consumer consumes data 4Enter data for producer to produce : 9Consumer consumes data 2Consumer consumes data 9
The first-fit, best-fit, or worst-fit strategy is used to select a free hole from the setof available holes.
First fit
Allocate the first hole that is big enough.Searching starts from the beginning of set of holes.
Best fit
Allocate the smallest hole that is big enough.The list of free holes is kept sorted according to size in ascending order.This strategy produces smallest leftover holes
Worst fit
Allocate the largest hole.The list of free holes is kept sorted according to size in descending order.This strategy produces the largest leftover hole.
The widely used page replacement algorithms are FIFO and LRU.
FIFO
Page replacement is based on when the page was brought into memory.When a page should be replaced, the oldest one is chosen.Generally, implemented using a FIFO queue.Simple to implement, but not efficient.Results in more page faults.The page-fault may increase, even if frame size is increased (Belady's anomaly)
LRU
Pages used in the recent past are used as an approximation of future usage.The page that has not been used for a longer period of time is replaced.LRU is efficient but not optimal.Implementation of LRU requires hardware support, such as counters/stack.
To allocate memory requirements for processes using first fit allocation.
Algorithm
1. Declare structures hole and process to hold information about set of holes andprocesses respectively.
2. Get number of holes, say nh.3. Get the size of each hole4. Get number of processes, say np.5. Get the memory requirements for each process.6. Allocate processes to holes, by examining each hole as follows:
a. If hole size > process size theni. Mark process as allocated to that hole.
ii. Decrement hole size by process size.b. Otherwise check the next from the set of hole
7. Print the list of process and their allocated holes or unallocated status.8. Print the list of holes, their actual and current availability.9. Stop
Result
Thus processes were allocated memory using first fit method.
struct process{ int size; int flag; int holeid;} p[10];struct hole{ int size; int actual;} h[10];
main(){ int i, np, nh, j;
printf("Enter the number of Holes : "); scanf("%d", &nh); for(i=0; i<nh; i++) { printf("Enter size for hole H%d : ",i); scanf("%d", &h[i].size); h[i].actual = h[i].size; }
printf("\nEnter number of process : " ); scanf("%d",&np); for(i=0;i<np;i++) { printf("enter the size of process P%d : ",i); scanf("%d", &p[i].size); p[i].flag = 0; }
$ ./a.outEnter the number of Holes : 5Enter size for hole H0 : 100Enter size for hole H1 : 500Enter size for hole H2 : 200Enter size for hole H3 : 300Enter size for hole H4 : 600
Enter number of process : 4enter the size of process P0 : 212enter the size of process P1 : 417enter the size of process P2 : 112enter the size of process P3 : 426
First fit
Process PSize HoleP0 212 H1P1 417 H4P2 112 H1P3 426 Not allocated
To allocate memory requirements for processes using best fit allocation.
Algorithm
1. Declare structures hole and process to hold information about set of holes andprocesses respectively.
2. Get number of holes, say nh.3. Get the size of each hole4. Get number of processes, say np.5. Get the memory requirements for each process.6. Allocate processes to holes, by examining each hole as follows:
a. Sort the holes according to their sizes in ascending orderb. If hole size > process size then
i. Mark process as allocated to that hole.ii. Decrement hole size by process size.
c. Otherwise check the next from the set of sorted hole7. Print the list of process and their allocated holes or unallocated status.8. Print the list of holes, their actual and current availability.9. Stop
Result
Thus processes were allocated memory using best fit method.
struct process{ int size; int flag; int holeid;} p[10];struct hole{ int hid; int size; int actual;} h[10];
main(){ int i, np, nh, j; void bsort(struct hole[], int);
printf("Enter the number of Holes : "); scanf("%d", &nh); for(i=0; i<nh; i++) { printf("Enter size for hole H%d : ",i); scanf("%d", &h[i].size); h[i].actual = h[i].size; h[i].hid = i; }
printf("\nEnter number of process : " ); scanf("%d",&np); for(i=0;i<np;i++) { printf("enter the size of process P%d : ",i); scanf("%d", &p[i].size); p[i].flag = 0; }
$ ./a.outEnter the number of Holes : 5Enter size for hole H0 : 100Enter size for hole H1 : 500Enter size for hole H2 : 200Enter size for hole H3 : 300Enter size for hole H4 : 600
Enter number of process : 4enter the size of process P0 : 212enter the size of process P1 : 417enter the size of process P2 : 112enter the size of process P3 : 426
To implement demand paging for a reference string using FIFO method.
Algorithm
1. Get length of the reference string, say l.2. Get reference string and store it in an array, say rs.3. Get number of frames, say nf.4. Initalize frame array upto length nf to -1.5. Initialize position of the oldest page, say j to 0.6. Initialize no. of page faults, say count to 0.7. For each page in reference string in the given order, examine:
a. Check whether page exist in the frame arrayb. If it does not exist then
i. Replace page in position j.ii. Compute page replacement position as (j+1) modulus nf.
iii. Increment count by 1.iv. Display pages in frame array.
8. Print count.9. Stop
Result
Thus page replacement was implemented using FIFO algorithm.
To implement demand paging for a reference string using LRU method.
Algorithm
1. Get length of the reference string, say len.2. Get reference string and store it in an array, say rs.3. Get number of frames, say nf.4. Create access array to store counter that indicates a measure of recent usage.5. Create a function arrmin that returns position of minimum of the given array.6. Initalize frame array upto length nf to -1.7. Initialize position of the page replacement, say j to 0.8. Initialize freq to 0 to track page frequency9. Initialize no. of page faults, say count to 0.10. For each page in reference string in the given order, examine:
a. Check whether page exist in the frame array.b. If page exist in memory then
i. Store incremented freq for that page position in access array.c. If page does not exist in memory then
i. Check for any empty frames.ii. If there is an empty frame,
Assign that frame to the pageStore incremented freq for that page position in access array.Increment count.
iii. If there is no free frame thenDetermine page to be replaced using arrmin function.Store incremented freq for that page position in access array.Increment count.
iv. Display pages in frame array.11. Print count.12. Stop
Result
Thus page replacement was implemented using LRU algorithm.www.re
The three methods of allocating disk space are:1. Contiguous allocation2. Linked allocation3. Indexed allocation
Contiguous
Each file occupies a set of contiguous block on the disk.The number of disk seeks required is minimal.The directory contains address of starting block and number of contiguousblock (length) occupied.Supports both sequential and direct access.First / best fit is commonly used for selecting a hole.
Linked
Each file is a linked list of disk blocks.The directory contains a pointer to first and last blocks of the file.The first block contains a pointer to the second one, second to third and so on.File size need not be known in advance, as in contiguous allocation.No external fragmentation.Supports sequential access only.
Indexed
In indexed allocation, all pointers are put in a single block known as indexblock.The directory contains address of the index block.The ith entry in the index block points to ith block of the file.Indexed allocation supports direct access.It suffers from pointer overhead, i.e wastage of space in storing pointers.
To implement file allocation on free disk space in a contiguous manner.
Algorithm
1. Assume no. of blocks in the disk as 20 and all are free.2. Display the status of disk blocks before allocation.3. For each file to be allocated:
a. Get the filename, start address and file lengthb. If start + length > 20, then goto step 2.c. Check to see whether any block in the range (start, start + length-1) is
allocated. If so, then go to step 2.d. Allocate blocks to the file contiguously from start block to start + length – 1.
4. Display directory entries.5. Display status of disk blocks after allocation6. Stop
Result
Thus contiguous allocation is done for files with the available free blocks.