Top Banner
RAJA COLLEGE OF ENGINEERING & TECHNOLOGY Department of Computer Science & Engineering OS LAB MANUAL LIST OF EXERCISES Exercise 01: Study of UNIX Commands Exercise 02: Shell Script Programs Exercise 03: FCFS Scheduling and SJF Scheduling Exercise 04: Priority Scheduling and Round Robin Scheduling Exercise 05: Producer Consumer Problem Exercise 06: Inter process communication using shared memory Exercise 07: Memory Management Technique I - First fit, Best fit, Worst fit. Exercise 08: Memory Management Technique II - FIFO , LRU page replacement. Exercise 09: Contiguous Memory Allocation. Exercise 10: Study of Unix Basic and I/O System Calls Prepared by S.J.Subashini & G.D.Kesavan
60

CS047-OS Lab Manual.

Oct 20, 2015

Download

Documents

operating system lab manual
Welcome message from author
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
Page 1: CS047-OS Lab Manual.

RAJA COLLEGE OF ENGINEERING & TECHNOLOGY

Department of Computer Science & Engineering

OS LAB MANUAL

LIST OF EXERCISES

Exercise 01: Study of UNIX Commands

Exercise 02: Shell Script Programs

Exercise 03: FCFS Scheduling and SJF Scheduling

Exercise 04: Priority Scheduling and Round Robin Scheduling

Exercise 05: Producer Consumer Problem

Exercise 06: Inter process communication using shared memory

Exercise 07: Memory Management Technique I - First fit, Best fit, Worst fit.

Exercise 08: Memory Management Technique II - FIFO , LRU page replacement.

Exercise 09: Contiguous Memory Allocation.

Exercise 10: Study of Unix Basic and I/O System Calls

Prepared by S.J.Subashini & G.D.Kesavan

Page 2: CS047-OS Lab Manual.

CODE:CS 047 OPERATING SYSTEMS LAB MANUAL CSE & IT

(Implement the following on LINUX or other Unix like platform. Use C for high level language Implementation)

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 some Memory management schemes like Paging and Segmentation.

9. Implement some Memory management schemes like FIRST FIT, BEST FIT & WORST FIT.

10. Implement any file allocation techniques(Contiguous, Linked or Indexed) Example for exercises 8 & 9

Free space is maintained as a linked list of nodes with each node having the starting byte address and the ending byte address of a free block. Each memory request consists of the process-id and the amount of storage space required in bytes. Allocated memory space is again maintained as a linked list of nodes with each node having the process-id, starting byte address and the ending byte address of the allocated space. When a process finishes (taken as input) the appropriate node from the allocated list should be deleted and this free space should be added to the free space list (care should be taken to merge contiguous free blocks into one single block. This results in deleting more than one node from the from the free space list and changing the start and end address in the appropriate node). For allocation use first fit, worst fit and best fit. Total: 45 Hrs

Prepared by S.J.Subashini & G.D.Kesavan

Page 3: CS047-OS Lab Manual.

Exercise 1: Study of UNIX Commands

Aim: To study and execute the basic commands in Unix OS installed along with Linux.

Algorithm: a) The Unix system is logged in through the IP address 192.168.0.100 from

Start->Run.b) The user enters the user login name as ‘student’ and Password as ‘student’.c) The system displays the current directory as student(Common Directory for all user logging in as student)d) Each command is entered as mentioned in syntax and output for each command is noted down.e) Any number of files or directories are created during command execution.f) The session is ended using exit command ‘exit’.

Commands:

1. TASK : To display the system date and time. COMMAND : date. SYNTAX : date. EXPLANATION : This command displays the current system date and time on the screen.

OUTPUT : Tue Jun 19 11:37:17 GMT 2007.

2. TASK : To display the current month. COMMAND : date. SYNTAX : date +%m. EXPLANATION : This command displays the current month on the screen. OUTPUT : 06.

3. TASK : To display the name of the current month. COMMAND : date. SYNTAX : date +%h. EXPLANATION : This command displays the name of the current month on the screen. OUTPUT : Jun.

4. TASK : To display the current system date. COMMAND : date. SYNTAX : date +%d. EXPLANATION : This command displays the current system date on the screen. OUTPUT : 19.

5. TASK : To display the current system date (year). COMMAND : date. SYNTAX : date +%y.

Prepared by S.J.Subashini & G.D.Kesavan

Page 4: CS047-OS Lab Manual.

EXPLANATION : This command displays the current year on the screen. OUTPUT : 07.

6. TASK : To display the current system time. COMMAND : date. SYNTAX : date +%H. EXPLANATION : This command displays the current system time (in hours) on the screen. OUTPUT : 11.

7. TASK : To display the current system time. COMMAND : date. SYNTAX : date +%M. EXPLANATION : This command displays the current system time (in minutes) on the screen. OUTPUT : 43.

8. TASK : To display the current system time. COMMAND : date. SYNTAX : date +%S. EXPLANATION : This command displays the current system time (in seconds) on the screen. OUTPUT : 15.

9. TASK : To display the calendar of the current month. COMMAND : calendar. SYNTAX : cal. EXPLANATION : This command displays the calendar of the current month on the screen. OUTPUT : Jun 07

S M T W T F S1 2

3 4 5 6 7 8 910 11 12 13 14 15 1617 18 19 20 21 22 2324 25 26 27 28 29 30

10. TASK : To display user-defined message. COMMAND : echo. SYNTAX : echo “message”. EXPLANATION : This command displays on the screen the argument of the echo command. OUTPUT : echo “OS”.

OS

Prepared by S.J.Subashini & G.D.Kesavan

Page 5: CS047-OS Lab Manual.

11. TASK : To display the details of all users. COMMAND : who. SYNTAX : who. EXPLANATION : This command lists the information about all the users who have logged on to that system. OUTPUT : displays all logged in user.

12. TASK : To display the user detail. COMMAND : who. SYNTAX : whoami. EXPLANATION : This command displays information about the current user of the system on the screen. OUTPUT : root.

13. TASK : To create a directory. COMMAND : make directory. SYNTAX : mkdir. EXPLANATION : This command is used to create a new directory with the specified name. EXAMPLE : mkdir student. OUTPUT : The directory “student” is created.

14. TASK : To change directory. COMMAND : change directory. SYNTAX : cd directory name. EXPLANATION : This command is used to switch from one directory to another. EXAMPLE : cd staff. OUTPUT : The directory “staff” is switched onto.

15. TASK : To delete a directory. COMMAND : remove directory. SYNTAX : rmdir directory name EXPLANATION : This command is used to delete the specified directory. EXAMPLE : rmdir student. OUTPUT : The “student” directory is deleted.

