You are on page 1of 50

KARPAGAM INSTITUTE OF TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY

CS 2257 OPERATING SYSTEM LAB

LAB MANUAL

TABLE OF CONTENTS

CHAPTER NO I

TOPIC

PAGE NO

Introduction to the language Main Features Advantages Limitations Applications

II III IV

Syllabus System Requirements Description about each experiment Aim Learning Objective

Experiments 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. (2 sessions) 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. (2 sessions).

Developing Application using Inter Process Communication (using shared memory, or message queues)

Implement the Producer Consumer problem using semaphores (using UNIX system calls) Implement some memory management schemes I Implement some memory management schemes II Implement any file allocation technique (Linked, Indexed or Contiguous)

8 9 10

INTRODUCTION OF THE LANGUAGE (Linux) MAIN FEATURES Linux is a generic term referring to Unix-like computer operating systems based on the Linux kernel. Their development is one of the most prominent examples of free and open source software collaboration; typically all the underlying source code can be used, freely modified, and redistributed by anyone. The name "Linux" comes from the Linux kernel, originally written in 1991 by Linus Torvalds. The rest of the system usually comprises components such as the Apache HTTP Server, the X Window System, the K Desktop Environment, and utilities and libraries from the GNU operating system (announced in 1983 by Richard Stallman). Many quantitative studies of free / open source software focus on topics including market share and reliability, with numerous studies specifically examining Linux. The Linux market is growing rapidly, and the revenue of servers, desktops, and packaged software running Linux was expected to exceed $35.7 billion by 2008. ADVANTAGES Cost The most obvious advantage of using Linux is the fact that it is free to obtain, while Microsoft products are available for a hefty and sometimes recurring fee. Security In line with the costs, the security aspect of Linux is much stronger than that of Windows. Choice (Freedom) The power of choice is a great Linux advantage. With Linux, you have the power to control just about every aspect of the operating system Software - There are so many software choices when it comes to doing any specific task. You could search for a text editor on Freshmeat and yield hundreds, if not thousands of results. My article on 5 Linux text editors you should know about explains how there are so many options just for editing text on the command-line due to the open source nature of Linux. Hardware - Linux is perfect for those old computers with barely anyprocessing power or memory you have sitting in your garage or basementcollecting dust. LIMITATIONS Understanding Becoming familiar with the Linux operating system requires patience as well as a strong learning curve. You must have the desire to read and figure things out on your own, rather than having everything done for you. Check out the 20 must read how tos and guides for Linux.

Compatibility Because of its free nature, Linux is sometimes behind the curve when it comes to brand new hardware compatibility. Though the kernel contributors and 5 maintainers work hard at keeping the kernel up to date, Linux does not have as much of a corporate backing as alternative operating systems. Sometimes you can find third party applications, sometimes you cant. Alternative Programs Though Linux developers have done a great job at creating alternatives to popular Windows applications, there are still some applications that exist on Windows that have no equivalent Linux application. Read Alternatives to Windows Applications to find out some of the popular alternatives. APPLICATIONS OpenShot (Video editor) Apache (Web server) Firefox (Web browser) Dropbox (Online storage) Asterisk (Telephony)

CS2257 OPERATING SYSTEM LAB LIST OF EXPERIMENTS

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 Ganttchart for FCFS and SJF. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. (2 sessions) 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. (2 sessions) 6. Developing Application using Inter Process Communication (using shared memory, or message queues) 7. Implement the Producer Consumer problem using semaphores (using UNIX system calls). 8. Implement some memory management schemes I 9. Implement some memory management schemes II 10. Implement any file allocation technique (Linked, Indexed or Contiguous)

HARDWARE REQUIREMENTS
System O/S Compiler :1 : Linux or Unix : Turbo C or TC3

