46
EASWARI ENGINEERING COLLEGE RAMAPURAM, CHENNAI-89 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING LAB MANUAL CS2257- OPERATING SYSTEM LABORATORY IV SEM CSE Prepared By Approved By HOD/CSE 1

Operating System Lab

Embed Size (px)

Citation preview

Page 1: Operating System Lab

EASWARI ENGINEERING COLLEGE

RAMAPURAM, CHENNAI-89

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

CS2257- OPERATING SYSTEM LABORATORY

IV SEM CSE

Prepared By Approved By

HOD/CSE

1

Page 2: Operating System Lab

CS 2257 OPERATING SYSTEMS LAB 0 0 3 2(Common to 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. (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, pipes 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)

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 andthis free disk 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 free space list and changing the start and end address in the appropriate node]. For allocation use first fit, worst fit and best fit.

2

Page 3: Operating System Lab

INDEX

1. Basic UNIX Commands

2. Implementation of system Calls

2a. Process Creation using System Calls (fork(), getpid(), exit())

2b. Process Creation using System Calls (fork(), exec())

2c. Program using System Calls (opendir(), readdir(),wait(),stat())

3. Copying the file using I/O System calls( open,read,write)

4. Simulation of UNIX commands

4.a Simulation of LS

4.b Simulation of GREP

5. Non-preemptive CPU Scheduling

5.a First come first serve Scheduling

5.b Shortest Job first Scheduling

6. Preemptive CPU scheduling

6.a Priority Scheduling

6.b Round Robin Scheduling

7. Interprocess communication using shared memory

8. Producer and Consumer problem using Semaphore

9. Memory management scheme- First fit method

10.Memory management scheme- Best fit method

11.File Allocation using linked technique

12.Memory allocation with pages

3

Page 4: Operating System Lab

Directory Commands

Command Descriptionpwd Shows the name and location of the directory where you are

curretly working. ls Gives you a short list of the files in the directory where you

are currently working.cd Moves you to another directory.mkdir Creates a new subdirectory inside of the directory where

you are currently working

File related commandsCommand DescriptionCAT>FILE Creates a filemore FILE Display contents of FILE, page by page.

cat FILE Display a file.cat FILE1 FILE2 > NEW Append FILE1 and FILE2 creating new file NEW.cat FILE1 >> FILE2 Append FILE1 at the end of FILE2.

sort FILE > NEWFILE Sort FILE, putting sorted version into NEWFILE.

grep ITEM FILE(S) Display lines of FILE(S) which contain ITEM.

wc FILE(S) Count characters, words and lines in FILE(S).diff FILE1 FILE2 | more Show differences between two versions of a filecp Type cp followed by the name of an existing file and the

name of the new file.

Eg:cp newfile newerfileTo copy a file to a different directoryspecify the directory instead of the new filename.

Eg:cp newfile testdirTo copy a file to a different directory and create a new file name, you need to specify a directory/a new file name.Eg:cp newfile testdir/newerfile cp newfile ../newerfile The .. represents one directory up in the hierarchy.

file Type file followed by the name of an existing file in the directory.Eg:file emergency3_demo.exe

chmod The chmod command allows you to alter access rights to

4

Page 5: Operating System Lab

files and directories. All files and directories have security permissions that grant the user particular groups’ or all other users’ access.

To view your files' settings, at the shell prompt type:

ls -alt

You should see some files with the following in front of them (an example follows):total 4drwxrwsr-x 7 reallyli reallyli 1024 Apr 6 14:30 .drwxr-s--x 22 reallyli reallyli 1024 Mar 30 18:20 ..d-wx-wx-wx 3 reallyli reallyli 1024 Apr 6 14:30 contentdrwxr-xr-x 2 reallyli reallyli 1024 Mar 25 20:43 files

What do the letters mean in front of the files/directories mean?r indicates that it is readable (someone can view the file’s contents)w indicates that it is writable (someone can edit the file’s contents)x indicates that it is executable (someone can run the file, if executable)- indicates that no permission to manipulate has been assigned

When listing your files, the first character lets you know whether you’re looking at a file or a directory. It’s not part of the security settings. The next three characters indicate Your access restrictions. The next three indicate your group's permissions, and finally other users' permissions.