16. TASK : To come out of a sub-directory. COMMAND : change directory. SYNTAX : cd .. EXPLANATION : This command helps in switching to the main directory. OUTPUT : The user comes out of the directory

17. TASK : To list all the files and directories. COMMAND : list. SYNTAX : ls. EXPLANATION : This command displays all the files and directories of the system.

Prepared by S.J.Subashini & G.D.Kesavan

Page 6: CS047-OS Lab Manual.

OUTPUT : List all the directory contents

18. TASK : To create a file. COMMAND : cat. SYNTAX : cat> file name. EXPLANATION : This command leads to the creation of a new file with the specified file name and contents. EXAMPLE : cat> wind. OUTPUT : A null file called “wind” is created.

19. TASK : To view a file. COMMAND : cat. SYNTAX : cat file name. EXPLANATION : This command displays the contents of the specified file. EXAMPLE : cat wind. OUTPUT : Contents of the file called “wind” will be displayed on the screen.

20. TASK : To copy a file. COMMAND : copy. SYNTAX : cp sourcefile destinationfile. EXPLANATION : This command produces a copy of the source file and is stored in the specified destination file by overwriting its previous contents. EXAMPLE : cp sun moon. OUTPUT : The contents of “sun” file will be copied to the “moon” file.

21. TASK : To move a file. COMMAND : move. SYNTAX : mv sourcefile destinationfile. EXPLANATION : After moving the contents of the source file into destination file, the source file is deleted. EXAMPLE : mv sun moon. OUTPUT : After copying contents from the “sun” file to “moon” file, the “sun” file is deleted. 22. TASK : To display / cut a column from a file. COMMAND : cut. SYNTAX : cut –c no. file name. EXPLANATION : This command displays the characters of a particular column in the specified file. EXAMPLE : cut –c3 moon. OUTPUT : Those characters occurring in the 3rd column of the file called “moon” are displayed.

23. TASK : To delete a file. COMMAND : remove.

Prepared by S.J.Subashini & G.D.Kesavan

Page 7: CS047-OS Lab Manual.

SYNTAX : rm file name. EXPLANATION : This command deletes the specified file from the directory. EXAMPLE : rm sun. OUTPUT : The file called “sun” will be deleted.

24. TASK : To retrieve a part of a file. COMMAND : head. SYNTAX : head -no. of rows file name. EXPLANATION : This command displays the specified no. of rows form the top of the specified file. EXAMPLE : head -1 sun. OUTPUT : The first row of the file called “sun” is displayed.

25. TASK : To retrieve a file. COMMAND : tail. SYNTAX : tail -no. of rows file name. EXPLANATION : This command displays the specified no. of rows form the bottom of the specified file. EXAMPLE : tail -1 moon. OUTPUT : The last row of the file called “moon” is displayed.

26. TASK : To sort the contents of a file. COMMAND : sort. SYNTAX : sort file name. EXPLANATION : This command helps in sorting the contents of a file in ascending order. EXAMPLE : sort win. OUTPUT : The contents of the file “win” are displayed on the screen in a sorted order.

27. TASK : To display the no. of characters in a file. COMMAND : word count. SYNTAX : wc file name. EXPLANATION : This command displays on the screen the no. of rows, words, and the sum of no. of characters and words. EXAMPLE : wc ball. OUTPUT : The no. of rows, words, and no. of characters present in the file

“ball” are displayed.

28. TASK : To display the calendar of a year. COMMAND : cal. SYNTAX : cal year. EXPLANATION : This command displays on the screen the calendar of the specified

year. EXAMPLE : cal 2007. OUTPUT : The calendar of the year 2007 will be displayed.

Prepared by S.J.Subashini & G.D.Kesavan

Page 8: CS047-OS Lab Manual.

29. TASK : To find the specified file. COMMAND : find SYNTAX : find filename. EXPLANATION : This command is used to find the specified file. EXAMPLE : find rose. OUTPUT :.The file is found message will be displayed.

30. TASK : To display the given message as banner. COMMAND : banner SYNTAX : banner format EXPLANATION : The command is used to display the message in banner format. EXAMPLE : banner Welcome to CSE OUTPUT :.The message Welcome to CSE will be displayed in banner format.

31. TASK : To Append two files COMMAND : cat SYNTAX : cat oldfilename >> newfilename EXPLANATION : The command is used to append one file to another. EXAMPLE : cat pink >> orange OUTPUT :.The contents pink(source) is appended to orange(destination)

32. TASK : To find current working directory. COMMAND : pwd SYNTAX : pwd EXPLANATION : The command is used to display the full pathname of current directory. EXAMPLE : pwd OUTPUT :.home/student/kesav

33. TASK : To flush the screen COMMAND : clear SYNTAX : clear EXPLANATION : The command is used to clear the screen. EXAMPLE : clear OUTPUT :.screen gets emptied.

34. TASK : Paste the contents from one file to another. COMMAND : paste SYNTAX : paste filename1 filename2 EXPLANATION : The command is used to paste the contents of a file vertically. EXAMPLE : paste rose lilly OUTPUT :.Contents of rose(source) is pasted into lilly(destination)

35. TASK : To find occurance of a string in a file COMMAND : grep SYNTAX : grep string filename

Prepared by S.J.Subashini & G.D.Kesavan

Page 9: CS047-OS Lab Manual.

EXPLANATION : The command is used to find the specified string within the file. EXAMPLE : grep CSE kesav OUTPUT :.The string CSE is matched from the file kesav.

36. TASK : To find occurance of a string in current lines in a file COMMAND : grep SYNTAX : grep_c string filename EXPLANATION : The command is used to find current lines that matches string pattern specified. EXAMPLE : grep_c Indian kesav OUTPUT :. The string Indian is matched from the file kesav.

37. TASK : Inputting values from user COMMAND : read SYNTAX : read variablename EXPLANATION : The command is used to get input to a variable EXAMPLE : read a OUTPUT :.Gets the user supplied value and stores in specified variable.

38. TASK : To join two common fields of files COMMAND : join SYNTAX : join filename1 filename2 EXPLANATION : The command is used to extract common fields between files and join them. EXAMPLE : join kesav kannan OUTPUT :.the common fields from kesav and kannan files are joined.

39. TASK : To compare lines in a file COMMAND : uniq SYNTAX : uniq[c/d/u] filename EXPLANATION : The command is used to compare adjacent lines in a file EXAMPLE : uniq xx OUTPUT :.Sun arises in the east is the unique line in the file

40. TASK : To match string with a postfix COMMAND : grep SYNTAX : grep pattern$ filename EXPLANATION : The command is used to EXAMPLE : grep apple$ fruits OUTPUT :.pineapple