ABOUT THE OPERATING SYSTEM LAB AIM At the end of the course students should be able to describe the general structure and purpose of an operating system; explain the concepts of process, address space, and file; compare and contrast various CPU scheduling algorithms; understand the differences between segmented and paged memories, and be able to describe the advantages and disadvantages of each; Compare and contrast polled, interrupt-driven and DMA-based access to I/O devices.. OVERVIEW OF THE EXPERIMENTS To implement various page replacement memory management schemes to compare and contrast the relative performance of different page replacement schemes. Inter Process Communication Using Shared Memory and Message Queuescan communicates among them using the Shared Memory regions. Shared Memory is an efficient means of passing data between programs. One program will create a memory portion, which other processes (if permitted) can access. A shared segment can be attached multiple times by the same process The way to use the most common system calls in order to make input-output operations on files, as well as operations to handle files and directories in the Linux operating system. Implementation of FCFS and SJF Scheduling, This selects each process from the processes in memory that are ready to execute, and allocates the CPU to one of them using First In First Out and Shortest Job First Scheduling . LEARNING OBJECTIVES The objective of this lab is to teach students about various operating systems including Windows, Mac and Unix. Students learn about systems configuration and administration. Students learn, explore and practice technologies related to mobile computing.

EX.NO: 1 DATE IMPLEMENTATION OF SYSTEM CALLS

DESCRIPTION The fork() function shall create a new process. The new process (child process) shall be an exact copy of the calling process (parent process). The child process shall have a unique process ID. The exec family of functions shall replace the current process image with a new process image. The new image shall be constructed from regular, executable file called the new process image file The exit status will be n, if specified. Otherwise, the value will be the exit value of the las command executed, or zero if no command was executed. When exit is executed in a trap action, the last command is considered to be the command that executed immediately preceding the trap action The readdir() function returns a pointer to a dirent structure representing the next directory entry in the directory stream pointed to by dir. The opendir() function opens a directory stream corresponding to the directory name, and returns a pointer to the directory stream. The stream is positioned at the first entry in the directory OBJECTIVE To keep track of how many times each of the fork, vfork, execl, readdir, opendir and wait system calls is invoked Place counters in kernel code Implement a new system call providing this information Request/retrieve these values from user space by invoking the new system call/s SYNTAX & KEYWORDS Fork: #include<unistd.h> pid_t fork(void);

execl: #include<unistd.h> extern char **environ; int execl(const char *path, const char *arg(), /*, (char *)0 */); exit: #include<stdlib.h> void exit(int status); wait: #include<sys/types.h> #include<sys/wait.h> pid_t wait(int *stat_loc); Readdir() : #include <sys/types.h> #include <dirent.h> struct dirent *readdir(DIR *dir); Opendir(): #include <sys/types.h> #include <dirent.h> DIR *opendir(const char *name);

ALGORITHM Open the VI text editor Create a sub directory under home directory. Type the codes using C language. Use the system calls such as fork(), stat(), getpid(), wait(), exit() Save the file using filename.c. Compile the program using gcc filename.c. Execute the program using ./a.out.

PROGRAM Fork(wait,exec,id_exit) #include<stdio.h> int main(int argc,char *get[]) { int pid; pid=fork(); if(pid<0) { fprintf(stderr,"fork failed"); exit(-1); } else if(pid==0) { execlp("/ucr/games/fortune","fortune",NULL); } else { wait(NULL); printf("\n child completed"); exit(0); } return 0; } OUTPUT Fork(wait,exec,id_exit) child complete PROGRAM Fork(stat) #include<stdio.h> #include<unistd.h>

#include<sys/stat.h> #include<fcntl.h> int main(int argc, char **argv[]) { struct stat x; int fd,i; if(argc==-1) { printf("Usage:%s[ALE]\n",argv[1]); return-1; } if(stat(argv[1],&x)==-1) { perror(lseek); exit(1); } else { printf("File owner:%d\n",x.st_ino); } return 0;} OUTPUT Fork(stat) File owner:1184864 PROGRAM Fork(opendir,readdir) #include<dirent.h> #include<sys/stat.h> main(int argc,char **argv[]) { DIR*dirname; struct dirent *dir;

struct stat fs; int ret; long last; dirname=opendir(argv[1]); printf("\nNODE NO\tNAME\tLENGTH"); while((dir==readdir(dirname))!=NULL) { printf("\n%d\t%s\t%d",dir->d_ino,dir->d_name,dir->d_reclen); printf("\n"); getchar(); } closedir(dirname); ret=stat(argv[1],&fs); if(ret>0) last=fs.st_mtime; printf("\nTIME=%d",last); printf("\nUSER ID=%d",fs.st_uid); } OUTPUT Fork(open dir, read dir) NODE NO 1705167 1779768 1765169 Time UserId NAME . . VICKY =12980252 = 525 LENGTH 16 16 16