Use chmod followed by the permission you are changing. In very simple form this would be: chmod 755 filenameThe example above will grant you full rights, group rights to execute and read, and all others access to execute the file.

# Permission  7 full  6 read and write  5 read and execute  4 read only  3 write and execute  2 write only

5

Page 6: Operating System Lab

  1 execute only  0 noneUse the table above to define the settings for the three "users." In the command, the first number refers to your permissions, the second refers to group, and the third refers to general users.

Typing the command: chmod 751 filenamegives you full access, the group read and execute, and all others execute only permission.

mv Type mv followed by the current name of a file and the new name of the file. Eg:mv oldfile newfile

Type mv followed by the name of a file and the new directory where you'd like to place the file.

Eg:mv newfile testdir

This moves the file named newfile to an existing directory named testdir. Be certain you’re specifying a directory name or the mv command alters the name of the file instead of moving it.

rmType rm followed by the name of a file to remove the file. Eg:rm newfile Use the wildcard character to remove several files at once.

Eg:rm n* This command removes all files beginning with n.

Type rm -i followed by a filename if you’d like to be prompted before the file is actually removed.

Eg:rm -i newfile rm -i n*

By using this option, you have a chance to verify the removal of each file. The -i option is very handy when removing a number of files using the wildcard character *.

find Search for file with a specific name in a set of filesfind . -name "rc.conf" -print

6

Page 7: Operating System Lab

This command will search in the current directory and all sub directories for a file named rc.conf.

Note: The -print option will print out the path of any file that is found with that name. In general -print will print out the path of any file that meets the find criteria.

How to search for a string in a selection of files (-exec grep ...). find . -exec grep "www.athabasca" '{}' \; -print

This command will search in the current directory and all sub directories. All files that contain the string will have their path printed to standard output.

Nl filename Inserts line number within the file

General Purpouse commands

date print or set the system date and time to set date and time

date -s "11/20/2003 12:48:00" - Set the date to the date and time shown.

date '+DATE: %m/%d/%y%nTIME:%H:%M:%S' - Would list the time and date in the below format:

DATE: 02/08/01TIME:16:44:55

bc Calculator

bc [-c] [-l] [file]

-c Compile only. The output is dc commands that are sent to the standard output.

-l Define the math functions and initialize scale to 20, instead of the default zero.

file Name of the file that contains the bc commands to be calculated this is not a necessary command.