41. TASK : To match string with a prefix COMMAND : grep SYNTAX : grep ^ parrern filename EXPLANATION : The command is used to display the line that matches pattern in prefix.

Prepared by S.J.Subashini & G.D.Kesavan

Page 10: CS047-OS Lab Manual.

EXAMPLE : grep ^pome fruits OUTPUT :.pomegranate

42. TASK : To compare two files to find differences COMMAND : cmp SYNTAX : cmp filename1 filename2 EXPLANATION : The command is used to compare two files. EXAMPLE : cmp xx yy OUTPUT :. generates the first difference between the two files, xx and yy.

43. TASK : To configure protection COMMAND : chmod SYNTAX : chmod EXPLANATION : The command is used to alter the access permissions. EXAMPLE : chmod OUTPUT :.Access permission gets altered.

44. TASK : To display month from calender COMMAND : cal SYNTAX : cal m [year] EXPLANATION : The command is used to display calendar of specified month EXAMPLE : cal 6 2007 OUTPUT :. Jun 07

S M T W T F S1 2

3 4 5 6 7 8 910 11 12 13 14 15 1617 18 19 20 21 22 2324 25 26 27 28 29 30

45. TASK : To display contents of directory COMMAND : ll SYNTAX : ll EXPLANATION : The command is used to list all the files in long list format EXAMPLE : ll OUTPUT :.The contents of the directory is displayed

Result: The Basic Unix commands is executed in Linux.------------------------------------------------------------------------------------------------------------

Prepared by S.J.Subashini & G.D.Kesavan

Page 11: CS047-OS Lab Manual.

Exercise 2: Shell Script Programs

a) Sum of N numbers using while loop

Aim: To write a shell script program for finding the sum of n numbers using while loop.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Read the range of numbers to be added from user.c) Find the sum using while iterative structure and display the result.d) Terminate the program.

Program:echo “Enter n”read nsum =0i=0while [ $i –le $n ]dosum=`expr $sum + $i`i=`expr $i + 1`doneecho “Sum of $n number is $sum”

Result: Thus sum of n numbers is computed using while iteration.

b) Sum of N numbers using for loop

Aim: To write a shell script program for finding the sum of n numbers using for loop.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Read the range of numbers to be added from user.c) Find the sum using for iterative structure and display the result.d) Terminate the program.

Program:echo “Enter n”read nsum =0i=0for i in `seq 1 $n`dosum=`expr $sum + $i`

Prepared by S.J.Subashini & G.D.Kesavan

Page 12: CS047-OS Lab Manual.

i=`expr $i + 1`doneecho “Sum of $n number is $sum”

Result: Thus sum of n numbers is computed using for iteration.

c) Sum of N numbers using until loop

Aim: To write a shell script program for finding the sum of n numbers using until loop.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Read the range of numbers to be added from user.c) Find the sum using until iterative structure and display the result.d) Terminate the program.

Program:echo “Enter n”read nsum =0i=0until [ $n –le $i ]dosum=`expr $sum + $i`i=`expr $i + 1`doneecho “Sum of $n number is $sum”

Result: Thus sum of n numbers is computed using until iteration.

d) Factorial of N numbers

Aim: To write a shell script program for finding the factorial of n numbers.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Read the value of n from user till which factorial is computed.c) Find the factorial using for loop structure and display the result.d) Terminate the program.

Program:fact =1j=1echo”Enter the number”

Prepared by S.J.Subashini & G.D.Kesavan

Page 13: CS047-OS Lab Manual.

read nwhile [ $j –le $n ]do fact=`expr $i \* $fact` j=`expr $j + 1`doneecho “The factorial of $n is $fact”

Result: Thus factorial for n numbers is computed using shell script.

e) Fibonacii Sequence

Aim: To write a shell script program for print the fibonacii Sequence.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Read the number, n, from user, that number of sequence generated.c) Display the sequence using while iteration.d) Terminate the program.

Program:echo “Enter the limit”read nc=0a=0b=1echo “The Fibonacii Series is”echo “$a”echo “$b”i=3while [ $i –le $n ]do

c=`expr $a + $b` a=$b

b=$c echo “$c” i=`expr $i + 1`

done

Result: Thus fibonacii sequence is printed using shell script.

f) Student Mark list

Aim: To write a shell script program for computing Student Mark list.

Algorithm:

Prepared by S.J.Subashini & G.D.Kesavan

Page 14: CS047-OS Lab Manual.

a) Open the editor in Insert mode using esc + i and start the program.b) Read the values for variables student, name, m1, m2 and m3 from user.c) Calculate the total and average and display the result.d) Terminate the program.

Program:echo “ Enter number of the Student”read ni=1t=1while [ $i –lt $n ]do echo “Enter a Student name” read name echo “Enter the Student register number” read rollno j=1 tot=0 while [ $j –le 2 ] do echo “Enter the mark $j” read s tot =`expr $tot + $s` j=`expr $j + 1` done echo “Name: $name” echo “Register Number: $rollno” echo “Total: $tot” avg=`expr $tot/2` echo “Average: $avg” i=`expr $i + 1`

done

Result: Thus student mark list is computed using shell script.

g) Menu driven program

Aim: To write a shell script program for implementing Menu driven options.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Display the choices to the user.c) Input the choice through variable n from user.d) Use Case conditional branching instruction, to branch to the exact

choice.e) Display the result respective to the choice chosen.

Prepared by S.J.Subashini & G.D.Kesavan

Page 15: CS047-OS Lab Manual.

f) Terminate the program.

Program:echo “Enter your Choice”echo “1.Date 2.Working Directory 3.Logged Users 4.Current User”echo “5.Copy File 6.Move File 7.Head & Tail 8.Pattern Matching”read ncase $n in 1)date;; 2)pwd;; 3)who;; 4)who am i;; 5) echo “Enter the Source File Name” read a echo “Enter the Destination File Name” read b cp $a $b echo “$a File is copied to $b File” ;; 6) echo “Enter the Source File Name” read a echo “Enter the Destination File Name” read b mv $a $b echo “$a File is copied to $b File” ;; 7) echo “Enter the File Name” read a echo “Head” head -1 $a echo “Tail” tail -2 $a ;; 8) echo “Enter the File Name” read a echo “Enter the Matching String” read b echo “The Matched String is” grep “$b” $a ;;esac

Result: Thus menu driven option is implemented using shell script.

h) Armstrong numbers

Prepared by S.J.Subashini & G.D.Kesavan

Page 16: CS047-OS Lab Manual.

Aim: To write a shell script program for checking for Armstrong numbers.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Read the value of n from user, which must be validated for Armstrong.c) Sum the segregated cube of individual digits of n from least significant