RESULT The program for process system call has been executed and shown the result as above.

EX.NO:2 DATE IMPLEMENTATION OF I/O SYSTEM CALL

DESCRIPTION File-I/O through system calls is simpler and operates at a lower level than making calls to the C file-I/O library. There are seven fundamental file-I/O system calls: creat() Create a file for reading or writing. open() Open a file for reading or writing. close() Close a file after reading or writing. write() Write bytes to file. read() Read bytes from file. These calls were devised for the UNIX operating system and are not part of the ANSI C spec. Use of these system calls requires a header file named "fcntl.h": SYNTAXES & KEYWORDS open() : <file descriptor variable> = open( <filename>, <access mode> ); write() : write( <file descriptor>, <buffer>, <buffer length> ); read() : read( <file descriptor>, <buffer>, <buffer length> ); ALGORITHM: Start the Program. Open a file for O_RDWR for read and write, O_CREATE for creating a file, O_TRUNC for truncating a file. Write the contents into a file and close it. Then the file is opened for read only mode and read the characters and displayed it and close the file. Stop the program.

PROGRAM #include<stdio.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> int main() { int fd; char buf1[100],buf2[]="hello everyone",fname[30]; printf("Enter the name:\n"); scanf("%s",fname); if((fd=creat(fname, S_IRWXU))<0) { printf("\n Enter the file creation"); exit(0); } else { write(fd,buf2,30); printf("Contents written successfully"); close(fd); fd=open(fname,O_RDONLY); read(fd,buf1,30); printf("\n The contents is:\n%s",buf1); close(fd); } return(0); }

OUTPUT Enter the name: praveen Contents written successfully The contents is: hello everyone

RESULT The i/o system call program has been executed and shown the results as above.

EX.NO: 3 DATE: SIMULATION OF UNIX COMMANDS

DESCRIPTION Date w, who whoami ls head tail show date and time who is on the system and what they are doing who is logged onto this terminal list files in a directory and their attributes show first few lines of a file(s) show last few lines of a file; or reverse line order

ALGORITHM: 1. Start the program. 2. Enter the options. 3. If the option is 1 call ls command and it display the files. 4. Stop the program. PROGRAM RESULT The program for simulation of unix commands ls and grep has been executed and the shown the results as above

EX.NO: 4 DATE IMPLEMENTATION OF FCFS SCHEDULING

DESCRIPTION The FCFS scheduler simply executes processes to completion in the order they are submitted. This code implements the First come First Served Scheduled algorithm. It gets the number of processes and the process name, burst time and arrival time for each user from the user. It then sorts the processes depending upon the arrival time. Calculates and displays the average turnaround time and waiting time. Then it will display the Gantt chart. EXPECTED OUTPUT AND ITS FORM Performs FCFS scheduling ie) the process that enters the queue first is served first. ALGORITHM: 1. Start the program. 2. Get the number of processes and their burst time. 3. Initialize the waiting time for process 1 is 0. 4. The waiting time and turn around time for other processes are calculated. 5. The waiting time and turn around time for all the processes are summed and then the average waiting time and turn around time are calculated. 6. The average waiting time and turn around time are displayed. 7. Stop the program. PROGRAM #include<stdio.h> main() { int p[10],bt[10],wt[10],tat[10]; int awt=0,atat=0; int i,n; printf("enter the process:");

scanf("%d",&n); printf("enter the burst time:"); for(i=1;i<=n;i++) { p[i]=i; scanf("%d",&bt[i]); } bt[0]=0; wt[0]=0; for(i=1;i<=n;i++) { wt[i]=bt[i-1]+wt[i-1]; tat[i]=bt[i]+wt[i]; awt=wt[i]+awt; atat=tat[i]+atat; } awt=awt/n; atat=atat/n; printf("\n Process id\t\t Turnaround time\t\t Waiting time\n"); for(i=1;i<=n;i++) { printf("\n%d\t\t\t\t%d\t\t\t\t%d",i,tat[i],wt[i]); } printf("\n Average waiting time:%d",awt); printf("\n aVERAGE turnaround time:%d",atat); }