Within the cal.txt file you could have a simple statement such as: /* Add the value 1+2 /*1+2quit

bc cal.txt

When running the above command you will receive the results of the cal.txt file. Which in this case would be 3.

echo Echo's to the screen what you type after echo. Echo is useful for producing diagnostics in command files, for sending known data into a pipe, and for

7

Page 8: Operating System Lab

displaying the contents of environment variables.

echo [-n] text

-n On BSD and some variants derived from BSD does not begin a new line after the echoed text.

text The text that you want to echo to the screen.

echo Hello world   The above example would return "Hello world" to the console echo * | wc The above example would list a count of all the files and directories in the current directory.

cal Calendar for the month and the year.cal [month] [year]

month Specifies the month for you want the calendar to be displayed. Must be the numeric representation of the month. For example: January is 1 and December is 12.

year Specifies the year that you want to be displayed.

Cal - Would give you the calendar for this month.Cal 12 2000 - Would give you the calendar for December of 2000. 

who Displays who is on the system.

man The man command is short for manualShows you online manuals on Unix commands.

man [-] [-k keywords] topic- Displays the manual without stopping.-k keywords  Searches for keywords in all of the manuals available. topic Displays the manual for the topic or command typed in.Man mkdir - Lists help information on the mkdir command. Man -k irc - Quickly searches for manuals containing irc within them.

clear Clears the screen

write Send a message to another user.write person [ttyname]

person If you wish to talk to someone on your own machine, then person is just the person's login name. If you wish to talk to a user on another host, then person is of the form 'user@host'.

ttyname If you wish to talk to a user who is logged in more than once, the ttyname argument may be used to indicate the appropriate terminal name, where ttyname is of the form 'ttyXX' or 'pts/X'

mail One of the ways that allows you to read/send E-Mail.

8

Page 9: Operating System Lab

Mail - Opens the mail program with the first message in the mail (if applicable).

Mail [email protected] - Starts a new e-mail, sending the e-mail to the support at Computer Hope. When composing a message to terminate the message type a period (.) and press enter.

ttyTo know terminal name

Filter commands

Grep

grep -i pattern file

grep -v pattern file

grep -c pattern file

grep -n pattern file

Finds text within a file.Eg:grep "unix" *.htmsearch all .htm files in the current directory for any reference of  unix and give results similar to the below example text

Prints all lines of file that contain the pattern, regardless of case. For example, grep -i cg data prints any line of data that contains "cg," "Cg," "cG," or "CG." The -i option ignores the case of the string when searching.

Prints all lines of the file except those that contain the pattern.

Display only the number of matching lines

What the "-n" does is tell grep to print out the line number as well as the line itself.

egrep

Search a file for a pattern using full regular expressions.egrep "support|help|windows" myfile.txt - Would search for patterns of support help and windows in the file myfile.txt.

sort Sorts the lines in a text file.sort [-b] [-d] [-f] [-i] [-m] [-M] [-n] [-r] [-u] [+fields] filename [-o outputfile]

-b Ignores spaces at beginning of the line.

-d Uses dictionary sort order and ignores the punctuation.

-f Ignores caps

-i Ignores nonprinting control characters.

-m Merges two or more input files into one sorted output.

-M Treats the first three letters in the line as a month

9

Page 10: Operating System Lab

(such as may.)

-n Sorts by the beginning of the number at the beginning of the line.

-r Sorts in reverse order

-u If line is duplicated only display once

+fields Sorts by fields , usually by tabs

filename The name of the file that needs to be sorted.

-o outputfile Sends the sorted output to a file.

Sort -r file.txt - Would sort the file, file.txt in reverse order.uniq Report or filter out repeated lines in a file.

uniq [-c | -d | -u ] [ -f fields ] [ -s char ] [-n] [+m] [input_file [ output_file ] ]

-c Precede each output line with a count of the number Of times the line occurred in the input.

-d Suppress the writing of lines that are not repeated In the input.

-u Suppress the writing of lines that are repeated In the input.

-f fields Ignore the first fields fields on each input line when doing comparisons, where fields is a positiveDecimal integer.

s char Ignore the first chars characters when doing comparisons,

-n Equivalent to -f fields with fields set to n.

+m Equivalent to -s chars with chars set to m.

input_file A path name of the input file. If input_file is not specified, or if the input_file is -, thestandard input will be used.

output_file A path name of the output file. If output_file is not specified, the standard output will be used.  The results are unspecified if the file named by output_file is the file named by input_file.

head Displays the first ten lines of a file, unless otherwise stated.head [-number | -n number] filename

-number The number of the you wants to display.

-n number The number of the you wants to display.

filename The file that you want to display the x amount of lines of.

Head -15 myfile.txt - Would display the first fifteen lines of myfile.txt.

tail Delivers the last part of the file.

10

Page 11: Operating System Lab

tail myfile.txt -n 100The above example would list the last 100 lines in the file myfile.txt.

cut Cut out selected fields of each line of a file.

Name=`who am i | cut -f1 -d' '` - set name to current login name.paste Merge corresponding or subsequent lines of files.

The below example would take the input from ls and paste that input into four columns.ls | paste - - - - 

tr Translate characters.tr [-c] [-d] [-s] [string1] [string2]

-c Complement the set of characters specified by string1.

-d Delete all occurrences of input characters that are specified by string1.

-s Replace instances of repeated characters with a single character.

string1 First string or character to be changed.

string2 Second string or character to change the string1.

EX:Echo "12345678 9247" | tr 123456789 computerh - this example takes an echo response of '12345678 9247' and pipes it through the tr replacing the appropriate numbers with the letters. In this example it would return computer hope.

Shell Commandscommand DescriptionPipe symbol (|). Pipes are a UNIX feature which allows you to connect several

commands together in one line and pass data from one to the next much like a chain.pipe connects one commands output to the next commands inputdirects UNIX to connect stdout from the first command to the stdin of the second commandline_count=`wc -l $filename | cut -c1-8`the wc -l command counts the number of lines in the filename contained in the variable $filename. This text string is then piped to the cut command which snips off the first 8 characters and passes them on to stdout, hence setting the variable line_count.upper_case=`echo $lower_case | tr '[a-z]' '[A-Z]'`

redirection Redirects work with files, not commandstr '[a-z]' '[A-Z]' < $in_file > $out_fileThe command must come first, the in_file is directed in by the

11

Page 12: Operating System Lab

less_than sign (<) and the out_file is pointed at by the greater_than sign (>).

tee It is used to store output of a ling pipeline command to be stored for later use.$cat mast|sort|tee temp|cut –d “:” –f1

System Call Description

NAME fopen, fdopen, freopen - stream open functionsSYNOPSIS #include <stdio.h>

FILE *fopen (const char *path, const char *mode); FILE *fdopen (int fildes, const char *mode); FILE *freopen (const char *path, const char *mode, FILE *stream);DESCRIPTION The fopen function opens the file whose name is the string Pointed to by path and associates a stream with it. The argument mode points to a string beginning with one of the Following sequences (Additional characters may follow these Sequence.):

r Open text file for reading. The stream is positioned at the beginning of the file.

r+ Open for reading and writing. The stream is positioned at the beginning of the file.

w Truncate file to zero length or create text file for Writing.The stream is positioned at the beginning of the File. w+ Open for reading and writing. The file is created if It does not exist, otherwise it is truncated. The Stream is positioned at the beginning of the file.

a Open for appending (writing at end of file). The file Is created if it does not exist. The stream is Positioned at the endof the file.

Fgets- Input the characters and string #include <stdio.h>

Char *fgets (char *s, int size, FILE *stream);

DESCRIPTIONFgets () - reads in at most one less than size characters from stream and

12

Page 13: Operating System Lab

Stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored Into the buffer.

RETURN Gets () and fgets () return s on success, and NULL on error or when End of file occurs while no characters have been read.

Fputs - output of characters and strings #include <stdio.h>

Int fputs (const char *s, FILE *stream);

DESCRIPTION fputs () writes the string s to stream

RETURN VALUE puts () and fputs () return a non-negative number on success, or EOF on error.NAME READDIR - read directory entry

SYNOPSIS #include <unistd.h> #include <linux/dirent.h> #include <linux/unistd.h>

Int readdir (unsigned int fd, struct dirent *dirp, unsigned int count);

DESCRIPTION Readdir reads one dirent structure from the directory pointed at by fd Into the memory area pointed to by dirp. The parameter count is Ignored; at most one dirent structure is read.

The dirent structure is declared as follows:

struct dirent {

long d_ino; /* inode number */ off_t d_off; /* offset to this dirent */ Unsigned short d_reclen; /* length of this d_name */ Char d_name [NAME_MAX+1]; /* file name (null-terminated) */

}