digit using while iterative structure.d) Check the sum with user entered number.e) If same display ‘Armstrong’ else display ‘Not Armstrong’.f) Terminate the program.

Program:echo “Enter then number”read nb=$ns=0while [ $n –gt 0 ]do

a=`expr $n % 10` s=`expr $s + $a \* $a \* $a` n=`expr $n / 10`

doneif [ $s –eq $b ]then

echo “The $b is Armstrong Number”else

echo “The $b is not Armstrong Number”fi;

Result: Thus armstrong number checking is implemented using shell script.

i) Prime numbers

Aim: To write a shell script program for checking for prime numbers.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Input range from user, till which count of prime numbers displayed.c) Check for Divisibility within the range.d) Divisibility is determined if remainder is zero. e) If not divisible then count is incremented. f) Display the count to the user.g) Terminate the program.

Program:echo “Enter the value for n ”

Prepared by S.J.Subashini & G.D.Kesavan

Page 17: CS047-OS Lab Manual.

read ni=2flag=0x=`expr $n/2`while [ $i –le $x ]do if [ `expr $n % $i` -eq 0 ] then flag=1

fi i=`expr $i + 1`

doneif [ $flag –eq 0 ]then echo “The $n number is prime Number”else echo “The $n number is not a prime Number”fi;

Result: Thus prime number checking is implemented using shell script.

j) Reverse the string

Aim: To write a shell script program for reversing a given string.

Algorithm:a) Open the editor in Insert mode using esc + i and start the program.b) Input the string from user.c) Find the length of the string by traversing the string till last character.d) Segregate individual characters, using cut function, starting from end

of the string.e) Add the splitted characters one by one to an empty string. f) Display the reversed string to user.g) Terminate the program.

Program:echo “Enter the String”read sl=`expr $s \wc –c`echo “$l”while [ $l –ne 0 ]do ch =`expr $s \cut –c $l` echo “$ch” rev=`expr $rev $ch` l=`expr $l – 1`

Prepared by S.J.Subashini & G.D.Kesavan

Page 18: CS047-OS Lab Manual.

doneecho “The Reversed String is: $rev”

Result: Thus reversing the string is implemented using shell script.------------------------------------------------------------------------------------------------------------

Exercise 3: FCFS Scheduling and SJF Scheduling

a) First Come First Served Scheduling

Aim: To write a program for First Come First Served CPU Scheduling algorithm.

Algorithm:a) Create array structures to store process name, waiting time, turn around time and burst time.b) Get the number of jobs, process name and burst time from user.c) Initialize time factors as zero.d) Calculate waiting time, turn around time for each process.e) Average waiting time, Average turn around time is also computed and display to the user.

Program:#include<stdio.h>#include<conio.h>void main(){ float aw,at; int b[10],I,w[10],t[10],wt,tt,n; printf(“Enter the number of process within 10:”); scanf(“%d”,&n); for(i=1;i<=n;i++) { printf(“Enter the burst time for the process %d”,i); scanf(%d”,&b[i]); } wt=0; tt=0; t[10]=0; printf(“\n Process no \t Burst time \t Waiting time \t Turn around time”); for(i=1;i<=n;i++) { w[i] =t[i-1]; t[i]=w[i]+b[i];

Prepared by S.J.Subashini & G.D.Kesavan

Page 19: CS047-OS Lab Manual.

wt=wt+w[i]; tt=tt+t[i]; printf(“\n%d\t\t%d\t\t%d\t\t%d\n”,i,b[i],w[i],t[i]); } aw=wt/n; at=tt/n; printf(“Average Waiting Time =%f \n Average Turn Around Time =%f”,aw,at); getch();}

Result: Thus the inputted process are scheduled using FCFS algorithm.

b) Shortest Job First Scheduling

Aim: To write a program for Shortest Job First CPU Scheduling algorithm.

Algorithm:a) Create array structures to store process name, waiting time, turn around time and burst time.b) Get the number of jobs, process name and burst time from user.c) Initialize time factors as zero.d) Sort the burst time in ascending order.e) Calculate waiting time, turn around time for each process.f) Average waiting time, Average turn around time is also computed and display to the user.

Program:#include<stdio.h>#include<conio.h>void main(){ float aw,at; int b[10],i,w[10],t[10],wt,tt,n,tp,tb,a[10],j; printf(“Enter the number of process within 10:”); scanf(“%d”,&n); for(i=1;i<=n;i++) { a[i]=i; printf(“Enter the burst time for the process %d”,i); scanf(%d”,&b[i]); } wt=0; tt=0; t[10]=0;

Prepared by S.J.Subashini & G.D.Kesavan

Page 20: CS047-OS Lab Manual.

for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { if(b[i]>b[j]) { tb=b[i]; b[i]=b[j]; b[j]=tb; tp=a[i]; a[i]=a[j]; a[j]=tp; }

}}

printf(“\n Process no \t Burst time \t Waiting time \t Turn around time”); for(i=1;i<=n;i++) { w[i] =t[i-1]; t[i]=w[i]+b[i]; wt=wt+w[i]; tt=tt+t[i]; printf(“\n%d\t\t%d\t\t%d\t\t%d\n”,i,b[i],w[i],t[i]); } aw=wt/n; at=tt/n; printf(“Average Waiting Time =%f \n Average Turn Around Time =%f”,aw,at); getch();}

Result: Thus the inputted process are scheduled using SJF algorithm.------------------------------------------------------------------------------------------------------------Exercise 4: Priority Scheduling and Round Robin Scheduling

a) Priority Scheduling

Aim: To write a program for Priority CPU Scheduling algorithm.

Algorithm:a) Create array structures to store process name, waiting time, turn around time and burst time.b) Get the number of jobs, process name and burst time from user.c) Initialize time factors as zero.d) Sort the burst time in ascending order based on priority number.

Prepared by S.J.Subashini & G.D.Kesavan

Page 21: CS047-OS Lab Manual.

e) Calculate waiting time, turn around time for each process.f) Average waiting time, Average turn around time is also computed and display to the user.

Program:#include<stdio.h>#include<conio.h>void main(){ float aw,at; int b[10],i,w[10],t[10],wt,tt,n,tp,tb,a[10],j,p[10]; printf(“Enter the number of process within 10:”); scanf(“%d”,&n); for(i=1;i<=n;i++) { a[i]=i; printf(“Enter the Burst time for the process %d”,i); scanf(%d”,&b[i]); printf(“Enter the Priority for the process %d”,i); scanf(%d”,&p[i]); } wt=0; tt=0; t[10]=0; for(i=1;i<=n;i++) { for(j=i+1;j<=n;j++) { if(p[i]>p[j]) { tb=b[i]; b[i]=b[j]; b[j]=tb; tp=a[i]; a[i]=a[j]; a[j]=tp; }

}}