OUTPUT Enter the process:3 Enter the burst time:4 5 6 Process id 1 2 3 Average waiting time:4 Average turnaround time:9 Turnaround time 4 9 15 Waiting time 0 4 9

RESULT The program for first come first serve algorithm has been executed and shown the results as above.

EX.NO:4.b DATE IMPLEMENTATION OF SJF SCHEDULING

DESCRIPTION Associate with each process the length of its next CPU burst. Use these lengths to schedule the process with the shortest time Two schemes: non preemptive once CPU given to the process it cannot be preempted until completes its CPU burst preemptive if a new process arrives with CPU burst length less than remaining time of current executing process, preempt. This scheme is known as the Shortest-RemainingTime-First (SRTF) SJF is optimal gives minimum average waiting time for a given set of processes objective EXPECTED OUTPUT AND ITS FORM Performs SJF scheduling ie) the process that has the shortest burst time is processed first ALGORITHM: 1. Start the program. 2. Get the number of processes and their burst time. 3. Initialize the waiting time for process 1 is 0. 4. The processes are stored according to their burst time. 5. The waiting time and turn around time for other processes are calculated. 6. The waiting time and turn around time for all the processes are summed and then the average waiting time and turn around time are calculated. 7. The average waiting time and turn around time are displayed. 8. Stop the program

PROGRAM #include<stdio.h> int main() { int i,n,j,temp1,temp2,b[10],t[10],w[10],p[10]; float att=0,awt=0; for(i=0;i<n;i++) { b[i]=0; w[i]=0; } printf("\t\t\tSJF"); printf("\nEnter the no. of process:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the burst time of process%d:",i); scanf("%d",&b[i]); p[i]=i; } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(b[i]>b[j]) { temp1=b[i]; temp2=b[i]; b[i]=b[j]; b[j]=temp1; } } } w[0]=0;

for(i=0;i<n;i++) w[i+1]=w[i]+b[i]; for(i=0;i<n;i++) { t[i]=w[i]+b[i]; awt=awt+w[i]; att=att+t[i]; } awt=awt/n; att=att/n; printf("\n\tProcess\tWaiting time\tTurnaround time\n"); for(i=0;i<n;i++) printf("\n\tp[%d]\t%d\t\t%d\n",p[i],w[i],t[i]); printf("\nthe average waiting time is:%f",awt); printf("\nthe average turnaround time is:%f:",att); return -1; } OUTPUT: Enter the no. of process:3 Enter the burst time of process0:8 Enter the burst time of process1:5 Enter the burst time of process2:2 Process Waiting time Turnaround time p[0] p[1] p[2] 0 2 7 2 7 15

the average waiting time is:3.000000

the average turnaround time is:8.000000

RESULT: The program for shortest job first algorithm has been executed and shown the results as above.

EX.NO:5.a DATE IMPLEMENTATION OF PRIORITY SCHEDULING

DESCRIPTION A priority number (integer) is associated with each process The CPU is allocated to the process with the highest priority (smallest integer highest priority) Preemptive non preemptive

SJF is a priority scheduling where priority is the predicted next CPU burst time Problem Starvation low priority processes may never execute Solution Aging as time progresses increase the priority of the process Performs priority scheduling ie) the process that is assigned with a highest priority is processed first. ALGORITHM: 1. Start the program. 2. Get the number of processes, their burst time and priority. 3. Initialize the waiting time for process 1 is 0. 4. Based upon the priority processes are arranged. 5. The waiting time and turn around time for other processes are calculated. 6. The waiting time and turn around time for all the processes are summed and then the average waiting time and turn around time are calculated. 7. The average waiting time and turn around time are displayed. 8. Stop the program. PROGRAM #include<stdio.h> void main() { int x,n,p[10],pry[10],bt[10],w[10],t[10],i,j,awt,atat; printf("\tPRIORITY SCHEDULING");

printf("\nEnter the number of process:"); scanf("%d",&n); printf("Enter the process time priorities\n"); for(i=0;i<n;i++) { printf("\nProcess no%d:enter burst time",i+1); scanf("%d",&bt[i]); printf("\n Enter priority:"); scanf("%d",&pry[i]); p[i]=i+1; } for(i=0;i<n-1;i++) { for(j=i+1;j<n;j++) { if(pry[i]>pry[j]) { x=pry[i]; pry[i]=pry[j]; pry[j]=x; x=bt[i]; bt[i]=bt[j]; bt[j]=x; x=p[i]; p[i]=p[j]; p[j]=x; } } } w[0]=0; awt=0; t[0]=bt[0]; atat=t[0]; for(i=1;i<n;i++)