d_ino is an inode number. d_off is the distance from the start of the directory to this dirent. d_reclen is the size of d_name, not counting

13

Page 14: Operating System Lab

the null terminator. d_name is a null-terminated file name.

RETURN VALUE On success, 1 is returned. On end of directory, 0 is returned. On error, -1 is returned, and errno is set appropriately.NAME GROUP - user group file

DESCRIPTION /etc/group is an ASCII file which defines the groups to which users belong. There is one entry per line, and each line has the format:

group_name: passwd: GID: user_list

The field descriptions are: group_name

the name of the group.

password The (encrypted) group password. If this field is empty, no password is needed.

GID the numerical group ID

user_list All the group member's user names, separated by commas.

PASSWD (1) User utilities PASSWD (1)

NAME passwd - update a userGÇÖs authentication tokens(s)

SYNOPSIS passwd [-k] [-l] [-u [-f]] [-d] [-n mindays] [-x maxdays] [-w warndays] [-i inactivedays] [-S] [--stdin] [username]

DESCRIPTION Passwd is used to update a user authentication token(s).

Passwd is configured to work through the Linux-PAM API. Essentially, it initializes itself as a "passwd" service with Linux-PAM and utilizes Configured password modules to authenticate and then update a user password.

STAT (1) User Commands STAT (1)