printf(“\n Process no \t Burst time \t Waiting time \t Turn around time”); for(i=1;i<=n;i++) { w[i] =t[i-1]; t[i]=w[i]+b[i]; wt=wt+w[i];

Prepared by S.J.Subashini & G.D.Kesavan

Page 22: CS047-OS Lab Manual.

tt=tt+t[i]; printf(“\n%d\t\t%d\t\t%d\t\t%d\n”,i,b[i],w[i],t[i]); } aw=wt/n; at=tt/n; printf(“Average Waiting Time =%f \n Average Turn Around Time =%f”,aw,at); getch();}

Result: Thus the inputted process are scheduled using Priority algorithm.

b) Round Robin Scheduling

Aim: To write a program for Round Robin CPU Scheduling algorithm.

Algorithm:a) Create a structure to store process name, waiting time, turn around time and burst time of individual process.b) Get the number of jobs, time slice, process name and burst time from user.c) If the process has burst time less than time quantum then schedule the process and move to next process.d) If the process has burst time greater than time quantum then schedule the process till time quantum and move to next process.e) Initialize time factors as zero.f) Calculate waiting time, turn around time for each process.g) Average waiting time, Average turn around time is also computed and display to the user.

Program:#include<stdio.h>#include<conio.h>struct rr{ char pname[30]; int wt,bt,tt,rbt,lt,flag;}rr[60];float at,aw,s1=0,s2=0;int i,n1=0,n=0,x=0,tq;

void get(){ printf(“\nEnter the total number of jobs”); scanf(“%d”,&n); printf(“\nEnter the time Quantum for Round Robin Scheduling”);

Prepared by S.J.Subashini & G.D.Kesavan

Page 23: CS047-OS Lab Manual.

scanf(“%d”,&tq); for(i=1;i<=n;i++) { printf(”\n Enter the process name:”); scanf(“%d”,&rr[i].pname); printf(“\n Enter the burst time:”); scanf(“%d”,&rr[i].bt); rr[i].rbt=rr[i].bt; rr[i].flag=rr[i].lt=0; }

}

void process(){ while(n1!=n) { for(i=1;i<=n;i++) { if(rr[i].flag!=1) { if(rr[i].rbt>=tq) { rr[i].rbt=rr[i].rbt-tq; x=x+tq; } else { x=x+rr[i].rbt; rr[i].rbt=rr[i].rbt-tq; } if(rr[i].rbt<1) { rr[i].flag=1; n1++; } rr[i].tt=x; } } } for(i=1;i<=n;i++) { rr[i].wt=rr[i].tt-rr[i].bt; rr[i].tt=rr[i].wt+rr[i].bt; s1=s1+rr[i].wt; s2=s2+rr[i].tt; }

Prepared by S.J.Subashini & G.D.Kesavan

Page 24: CS047-OS Lab Manual.

aw=s1/n; at=s2/n;}

void display(){ for(i=1;i<=n;i++) { printf(“%s\t%d\t\t%d\t\t%d”,rr[i].pname,rr[i].bt,rr[i].wt,rr[i].tt); printf(“\n Average Waiting Time =%f”,aw); printf(“\n Average Turn Around Time =%f”,at); }}

void main(){ clrscr(); get(); process(); disp(); getch();}

Result: Thus the inputted process are scheduled using Round Robin algorithm.

------------------------------------------------------------------------------------------------------------Exercise 5: Producer Consumer Problem

Aim: To implement the Producer-Consumer Problem using Semaphores.

Algorithm: a) Typedef a variable “sum” as integer and implement up and down function which simulate signal and wait procedure.

b) A buffer variable for producer and consumer are written.c) In producer, buffer full condition is checked and if it is full then it is displayed.d) In consumer, buffer empty condition is checked and a message is displayed.e) Both the producer() and consumer() program produces are randomly from main().f) The produce() and Consumer() produces messages are displayed till the user quits the program.

Program:#include<stdio.h>

Prepared by S.J.Subashini & G.D.Kesavan

Page 25: CS047-OS Lab Manual.

#include<conio.h>#include<time.h>

#define MAX 3

typedef int sem;sem buffer=0;int num=1;

int up(sem* s){ if(*s>=MAX) return -1; *s=*s+1; return 0;}

int down(sem* s){ if(*s<=0) return -1; *s=*s-1; return 0;}

void producer(){ if(up(&buffer)==-1) { printf(“\nBuffer Full. Producer Waiting!!!”); return; } printf(“\nProduced %d”,num++); return;}

void consumer(){ if(down(&buffer)==-1) { printf(“\nBuffer Empty. Consumer Waiting!!!”); return; } printf(“\nConsumed%d”,Num-(buffer+1)); return}

Prepared by S.J.Subashini & G.D.Kesavan

Page 26: CS047-OS Lab Manual.

int main(){ int i,a=0,j; srand((unsigned)time(0)); while(1) { if(rand()%10>=5) producer(); else consumer(); for(i=1;i<=990000;i++) { a=0; a++; a--; a=i/150; } for(j=1;j<=100;j++) { for(i=1;i<=990000;i++) { a=0; a++; a--; a=i/150; } } } return 0;}

Result: Thus Producer-Consumer Problem is implemented using Semaphores.------------------------------------------------------------------------------------------------------------Exercise 6: Inter Process Communication Using Shared Memory

Aim: To write a program to implement a shared memory

Algorithm:a) Start the processb) Declare the size and data variablesc) Get the number of processes to be insertedd) Get the valuee) Start and identify the process with process idf) Make a common function to communicate with each process running ing) shared memory

Prepared by S.J.Subashini & G.D.Kesavan

Page 27: CS047-OS Lab Manual.

h) Make the variables and arguments to be a global while in communicationi) Write a separate routine for creating memory delete memory in separate regionj) Give permission that a process can kill shared memoryk) Display the valuesl) Stop the process

Program:#include<sys/types.h>#include<sys/shm.h>#include<sys/ipc.h>main(){int shmid;key_t key=0x10;shmid=shmget(key,100,IPC_CREAT|0666);if( shmid < 0 ) printf("\nFirst SHMID failed\n");else printf("\nFirst SHMID Succeded id=%d \n",shmid);

shmid=shmget(key,101,IPC_CREAT|0666);if(shmid<0) printf("\nSecond SHMID failed\n");else printf("\nSecond SHMID Succeded id=%d \n",shmid);