{ w[i]=t[i-1]; awt+=w[i]; t[i]=w[i]+bt[i]; atat+=t[i]; } printf("\n\nJOB\tBURST TIME\tWAITING TIME\tTURNAROUND TIME\tPRIORITY\n"); for(i=0;i<n;i++) printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d\n",p[i],bt[i],w[i],t[i],pry[i]); awt/=n; atat/=n; printf("\nAverage waiting time:%d\n",awt); printf("\nAverage turn around time:%d\n",atat); }

OUTPUT PRIORITY SCHEDULING Enter the number of process:3 Enter the process time priorities Process no1:enter burst time10 Enter priority:1 Process no2:enter burst time20 Enter priority:2 Process no3:enter burst time30 Enter priority:3 JOB 1 2 3 BURST TIME 10 20 30 WAITING TIME TURNAROUND TIME PRIORITY 0 10 30 10 30 60 1 2 3

Average waiting time:13 Average turn around time:33

RESULT The program for priority scheduling has been executed and shown the results as above.

EX.NO:5.b DATE: IMPLEMENTATION OF ROUND ROBIN SCHEDULING

DESCRIPTION Each process gets a small unit of CPU time (time quantum), usually 10-100 milliseconds. After this time has elapsed, the process is preempted and added to the end of the ready queue. If there are n processes in the ready queue and the time quantum is q, then each process gets 1/n of the CPU time in chunks of at most q time units at once. No process waits more than (n-1)q time units. Performance q large -FIFO q small- q must be large with respect to context switch, otherwise overhead is too high EXPECTED OUTPUT AND ITS FORM Performs round robin scheduling ie) the process that is assigned with a Quantum time and the process is processed for the given quantum time in fcfs fashion. ALGORITHM 1. Start the program. 2. Get the number of processes, their burst time and time slice for each process. 3. Calculate the total burst time. 4. To check whether the burst time of process is less then the time slice, the required time only allotted to the process. 5. If the burst time of process is greater than the time slice one time slice is allotted for the process and burst time is subtracted by one time slice. 6. Step 4 and 5 is repeated up to process burst time is 0. 7. The waiting time and turn around time for all the processes are summed and then the average waiting time and turn around time are calculated. 8. The average waiting time and turn around time are displayed. 9. Stop the program.

PROGRAM #include<stdio.h> struct rr { int pid; int st,ct,wt,rt,tat; } a[10]; int n,q,k,prev,next,j,i,l,wtt; static float avgtat,avgwtt; int main(void) { printf("ROUND ROBIN SCHEDULING"); printf("\n enter the number of process"); scanf("%d",&n); for(i=0;i<n;i++) { printf("\n enter the process id and burst time of the job"); scanf("%d%d",&a[i].pid,&a[i].st); a[i].rt=a[i].st; } printf("enter the time quantum"); scanf("%d",&q); a[0].ct=0; if(a[0].st<q) { a[0].tat=a[0].st; a[0].rt=a[0].st-q; } else { a[0].tat=q; a[0].rt=a[0].st-q;

} a[0].wt=0; prev=0; next=1; while(1) { k=0; for(j=next;j<n;j++) { if(a[j].rt>0) { next=j; a[next].ct=a[prev].tat; if(a[next].rt<q) a[next].tat=a[next].rt+a[next].ct; else a[next].tat=q+a[next].ct; wtt=a[next].st-a[next].rt; a[next].wt=a[next].ct-wtt; a[next].rt=a[next].rt-q; prev=next; } else k++; } if(k==n) break; next=0; } for(i=0;i<n;i++) { avgtat+=(float)a[i].tat/n; avgwtt+=(float)a[i].wt/n; }

printf("PROCESS ID BURST TIME CPU ACCESSTIME TURNAROUND TIME WAITINGTIME"); for(i=0;i<n;i++) { printf("\n %d \t\t%d\t\t%d\t%d\t%d",a[i].pid,a[i].st,a[i].ct,a[i].tat,a[i].wt); } printf("\n avg tat time is:%f",avgtat); printf("\n avg wait time is:%f",avgwtt); }