14

Page 15: Operating System Lab

NAME stat - display file or filesystem status

SYNOPSIS stat [OPTION] FILE...

DESCRIPTION Display file or filesystem status.

-f, --filesystem Display filesystem status instead of file status -c --format=FORMAT use the specified FORMAT instead of the default -L, --dereference follow links -t, --terse print the information in terse form -Z, --context

STRSTRChar *strstr (const char *s1, const char *s2) -- locates the first occurrence of the string s2 in string s1. Strstr () returns a pointer to the specified search string or a null pointer if the string is not found. If s2 points to a string with zero length (that is, the string ""), the function returns s1. For example, Char *str1 = "Hello";Char *ans;ans = strstr (str1,'lo');Will yield ans = str + 3.

OPENInt open (char * filename, int flags) Int open (char * filename, int flags, int mode) include: <fcntl.h> flags = bitwise | or of any of the following: O_RDONLY Only read operations permitted O_WRONLY Only write operations permitted O_RDWR Read and Write operations both permitted O_NONBLOCK Non-blocking, applies to open operation only O_APPEND All writes go to end of file O_CREAT Create file if it doesn't already exist O_TRUNC Delete existing contents of file O_EXCL Open fails if file already exists O_SHLOCK Get a "shared lock" on the file O_EXLOCK Get an "exclusive lock" on the file O_DIRECT Try to avoid all caching of operations

15

Page 16: Operating System Lab

O_FSYNC All writes immediately effective, no buffering O_NOFOLLOW If file is symbolic link, open it, don't follow it mode required if file is created, ignored otherwise. mode specifies the protection bits, e.g. 0644 = rw-r--r-- returns <0 for error, or integer file descriptor.

READInt read (int fd, void * ptr, int numbytes) include< <unistd.h> fd = file descriptor as returned by open Ptr = address in memory where data is to be stored; may be a pointer of any type. numbytes = number of bytes to attempt to read returns <0 for error, 0 for end-of-file, or number of bytes successfully read. (for a non-blocking interactive file, that may be zero).

16

Page 17: Operating System Lab

1. Basic UNIX Commands

1. Create the following directory structure in UNIX CSE

PG UG2. Create files under CSE with extensions like *.txt, *.c etc.3. Display all files with extension ‘txt’4. Rename all files with extension ‘txt’ to ‘dat’5. Copy the files with extension C to UG directory6. Delete all the files with extension C from CSE directory7. Display all files with 2 character filename and extension ‘.txt’8. Create a file with list of subject names and Display the first three and last three Subjects stored in the file.9. List the contents of the file from the fourth subject from the end of the file and also list the

contents of the file from the seventh subject from the beginning of the file10. Create a file named INDIA which contains the following data

India is my countryAll Indians are myBrothers and SisterI love my countrya) Use the filter command to search for the pattern ‘my’b) Display all the lines that do not contain the above patternc) Count the total number of lines containing the pattern ‘my’d) Display all the lines which contains the pattern ‘country’

11. Create a file with 15 lines of data. Using filter commands select top 10 lines, Last 8 lines and display them in two different files. Add line numbers to the files. 12. Create a file containing 10 lines of information. Count the number of lines, number of words and number of character 13. Redirect the contents of ls –p to a file called LISTING. Give the commands to Redirect the output of a long listing of files and append it to the file LISTING

14. Change the modes of those files which begin with the letter ‘s’ in such a way that the owner has read and execute permission, the group has read and write permission and others only read permission(use octaldecimal representation)

15. Create a file called MARK which contains the sample data as follows:S001 Raja dbms 78S002 Usha os 96

17

Page 18: Operating System Lab

a) Display the contents of the file sorted according to the marks in the descending orderb) Display the names of the students in the alphabetic order ignoring the casesc) Display the list of students who have scored marks between 50 and 80d) Display the list of students and their registration numberse) Sort the files according to the third field and dump it to the file called SCODE

16. Create a file called EMP as given below:

E001:malar:mktg:5000E002:balan:acct:7000a) Sort the file on the employee’s department and display the name of the employee and the

departmentb) List the employees who earn between 4000 and 6000c) Sort the file on the employee name in the reverse order and extract their codes and their namesd) Display the contents of the file without redundancy in sorted order

17. Display the permission of the group for the files whose names begin with ‘p’18. Give the command to extract logins of the people whose login name starts with ‘CSE’19. Display the entire text of the file in uppercase20. Give the command to extract the links, the file owner and the file name only in the current

directory.

18

Page 19: Operating System Lab

Ex No:2a Process Creation using System calls( fork(), getpid(), exit())

Aim:

To Create a Program in C using fork(), getpid() and exit() system calls.

Algorithm:

Step 1: Start

Step 2: Create a process using Fork() System call and store the process id of the child in the

variable pid.

Step 3: If pid==-1 print ‘error in process creation’ and exit.

Step 4: If pid==0 then

4.1) Print ‘child process is executing’

4.2) Print the process id of the child using getpid() system call

4.3) Print the process id of the parent using getppid() system call

else

4.1’) Print ‘Parent process is executing’

4.2’) Print the process id of the parent using getpid() system call

4.3’) Print the process id of the child using pid

4.3’) Print the process id of the parent of the parent using getppid() system call

Step5: Stop

19

Page 20: Operating System Lab

Ex No:2b Process Creation using System calls (fork(), exec())

Aim:

To Create a Program in C using fork(), getpid() and exec() system calls.

Algorithm:

Step 1: Start

Step 2: Get the process id of the parent in the variable pid

Step 3: Create a child process using fork() system call

Step 4: Replace the child process with the ls command using exec() system call.

Step 5: Use wait system call to make the parent wait till the child is finished.

Step 6: End.

Ex No:2c Program using directory System calls

Aim:

To Create a Program in C to open and read the directory contents using opendir(), readdir() and stat() system calls.

Algorithm:

Step 1: Start

Step 2: Open the directory

Step 3: Read the contents of the directory

Step 4: Check the status whether the content of the directory is file or a directory

Step 5: Print the pathname of each and every file along with the access control list value.

Step 6: Stop

20

Page 21: Operating System Lab

21

Page 22: Operating System Lab

Ex No:3 Copying the File using I/O System calls

Aim:

To Create a Program in C to simulate cp command using I/O System Calls.

Algorithm:

Step 1: Start

Step 2: Open the file file1 to be copied in the read mode

Step 3: Open the new file file2 in the write mode

Step 4: While not end-of-file of file1 do the following

Step 4.1’: Read a string from file1

Step 4.2’: Copy the string onto file2

Step 5: Close file1, file2

Step 6: End

22

Page 23: Operating System Lab

Ex No:4a Simulation of LS

Aim:

To Simulate Unix command LS using C program.

Algorithm:

Step 1: Declare an object of type struct direct aqnd open the directory in read mode.

Step 2: Do the following until end of directory.

a) Check if number of arg is 1, if so then print the name of the file.

b) If number of arg==2 & 2nd arg is “-l” Call function dispperm() by passing file name

and the arg”-l”.

c) Read contents of dir.

d) End

Dispperm (char * name, char * arg):

Step 1: Declare objects P of struct stat and * grp of struct grp and pwd of struct password.

Step 2: Assign all contents of struct P.

Step 3: Check if it’s a regular file, if so, print “_”r else print “d” indicating it is a dir.

Step 4: Check if mode of operation is read/write/execute and return “r”/’w’/’x’ accordingly.

Step 5: Print number of lines.

Step 6: Get user id & print name of current working dir, group name.

Step 7: Print size of file, last modified time & name of file.

Step 8: Return to calling function.

23

Page 24: Operating System Lab

Ex No: 4b Simulation of GREP

Aim:

To Simulate Unix command GREP using C program.

Algorithm:

Step 1: If number of argument is less than 3, print an error statement and exit.

Step 2: If the number of argument is exactly equal to open file, then the name of file present is 3rd

argument.

.

a) Print ‘error’ if the file does not .exist and go to step 6