shmid=shmget(key,90,IPC_CREAT|0666);if(shmid<0) printf("\nThird SHMID failed\n");else printf("\n Third SHMID Succeded id=%d \n",shmid);}

Result: The program for interprocess communication using shared memory was implemented and hence verified.

------------------------------------------------------------------------------------------------------------Exercise 7: Memory Management Technique I using First, Best, Worst fit.

a) First fit Algorithm

Aim: To write a program to implement First fit page replacement algorithm

Algorithm:a) Start the processb) Declare the sizec) Get the number of processes to be insertedd) Allocate the first hole that is big enough searching

Prepared by S.J.Subashini & G.D.Kesavan

Page 28: CS047-OS Lab Manual.

e) Start at the beginning of the set of holes f) If not start at the hole that is sharing the pervious first fit search end g) Compare the hole h) if large enough then stop searching in the procedure i) Display the valuesj) Stop the process

Program:#include<stdio.h>#include<process.h>void main(){int a[20],p[20],i,j,n,m;printf("Enter no of Blocks.\n");scanf("%d",&n);for(i=0;i<n;i++){ printf("Enter the %dst Block size:",i); scanf("%d",&a[i]);}printf("Enter no of Process.\n");scanf("%d",&m);for(i=0;i<m;i++){ printf("Enter the size of %dst Process:",i); scanf("%d",&p[i]);}

for(i=0;i<n;i++){

for(j=0;j<m;j++) {

if(p[j]<=a[i]) {

printf("The Process %d allocated to %d\n",j,a[i]);p[j]=10000;break;

} }

}for(j=0;j<m;j++){

if(p[j]!=10000) {

printf("The Process %d is not allocated\n",j); }

Prepared by S.J.Subashini & G.D.Kesavan

Page 29: CS047-OS Lab Manual.

}}

Result: The program for First fit was implemented and hence verified.

b) Best fit Algorithm

Aim: To write a program to implement Best fit page replacement algorithm

Algorithm:a) Start the processb) Declare the sizec) Get the number of processes to be insertedd) Allocate the best hole that is small enough searchinge) Start at the best of the set of holes f) If not start at the hole that is sharing the pervious best fit search end g) Compare the hole h) If small enough then stop searching in the procedure i) Display the valuesj) Stop the process

Program:#include<stdio.h>#include<process.h>void main(){int a[20],p[20],i,j,n,m,temp,b[20],temp1,temp2,c[20];printf("Enter no of Blocks.\n");scanf("%d",&n);for(i=0;i<n;i++) { printf("Enter the %dst Block size:",i); scanf("%d",&a[i]);

b[i]=i;}printf("Enter no of Process.\n");scanf("%d",&m);for(i=0;i<m;i++){ printf("Enter the size of %dst Process:",i); scanf("%d",&p[i]); c[i]=i;}for(i=0;i<n;i++)

Prepared by S.J.Subashini & G.D.Kesavan

Page 30: CS047-OS Lab Manual.

{ for(j=0;j<m;j++) {

if(a[i]<a[j]) { temp=a[i]; temp1=b[i]; a[i]=a[j]; b[i]=b[j]; a[j]=temp; b[j]=temp1; } if(p[i]<p[j]) { temp=p[i]; temp2=c[i]; p[i]=p[j]; c[i]=c[j]; p[j]=temp; c[j]=temp2; }

}}for(i=0;i<n;i++){ for(j=0;j<m;j++) {

if(p[j]<=a[i]) {

printf("The Process %d allocated to Block %d\n",c[j],b[i]);

p[j]=10000;break;

} }}for(j=0;j<m;j++){ if(p[j]!=10000) { printf("The Process %d is not allocated\n",j); }

}}

Result: The program for Best fit was implemented and hence verified.

Prepared by S.J.Subashini & G.D.Kesavan

Page 31: CS047-OS Lab Manual.

c) Worst fit Algorithm

Aim: To write a program to implement Worst fit page replacement algorithm

Algorithm:a) Start the processb) Declare the sizec) Get the number of processes to be insertedd) Allocate the best hole that is small enough searchinge) Start at the best of the set of holes f) If not start at the hole that is sharing the pervious best fit search end g) Compare the hole h) If small enough then stop searching in the procedure i) Display the valuesj) Stop the process

Program:#include<stdio.h>#include<process.h>void main(){int a[20],p[20],i,j,n,m,temp,b[20],temp1,temp2,c[20];printf("Enter no of Blocks.\n");scanf("%d",&n);for(i=0;i<n;i++) { printf("Enter the %dst Block size:",i); scanf("%d",&a[i]);

b[i]=i;}printf("Enter no of Process.\n");scanf("%d",&m);for(i=0;i<m;i++){ printf("Enter the size of %dst Process:",i); scanf("%d",&p[i]); c[i]=i;}for(i=0;i<n;i++){ for(j=0;j<m;j++) {

if(a[i]<a[j]) { temp=a[i];

Prepared by S.J.Subashini & G.D.Kesavan

Page 32: CS047-OS Lab Manual.

temp1=b[i]; a[i]=a[j]; b[i]=b[j]; a[j]=temp; b[j]=temp1; } if(p[i]<p[j]) { temp=p[i]; temp2=c[i]; p[i]=p[j]; c[i]=c[j]; p[j]=temp; c[j]=temp2; }

}}for(i=0;i<n;i++){ for(j=0;j<m;j++) {

if(p[j]<=a[i]) {

printf("The Process %d allocated to Block %d\n",c[j],b[i]);

p[j]=10000;break;

} }}for(j=0;j<m;j++){ if(p[j]!=10000) { printf("The Process %d is not allocated\n",j); }

}}

Result: The program for Worst fit was implemented and hence verified.------------------------------------------------------------------------------------------------------------Exercise 8: FIFO & LRU Page Replacement Algorithm

a) Implementation of FIFO Page Replacement Algorithm

Aim: To write a program to implement FIFO page replacement algorithm

Prepared by S.J.Subashini & G.D.Kesavan

Page 33: CS047-OS Lab Manual.

Algorithm:a) Start the processb) Declare the size with respect to page lengthc) Check the need of replacement from the page to memoryd) Check the need of replacement from old page to new page in memorye) Forma queue to hold all pagesf)Insert the page require memory into the queueg) Check for bad replacement and page faulth) Get the number of processes to be insertedi) Display the valuesj) Stop the process

Program:#include<stdio.h>int main(){int i,j,n,a[50],frame[10],no,k,avail,count=0; printf("\n ENTER THE NUMBER OF PAGES:\n");scanf("%d",&n); printf("\n ENTER THE PAGE NUMBER :\n"); for(i=1;i<=n;i++) scanf("%d",&a[i]); printf("\n ENTER THE NUMBER OF FRAMES :"); scanf("%d",&no);for(i=0;i<no;i++) frame[i]= -1; j=0; printf("\tref string\t page frames\n");