OUTPUT ROUND ROBIN SCHEDULING enter the number of process3 enter the process id and burst time of the job1 10 enter the process id and burst time of the job2 20 enter the process id and burst time of the job3 30 enter the time quantum50 PROCESS ID BURSTTIME CPUACCESSTIME 1 2 3 10 20 30 0 10 30 TURNAROUNDTIME 10 30 60 WAITINGTIME 0 10 30

avg tat time is:33.333332 avg wait time is:13.333333

RESULT: The program for implementation of round robin scheduling has been executed and shown the results as above.

EX.NO:6 IMPLEMENTATION OF INTERPROCESS COMMUNICATION DATE:

DESCRIPTION A shared memory is an extra piece of memory that is attached to some address spaces for their owners to use. As a result, all of these processes share the same memory segment and have access to it. Consequently, race conditions may occur if memory accesses are not handled properly. The following figure shows two processes and their address spaces. The yellow rectangle is a shared memory attached to both address spaces and both process 1 and process 2 can have access to this shared memory as if the shared memory is part of its own address space. In some sense, the original address space is "extended" by attaching this shared memory. EXPECTED OUTPUT AND ITS FORM This program is designed in such a way that the first instance is automatically the server and any other instance started later is a client. The communication handles correctly the situation when the server is closed while the clients are running. ALGORITHM: 1. Start the program 2. Create the child process using fork() 3. Create the shared memory for parent process using shmget() system call 4. Now allow the parent process to write in shared memory using shmpet pointer which is return type of shmat() 5. Now across and attach the same shared memory to the child process 6. The data in the shared memory is read by the child process using the shnot pointer 7. Now, detach and rebase the shared memory 8. Stop the program

PROGRAM #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/shm.h> #include<errno.h> #include<string.h> #include<ctype.h> extern int errno; #define SIZE 1 char *read_key; int shmid; int shared_init() { if((shmid = shmget(9999, SIZE, IPC_CREAT | 0666)) <0) { printf("Error in shmget.errno is:%d\n",errno); return -1; } if((read_key = shmat(shmid, NULL, 0)) <0) { printf("error in shm attach. errno is:%d \n",errno); return -1; } return 0; } void read_char() { char c; while(1) { c= getchar();

if(c =='\n') { c= getchar(); } strncpy(read_key, &c,SIZE); printf("read_key now is %s\n",read_key); if(isalnum(*read_key)) { shmdt(read_key); shmctl(shmid,IPC_RMID, NULL); exit(1); } } } int main() { if(shared_init() < 0) { printf("problems with shared memory \n"); exit(1); } read_char(); return 0; }

OUTPUT [icsa47@unixserver ~]$ cc ipc.c [icsa47@unixserver ~]$ ./a.out 2 read_key now is 2 [icsa47@unixserver ~]$ ./a.out a read_key now is a

RESULT The program for interprocess communication using shared memory has been executed and shown.

EX.NO:7 DATE: PRODUCER-CONSUMER PROBLEM USING SEMAPHORES

DESCRIPTION This is an illustration of a solution to the classic producer-consumer (bounded-buffer) problem using semaphores. CONCEPT Producers produce items to be stored in the buffer. Consumers remove and consume items which have been stored. Mutual exclusion must be enforced on the buffer itself. Moreover, producers can store only when there is an empty slot, and consumers can remove only when there is a full slot. Three semaphores are used. The binary semaphore mutex controls access to the buffer itself. The counting semaphore empty keeps track of empty slots, and the counting semaphore full keeps track of full slots. In this example, the buffer is implemented as an array of size MAX treated as a circular (ring) buffer. Variables in and out give the index of the next position for putting in and taking out (if any). Variable count gives the number of items in the buffer. EXPECTED OUTPUT AND ITS FORM one or more producers are generating data and placing these in a buffer a single consumer is taking items out of the buffer one at time only one producer or consumer may access the buffer at any one time

ALGORITHM: 1. Start the program. 2. Declare the variables. 3. Declare a structure for semaphore variables. 4. During run time read the number of items to be produced and consumed. 5. Declare and define semaphore function for creation and destroy. 6. Define producer function. 7. Define consumer function. 8. Call producer and consumer function.