Step 3: If number of argument=4,open the file present in 4th argument and if file does

not exist print error and go to step 6

Step 4: Read a char from file into buffer and return the number of characters into a variable.

Step 5: Repeat following until number of char>0

a) If buffer does not contains ‘n’ copy its contents to another string line & increment

index.

b) Else

1. If number of argument= 3 & if line contains the 2nd argument (ie) the string, print

the line.

2. If number of argument=4 & line has 3rd argument (ie) string, print line number &

line.

3. Increment line number and empty the string line & make its index 0.

c) Read the file again.

Step 6: End.

24

Page 25: Operating System Lab

NON-PREEMPTIVE CPU SCHEDULING

Ex No:5.a First Come First Serve

Aim:

To schedule the process to CPU on first come first serve basis

Algorithm:

1. Start

2. Read the process name, Arrival time, its CPU burst from the user

3. Calculate waiting time and turn around for each process on a first come first basis

Waiting time = starting time - arrival time

Turn around time= finishing time – arrival time

4. Display the starting and finishing time of each process in their arrival time order

5. Calculate the average waiting time and average turn around time

6. Display the average waiting time and average turn around time

7. Stop

25

Page 26: Operating System Lab

Ex No:5.b Shortest Job First

Aim:

To schedule the process to CPU based on Shortest CPU burst time

Algorithm:

1. Start

2. Declare a structure ‘Proc_stru’ with member variables such as process name, CPU burst, arrival

time, waiting time and turn around time

3. Read the process name, Arrival time, its CPU burst from the user and store it in the structure

“Proc_stru”

4. Sort the process in the ascending order of their CPU burst

5. Calculate waiting time and turn around time for each process which ordered by the CPU burst time

Waiting time = starting time - arrival time

Turn around time= finishing time – arrival time

6. Display the starting and finishing time of each process in their execution order

7. Calculate the average waiting time and average turn around time

8. Display the average waiting time and average turn around time

9. Stop

26

Page 27: Operating System Lab

PREEMPTIVE CPU SCHEDULING

Ex No:6.a Priority Scheduling

Aim:

To schedule the process to CPU based on their Priority Algorithm

1. Start

2. Declare a structure ‘Proc_stru’ with member variables such as process name, CPU burst, priority,

arrival time, waiting time and turn around time

3. Read the process name, Arrival time, its CPU burst, priority from the user and store it in the

structure “Proc_stru”

4. Sort the process in the ascending order of their Priority

5. Calculate waiting time and turn around time for each process which ordered by their Priority

Waiting time = starting time - arrival time

Turn around time= finishing time – arrival time

6. Display the starting and finishing time of each process in their execution order

7. Calculate the average waiting time and average turn around time

8. Display the average waiting time and average turn around time

9. Stop

27

Page 28: Operating System Lab

Ex No:6.b Round Robin Scheduling

Aim:

To schedule the process to CPU in a Round Robin manner using a Time slice Algorithm

1. Start

2. Declare a structure ‘Proc_stru’ with member variables such as process name, CPU burst

3. Read the process name, its CPU burst from the user and store it in the structure “Proc_stru”

4. Get from the user – CPU Time slice

5. Allot the process to CPU for given time slice

6. Switch the CPU to next process when time slice over

7. Display the currently allotted process’s detail

8. Repeat the step 5,6 till all the process are serviced completely.

9. Stop

28

Page 29: Operating System Lab

Ex.No 7. Inter process communication using shared memory

Aim:

To develop a client-server application program which uses shared memory using IPC

Algorithm:

Server:

1. Define shared memory size of 30 bytes

2. Define the key to be 5600

3. Create a shared memory using shmget() system call and get the shared memory id in variable

shmid.

4. Attach the shared memory to server data space

5. Get the content to be placed in the shared memory from the user of the server.

6. Write the content in the shared memory, which will read out by the client.

7. stop

Client :

1. Define the key to be 5600

2. Attach the client to the shared memory created by the server.

3. Read the content from the shared memory.

4. Display the content on the screen.

5. stop

29

Page 30: Operating System Lab

EX No:8 Producer and Consumer Problem Using Semaphore

Aim:

To implement the Producer and Consumer Problem using semaphores

Algorithm:

1. Start

2. Initialize the semaphore variable S

3. In the producer function ,

3a)While s ==1 do nothing

3b)Produce the value

3c) Assign s=1

3d) Return

4. In the Consumer function

4a)While s==0 do nothing

4b)Display the consumed value

4c)Assign s=0

4d) Return

5. Create threads for producer and consumer function to make it run concurrently

6. Stop

30

Page 31: Operating System Lab

EX No:9 Memory management scheme – First fit method

Aim:

To allocate the memory using first fit strategy

Algorithm:

1. Start

2. Initialize the AVAIL linked list, where each node consist of starting address, size of the empty

block and a link for next available node

3. Initialize the ALLOCATE linked list, where each node consist of processe id, starting address,

size of the block and a link to next allocated block

4. Display the AVAIL List and ALLOCATE List

5. Read the memory request from the user which consist of process id and its size

6. Traverse the AVAIL linked list from the starting node

7. If the size of the empty block greater than process’s block size

a. Then Update size of the empty block

8. If the size of the empty block is equal to process’s block size

a. Then delete the node from AVAIL linked list

b. Else display a message, required memory is not available and go to step 14

9. Create a node and store process id , starting address of allotted block and its size

10. Insert the node in the ALLOCATE linked list

11. Display the AVAIL List and ALLOCATE List

12. Read the completed process’s id and its size from the user

13. Traverse the ALLOCATE list and delete the node containing the completed process id

14. Traverse the AVAIL list to merge the deallocated memory space

15. Display the AVAIL List and ALLOCATE List

16. Stop

31

Page 32: Operating System Lab

EX No:10 Memory management scheme –Best fit method

Aim:

To allocate the memory using Best fit strategy

Algorithm:

1. Start

2. Initialize the AVAIL linked list, where each node consist of starting address, size of the empty

block and a link for next available node

3. Sort the list according to its block size

4. Initialize the ALLOCATE linked list, where each node consist of processe id, starting address, size

of the block and a link to next allocated block

5. Display the AVAIL List and ALLOCATE List

6. Read the memory request from the user which consist of process id and its size

7. Traverse the AVAIL linked list from the starting node

8. If the size of the empty block greater than process’s block size

a. Then Update size of the empty block

9. If the size of the empty block is equal to process’s block size

a. Then delete the node from AVAIL linked list

b. Else display a message, required memory is not available and go to step 14

10. Create a node and store process id , starting address of allotted block and its size

11. Insert the node in the ALLOCATE linked list

12. Display the AVAIL List and ALLOCATE List

13. Read the completed process’s id and its size from the user

14. Traverse the ALLOCATE list and delete the node containing the completed process id

15. Traverse the AVAIL list to merge the deallocated memory space

16. Display the AVAIL List and ALLOCATE List

17. Stop

32

Page 33: Operating System Lab

EX No:11 File Allocation technique

Aim: To allocate the files in the secondary storage using Linked allocation technique

Algorithm:

1. Start

2. Initialize the AVAIL linked list, where each node consist of starting address, size of the empty

block and a link for next available node

3. Initialialize the FAT ( File Allocation Table) which is implemented as array of pointers.

4. Display the AVAIL List

5. Read File allocation request which consist of File name, No of blocks and its contents

6. Traverse the AVAIL linked list from the starting node

7. Retrieve the required no of blocks from AVAIL List

8. Assign the contents of file to the retrieved blocks

9. Update the FAT by making an entry in FAT

10. Update the AVAIL LIST

11. Display the AVAIL List and FAT table

12. Stop

33

Page 34: Operating System Lab

EX No:12 Memory Allocation With Pages

Aim: To implement memory allocation with pages

Algorithm:

1. Start

2. Declare the structure P_table with variables for page no and frame no

3. Display the status of physical memory

4. Get the number of pages needed for a process

5. Get the contents of the pages

6. Display the contents of logical memory

7. If the physical memory is available then allot the pages of the process

8. Update the physical memory status

9. Update the page table status

10. Display the page table after allocation

11. Display the physical memory after allocation

12. Stop

34