for(i=1;i<=n;i++) { printf("%d\t\t",a[i]); avail=0; for(k=0;k<no;k++)

if(frame[k]==a[i]) avail=1; if (avail==0) { frame[j]=a[i]; j=(j+1)%no; count++; for(k=0;k<no;k++) printf("%d\t",frame[k]);

} printf("\n");

}

Prepared by S.J.Subashini & G.D.Kesavan

Page 34: CS047-OS Lab Manual.

printf("Page Fault Is %d",count); return 0;}

Result: The program for FIFO page replacement was implemented and hence verified.

------------------------------------------------------------------------------------------------------------b)Implementation of LRU Page Replacement Algorithm

Aim: To write a program a program to implement LRU page replacement algorithm

Algorithm:a) Start the processb) Declare the sizec) Get the number of pages to be insertedd) Get the valuee) Declare counter and stackf) Select the least recently used page by counter valueg) Stack them according the selection.h) Display the valuesi) Stop the process

Program:#include<stdio.h>main(){int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];printf("Enter no of pages:");scanf("%d",&n);printf("Enter the reference string:");for(i=0;i<n;i++) scanf("%d",&p[i]);printf("Enter no of frames:");scanf("%d",&f);q[k]=p[k];printf("\n\t%d\n",q[k]);c++;k++;for(i=1;i<n;i++) { c1=0; for(j=0;j<f;j++) { if(p[i]!=q[j]) c1++;

Prepared by S.J.Subashini & G.D.Kesavan

Page 35: CS047-OS Lab Manual.

} if(c1==f) { c++; if(k<f) { q[k]=p[i]; k++; for(j=0;j<k;j++) printf("\t%d",q[j]); printf("\n"); } else { for(r=0;r<f;r++) { c2[r]=0; for(j=i-1;j<n;j--) { if(q[r]!=p[j]) c2[r]++; else break; } } for(r=0;r<f;r++) b[r]=c2[r]; for(r=0;r<f;r++) { for(j=r;j<f;j++) { if(b[r]<b[j]) { t=b[r]; b[r]=b[j]; b[j]=t; } } } for(r=0;r<f;r++) { if(c2[r]==b[0]) q[r]=p[i]; printf("\t%d",q[r]); } printf("\n");

Prepared by S.J.Subashini & G.D.Kesavan

Page 36: CS047-OS Lab Manual.

} }}printf("\nThe no of page faults is %d",c);}

Result: The program for LRU page replacement was implemented and verified------------------------------------------------------------------------------------------------------------Exercise 09: Contiguous Memory Allocation.

Aim: To write a program a program to implement contiguous memory allocation.

Algorithm:a) Start the program and input the size of hole, process etc from user.b) Allocate the process if less than hole size and add the process to running array.c) Wait the process if size more than hole and add the process to waiting array.d) When running process completes, resume the allocated space.e) Move the waiting array to process array and try to allocate the process.f) Allocation is made continuous here.g) Terminate the program.

Program:#include<stdio.h>#include<process.h>void main(){int a[20],p[20],i,j,n,m,y=0,z=0,running[20],waiting[20],b[20];

printf("Enter size of hole.\n");scanf("%d",&n);

printf("Enter no of Process.\n");scanf("%d",&m);

for(i=0;i<m;i++){ a[i]=i; printf("Enter the size of %dst Process:",i); scanf("%d",&p[i]);}

while(m){

for(i=0;i<m;i++){

if(p[j]<=n){

printf("The Process %d is allocated \n",a[i]);

Prepared by S.J.Subashini & G.D.Kesavan

Page 37: CS047-OS Lab Manual.

n=n-p[i];running[y]=a[i];y++;

}else

{ printf(“The Process %d is waiting\n”,a[i]);

waiting[z]=a[i];b[z]=p[i];z++;

}}

for(i=0;i<y;i++){

printf("The Process %d Terminated\n",running[i]);n=n+p[i];m--;

}

for(i=0;i<m;i++)p[i]=0;

for(i=0;i<m;i++)p[i]=b[i];

z=0;y=0;}

}

Result: The program for Contiguous Memory allocation was implemented and hence verified.

------------------------------------------------------------------------------------------------------------Exercise 10: Study of Unix Basic & I/O System Calls

The fork() & getpid() System Call

System call fork() is used to create processes. It takes no arguments and returns a process ID. The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call. Therefore, we have to distinguish the parent from the child. This can be done by testing the returned value of fork():

If fork() returns a negative value, the creation of a child process was unsuccessful.

Prepared by S.J.Subashini & G.D.Kesavan

Page 38: CS047-OS Lab Manual.

fork() returns a zero to the newly created child process. fork() returns a positive value, the process ID of the child process, to the parent.

The returned process ID is of type pid_t defined in sys/types.h. Normally, the process ID is an integer. Moreover, a process can use function

getpid() to retrieve the process ID assigned to this process.

Therefore, after the system call to fork(), a simple test can tell which process is the child. Please note that Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces. Void main(){Pid_t pid;

fork();pid=getpid();if(pid == -1)printf(“\n Error in creating process “);else if(pid == 0)printf("\nExecuting in child process, pid=%d and its parent pid = %d ", getpid(),getppid());elseprintf("\nExecuting in parent process,pid=%d \n",getppid());}

The exec() System Call

The exec functions of Unix-like operating systems are a collection of functions that causes the running process to be completely replaced by the program passed as argument to the function. As a new process is not created, the process ID (PID) does not change across an execute, but the data, heap and stack of the calling process are replaced by those of the new process.

int main(int argc, char *argv[]){ execvp(argv[1], &argv[1]); perror("exec failure"); exit(1);}

The wait() System Call

A parent process usually needs to synchronize its actions by waiting until the child process has either stopped or terminated its actions.

Prepared by S.J.Subashini & G.D.Kesavan

Page 39: CS047-OS Lab Manual.

The wait() system call allows the parent process to suspend its activities until one of these actions has occurred.

The wait() system call accepts a single argument, which is a pointer to an integer and returns a value defined as type pid_t.

If the calling process does not have any child associated with it, wait will return immediately with a value of -1.

If any child processes are still active, the calling process will suspend its activity until a child process terminates.

Void main(){

int status; pid_t pid;

pid = fork();

if(pid == -1) printf(“\nERROR child not created “);else if (pid == 0) /* child process */ {

printf("\n I'm the child!"); exit(0);

} else /* parent process */ {

wait(&status); printf("\n I'm the parent!") printf("\n Child returned: %d\n", status)

} }