9. Stop the execution. PROGRAM #include<stdio.h> #include<stdlib.h> void main() { int value,size=3; int buffer[2]; int in=1,out=1,c,op; do { printf("1.Producer 2.Consumer 3.Exit\n"); printf("Enter your choice"); scanf("%d",&c); switch(c) { case 1: if(((in+1)%size)!=out) { printf("Enter the value"); scanf("%d",&value); buffer[in]=value; printf("%d is the value produced",buffer[in]); in=(in+1)%size; } else printf("\n Buffer is full"); break; case 2: if(in!=out) { value=buffer[out]; out=(out+1)%size; printf("\n%d is consumed",value);

} else printf("\nBuffer is empty"); break; case 3: exit(0); break; } printf("Do you want to continue?(0/1):"); scanf("%d",&op); } while(op==1); } OUTPUT 1.Producer 2.Consumer 3.Exit Enter your choice1 Enter the value100 100 is the value produced Do you want to continue?(0/1):1 1.Producer 2.Consumer 3.Exit Enter your choice2 100 is consumed Do you want to continue?(0/1):0

RESULT The program to implement producer and consumer problem using semaphores has been executed and shown the results as above.

EX.NO:8 DATE: MEMORY MANAGEMENT SCHEMES I FIRST FIT

DESCRIPTION Memory Management Algorithms In an environment that supports dynamic memory allocation, the memory manager must keep a record of the usage of each allocatable block of memory. This record could be kept by using almost any data structure that implements linked lists. An obvious implementation is to define a free list of block descriptors, with each descriport containing a pointer to the next descriptor, a pointer to the block, and the length of the block. The memory manager keeps a free list pointer and inserts entries into the list in some order conducive to its allocation strategy. A number of strategies are used to allocate space to the processes that are competing for memory. First Fit Another strategy is first fit, which simply scans the free list until a large enough hole is found. Despite the name, first-fit is generally better than best-fit because it leads to less fragmentation. Small holes tend to accumulate near the beginning of the free list, making the memory allocator search farther and farther each time.

EXPECTED OUTPUT AND ITS FORM The memory segments are allocated with the memory space using First fit technique. ALGORITHM: 1. Start the program 2. Declare a structure which contains starting address,ending address and size of the free blocks. 3. Get the number of available free blocks from the user. 4. Get the process name and its size. 5. Get the starting address and ending address of the free blocks,calculate the size by subracting

starting adress from ending address. 6. Allocate the given process in the free block using the first fit and display block number. 7. Stop the program PROGRAM #include<stdio.h> main() { struct sss { int st,en,fr; } p[10]; int c,s,i,n; char pid[10]; printf("Enter the number of free blocks"); scanf("%d",&n); printf("Enter the process name and size"); scanf("%s%d",pid,&s); printf("Enter the st and end address of free block"); for(i=0;i<n;i++) { scanf("%d%d",p[i].st,&p[i].en); p[i].fr=p[i].en-p[i].st; } for(i=0;i<n;i++) { if(p[i].fr>=s) { printf("Process %s is allocated in fb %d to %d",pid,p[i].st,p[i].en); c=1; break; } }

if(c==0) printf("Free blockis not available"); } OUTPUT Enter the number of free blocks2 Enter the process name and sizes 50 Enter the st and end address of free block100 200 200 300 Process s is allocated in fb 100 to 200

RESULT The program for first fit algorithm for memory management has been executed and shown the results as above.

EX.NO:9 DATE:

MEMORY MANAGEMENT SCHEMES II BEST FIT

DESCRIPTION Memory Management Algorithms In an environment that supports dynamic memory allocation, the memory manager must keep a record of the usage of each allocatable block of memory. This record could be kept by using almost any data structure that implements linked lists. An obvious implementation is to define a free list of block descriptors, with each descriport containing a pointer to the next descriptor, a pointer to the block, and the length of the block. The memory manager keeps a free list pointer and inserts entries into the list in some order conducive to its allocation strategy. A number of strategies are used to allocate space to the processes that are competing for memory. Best Fit The allocator places a process in the smallest block of unallocated memory in which it will fit. It requires an expensive search of the entire free list to find the best hole. More importantly, it leads to the creation of lots of little holes that are not big enough to satisfy any requests. This situation is called fragmentation, and is a problem for all memory-management strategies, although it is ALGORITHM 1. Start the program 2. Declare structure which contains starting address,ending address and size of free blocks. 3. Get the number of available free blocks from the user. 4. Get the process name and its size. 5. Get the starting address and ending addressof free blocks,calculate the size by subracting starting address from ending address. 6. Sort the free blocks using its size. 7. Allocate the process using best fit allocation methods. 8. Display the blocks number in which the given process is allocated 9. Stop the program