The stat() System Call

There are a number of system calls that a process can use to obtain file information. The most useful one is "stat" system call.

The stat() system call is used to obtain file information.

Its prototype is like this:    int stat(const char *file_name, struct stat *buf) The stat structure is a pre-defined structure, which contains the following fields:struct stat

Prepared by S.J.Subashini & G.D.Kesavan

Page 40: CS047-OS Lab Manual.

{dev_t st_dev; /* device */ino_t st_ino; /* inode */mode_t st_mode; /* protection */nlink_t st_nlink; /* number of hard links */uid_t st_uid; /* user ID of owner */gid_t st_gid; /* group ID of owner */dev_t st_rdev; /* device type (if inode device) */off_t st_size; /* total size, in bytes */blksize_t st_blksize; /* blocksize for filesystem I/O */blkcnt_t st_blocks; /* number of blocks allocated */time_t st_atime; /* time of last access */time_t st_mtime; /* time of last modification */time_t st_ctime; /* time of last change */};const int N_BITS = 3;int main(int argc, char *argv[ ]){unsigned int mask = 0700;struct stat buff;static char *perm[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};if (argc > 1) {    if ((stat(argv[1], &buff) != -1))         {           cout << "Permissions for " << argv[1] << " ";           for (int i=3; i; --i)               {              cout << perm[(buff.st_mode & mask) >> (i-1)*N_BITS];              mask >>= N_BITS;              }        cout << endl;       }   else       {       perror(argv[1]);      return 1;     }  }else {cerr << "Usage: " << argv[0] << " file_name\n";return 2;}return 0;}

Prepared by S.J.Subashini & G.D.Kesavan

Page 41: CS047-OS Lab Manual.

The close() System Call

The close() system call is used to close a file descriptor.

#include <unistd.h> int close(int fd);main(int argc,char *argv[]){int fd,i;char ch[1];if (argc<2){ printf("Usage: mycat filename\n");exit(0);}fd=open(argv[1],O_RDONLY);if(fd==-1)printf("%s is not exist",argv[1]);else{printf("Contents of the file %s is : \n",argv[1]);while(read(fd,ch,1)>0)printf("%c",ch[0]);close(fd);}

The readdir() System Call

The readdir() function returns a pointer to a dirent structure repre-enting the next directory entry in the directory stream pointed to by dir. It returns NULL on reaching the end-of-file or if an error occurred.

main(){if(readdir() != null){ printf("Directory contents available\n");exit(0);}Else{printf("Directory contents is in end of file\n");exit(0);}}

The opendir() System Call

Prepared by S.J.Subashini & G.D.Kesavan

Page 42: CS047-OS Lab Manual.

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.

main(){if(opendir() != null){ printf("Directory opened\n");exit(0);}Else{printf("Error\n");exit(0);}}

The exit() System Call

This system call is used to terminate(normal/abnormal) the current running program.

main(int argc,char *argv[]){int fd,I,j=0;char ch[1],new[10];if (argc<2){ printf("Usage: mycat filename\n");exit(0);}fd=open(argv[1],O_RDONLY);if(fd==-1)printf("%s is not exist",argv[1]);else{New[0]=’a’;printf("Contents of the file %s is : \n",argv[1]);while(read(fd,ch,1)>0)printf("%c",ch[0]);while (j <=10){{write(fd,new,10)j++;

Prepared by S.J.Subashini & G.D.Kesavan

Page 43: CS047-OS Lab Manual.

new[j]=new[j-1]+1;}close(fd);exit(0);}

The open() Sytem Call

The "open()" system call opens an existing file for reading or writing. It has the syntax:

<file descriptor variable> = open( <filename>, <access mode> );

The "open()" call is similar to the "creat()" call in that it returns a file descriptor for the given file, and returns a file descriptor of -1 if it encounters an error. However, the second parameter is an "access mode", not a permission code. There are three modes (defined in the "fcntl.h" header file):

O_RDONLY Open for reading only.

O_WRONLY Open for writing only.

O_RDWR Open for reading and writing.

main(int argc,char *argv[]){int fd,i;char ch[1];if (argc<2){ printf("Usage: mycat filename\n");exit(0);}fd=open(argv[1],O_RDONLY);if(fd==-1)printf("%s is not exist",argv[1]);else{printf("Contents of the file %s is : \n",argv[1]);while(read(fd,ch,1)>0)printf("%c",ch[0]);close(fd);}

The write() Sytem Call

The "write()" system call writes data to an open file. It has the syntax:

Prepared by S.J.Subashini & G.D.Kesavan

Page 44: CS047-OS Lab Manual.

write( <file descriptor>, <buffer>, <buffer length> );

The file descriptor is returned by a "creat()" or "open()" system call. The "buffer" is a pointer to a variable or an array that contains the data; and the "buffer length" gives the number of bytes to be written into the file.

While different data types may have different byte lengths on different systems, the "sizeof()" statement can be used to provide the proper buffer length in bytes. A "write()" call could be specified as follows:

float array[10];

write( fd, array, sizeof( array ) );

The "write()" function returns the number of bytes it actually writes. It will return -1 on an error.

main(int argc,char *argv[]){int fd,i,j=0;char ch[1], new[10];if (argc<2){ printf("Usage: mycat filename\n");exit(0);}fd=open(argv[1],O_RDONLY);if(fd==-1)printf("%s is not exist",argv[1]);else{New[0]=’a’printf("Contents of the file %s is : \n",argv[1]);while(read(fd,ch,1)>0)printf("%c",ch[0]);while (j <=10){{write(fd,new,10)j++;new[j]=new[j-1]+1;}}close(fd);}

The read() Sytem Call

Prepared by S.J.Subashini & G.D.Kesavan

Page 45: CS047-OS Lab Manual.

The "read()" system call reads data from a open file. Its syntax is exactly the same as that of the "write()" call:

read( <file descriptor>, <buffer>, <buffer length> );

The "read()" function returns the number of bytes it actually returns. At the end of file it returns 0, or returns -1 on error

main(int argc,char *argv[]){int fd,I,j=0;char ch[1],new[10];if (argc<2){ printf("Usage: mycat filename\n");exit(0);}fd=open(argv[1],O_RDONLY);if(fd==-1)printf("%s is not exist",argv[1]);else{New[0]=’a’;printf("Contents of the file %s is : \n",argv[1]);while(read(fd,ch,1)>0)printf("%c",ch[0]);while (j <=10){{write(fd,new,10)j++;new[j]=new[j-1]+1;}

close(fd);}

------------------------------------------------------------------------------------------------------------

Prepared by S.J.Subashini & G.D.Kesavan