PROGRAM #include<stdio.h> #include<string.h> main() { struct sss { char pn[10]; int st,en,fr; }p[10]; int c=0,s,i,n,t,j; char pid[10],t1[10]; printf("\nEnter the no. of free blocks:"); scanf("%d", &n); printf("\nEnter the process name and size:"); scanf("%s%d",pid,&s); printf("Enter the process name with start and end address of free blocks:"); for(i=0;i<n;i++) { scanf("%s%d%d",&p[i].pn,&p[i].st,&p[i].en); p[i].fr=p[i].en-p[i].st; } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(p[i].fr>p[j].fr) { t=p[i].fr; p[i].fr=p[j].fr; p[j].fr=t; strcpy(t1,p[i].pn); strcpy(p[i].pn,p[j].pn);

strcpy(p[j].pn,t1); } } } for(i=0;i<n;i++) { if(p[i].fr>=s) { printf("Process %s is allocated in %s",pid,p[i].pn); c=1; break; } } } OUTPUT Enter the no. of free blocks:3 Enter the process name and size:s 50 Enter the process name with start and end address of free blocks:fb1 100 fb2 200 fb3 300 fb4 500 Process s is allocated in fb2

RESULT The program for best fit algorithm for memory management has been executed and shown the results as above.

EX.NO:10 FILE ALLOCATION TECHNIQUE-CONTIGUOUS DATE:

DESCRIPTION File Allocation Methods One main problem in file management is how to allocate space for files so that disk space is utilized effectively and files can be accessed quickly. Three major methods of allocating disk space are: * Contiguous Allocation * Linked Allocation * Indexed Allocation. Each method has its advantages and disadvantages. Accordingly, some systems support all three (e.g. Data General's RDOS). More commonly, a system will use one particular method for all files. Contiguous File Allocation Each file occupies a set of contiguous block on the disk Allocation using first fit/best fit. A need for compaction Only starting block and length of file in blocks are needed to work with the file Allows random access Problems with files that grow EXPECTED OUTPUT AND ITS FORM Allocates blocks of memory for files using file allocation techniques. ALGORITHM: 1. Start the program 2. Declare the variable method. 3. Get the number of free blocks and data blocks.

4. Input a data by using for loop. 5. Display the starting address and length of the data. 6. Stop the program

PROGRAM #include<stdio.h> int main() { int i,n,a[20],d,l[10],m[10],data[10],p[10]; printf("\nEnter the number of free blocks available:"); scanf("%d",&n); printf("\nEnter the number of data to be stored:"); scanf("%d",&d); while(n>0) { for(i=0;i<d;i++) { if(n>0) { printf("\nEnter the starting address of the contiguos block:"); scanf("%d",&a[i]); printf("Enter the length="); scanf("%d",&l[i]); n=n-l[i]; p[i]=n; if(n>=0) { printf("\nEnter the data"); scanf("%d",&data[i]); } else { printf("\n!out of space!\n\n");

} } } } if(n==0) printf("\n!Cylinder block is completely occupied!\n\n"); printf("\nStarting address \tlength\t data"); for(i=0;i<d;i++) { printf("\n\t%d\t\t%d\t\t%d\n)",a[i],l[i],data[i]); } return 0; }

OUTPUT Enter the number of free blocks available:4 Enter the number of data to be stored:2 Enter the starting address of the contiguos block:3 Enter the length=1 Enter the data2 Enter the starting address of the contiguos block:5 Enter the length=2 Enter the data45 Enter the starting address of the contiguos block:2 Enter the length=3 !out of space! Starting address 2 5 length 3 2 data 2 45

RESULT The program for file allocation technique has been executed and shown the results as above.

You might also like