Displaying The File: EX - NO:1 Unix Commands AIM

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 82

EX.

NO:1 UNIX COMMANDS

AIM :
To Study the UNIX commands.

BASIC COMMANDS

1. CAT:

This is used to create a file.

SYNTAX:
Cat >file name

EXAMPLE:
Cat > rose
Hai
Hello

Displaying the file


SYNTAX:
Cat file name

EXAMPLE:
Cat rose
Hai
Hello

2. MKDIR:

This command helps us to make the directory.

SYNTAX:
mkdir <directory name>

EXAMPLE:
Mkdir tom

3. PWD:

This command displays the path name of the working directory.

SYNTAX:
Pwd

EXAMPLE:
home/w/x1

4. CD

This command is used to change the working directory to the specified directory.

SYNTAX:

[1]
cd
EXAMPLE:
[HTS171@vc2839 ~]$ cd tom
[HTS171@vc2839 tom]$

5. RMDIR:

This command removes the existing directory.

SYNTAX:
rmdir <directory name>

EXAMPLE:
Rmdir tom

6. CLEAR:

It is used to clear the screen.

SYNTAX:
Clear

7. LISTING DIRECTORY:

This command is used to view the content of the directory.

SYNTAX:
ls

EXAMPLE:
[HTS171@vc2839 ~]$ ls
f1 f3 gee rose

Other listing commands


(7.1) -a Lists all entries, including those not normally displayed.

EXAMPLE:
[HTS171@vc2839 ~]$ ls -a
. .bash_history .bash_profile f1 gee rose
.. .bash_logout .bashrc f3 .kde .zshrc

(7.2) -b displays nonprinting characters in octal notation

EXAMPLE:
[HTS171@vc2839 ~]$ ls -b
f1 f3 gee rose

(7.3) -d Lists only name of the directory, not in contents

EXAMPLE:
[HTS171@vc2839 ~]$ ls -d

(7.4) -lLists long format of directory, not its contents.

EXAMPLE:

[2]
[HTS171@vc2839 ~]$ ls -l
total 28
-rw-rw-r-- 1 HTS171 HTS171 97 2007-12-18 02:47 f1
-rw-rw-r-- 1 HTS171 HTS171 97 2007-12-18 03:07 f3
drwxrwxr-x 2 HTS171 HTS171 4096 2007-12-18 03:08 gee
-rw-rw-r-- 1 HTS171 HTS171 0 2007-12-18 01:46 rose

(7.5) -m Lists files across page, separated by commas.

EXAMPLE:
[HTS171@vc2839 ~]$ ls -m
f1, f3, gee, rose

(7.6) -n Lists long format showing UID and GID numbers instead of strings.

EXAMPLE:
[HTS171@vc2839 ~]$ ls -n
total 28
-rw-rw-r-- 1 616 616 97 2007-12-18 02:47 f1
-rw-rw-r-- 1 616 616 97 2007-12-18 03:07 f3

(7.7) -q Displays each nonprintable character in files as a question mark (?)

EXAMPLE:
[HTS171@vc2839 ~]$ ls -q
f1 f3 gee rose

(7.8) -r Lists files in reverse alphabetical order or oldest first when used with –t

EXAMPLE:
[HTS171@vc2839 ~]$ ls -r
rose gee f3 f1

(7.9) -t Lists file information sorted by most recent to oldest time stamp

EXAMPLE:
[HTS171@vc2839 ~]$ ls -t
gee f3 f1 rose

(7.10) -1 Lists only one entry per line of output

EXAMPLE:
[HTS171@vc2839 ~]$ ls -1
f1
f3

8. COPY:

This command is used to copy the contents of one file to another file.

SYNTAX:
cp filename new filename

EXAMPLE:

[3]
cp rose rose2

9. MOVE:

This command is used to move the file from source to destination.

SYNTAX:
mv old filename new filename
EXAMPLE:
mv ram1 ram2

10. SH COMMAND
Starts up the default shell command interpreter
SYNTAX:
Sh
EXAMPLE:
[HTS171@vc2839 ~]$ sh
sh-3.2$

11. STTY COMMAND


Set terminal options
SYNTAX:
stty
EXAMPLE:

[HTS171@vc2839 ~]$ stty


speed 9600 baud; line = 0;
-brkint -imaxbel

(11.1) -a Shows all of the current option setting


EXAMPLE:
[HTS171@vc2839 ~]$ stty -a
speed 9600 baud; rows 25; columns 80; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff
-iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke

(11.2) -g Allows option settings to be used as arguments to another sty command

EXAMPLE:
[HTS171@vc2839 ~]$ stty -g
500:5:bd:8a3b:3:1c:7f:15:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0
:0:0:0

12. WC COMMAND:
This is used to count the number of words, lines and number characters in a file.

SYNTAX:
wc filename

[4]
EXAMPLE:

[HTS171@vc2839 ~]$ cat file


unix program
operating systems
welcome
india
[HTS171@vc2839 ~]$ wc file
4 6 46 file

-l Counts the number of lines in a file


-w Counts the number of words in a file
-c Counts the number of characters in a file

EXAMPLE:
[HTS171@vc2839 ~]$ wc file -l
4 file
[HTS171@vc2839 ~]$ wc -c file
46 file
[HTS171@vc2839 ~]$ wc -w file
6 file
13. DATE:

This command is used to display the current date.

SYNTAX:
date
EXAMPLE:
[HTS171@vc2839 ~]$ date
Wed Dec 19 02:23:20 IST 2007

[HTS171@vc2839 ~]$ date +%y


07
[HTS171@vc2839 ~]$ date +%m
12
[HTS171@vc2839 ~]$ date +%d
19
14. TIME:
To display the time
SYNTAX:
time
EXAMPLE:
[HTS171@vc2839 ~]$ time
real 02:20.25
user 02:20.25
sys 02:20.25
[HTS171@vc2839 ~]$ date +%H
02
[HTS171@vc2839 ~]$ date +%M
20
[HTS171@vc2839 ~]$ date +%S
37
15. ECHO:

This command is used to display the string printed in this command line.

[5]
SYNTAX:
Echo”string”

EXAMPLE:
Echo hello

16. WHO:

This command is used to display the information about the current user.
SYNTAX:
Who
EXAMPLE:
[HTS171@vc2839 ~]$ who
VH946 pts/3 2007-12-18 02:09 (172.16.1.8)
VH940 pts/2 2007-12-18 02:10 (172.16.1.2)
VH947 pts/9 2007-12-18 02:14 (172.16.1.10)

17. GREP:
This command is used to search and print the specified pattern from file
SYNTAX:
grep[option]patternfilename
EXAMPLE:
Cat>count
Ab
ac
bc
Grep “a” count
Ab
Ac
18. SORT:
This command is used to sort the content of a file
SYNTAX:
Sort filename
EXAMPLE:
Cat >count
Ab
Ax
Ac
sort count

ab
ac
ax

19. READ:
This command is used to read the input values.

SYNTAX:
read varname
EXAMPLE:
read a

20. WHOAMI:

[6]
This command is used to print the details of the user.

SYNTAX:
Whoami
EXAMPLE:
[HTS171@vc2839 ~]$ whoami
HTS171

21. CALENDAR:

This command is used to display the calendar of any year and month.
SYNTAX:
Cal
EXAMPLE: [HTS171@vc2839 ~]$ cal 4 2007
April 2007
Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
22. FINDCOMMAND:
This command locates file and folders.
SYNTAX:
finddirectoryname
EXAMPLE:
[HTS171@vc2839 ~]$ find gee
gee
gee/f5

23. BC COMMAND:
Performs interactive arithmetic processing and displays results
SYNTAX:
bc
EXAMPLE:
[HTS171@vc2839 ~]$ bc
bc 1.06

24. CMP COMMAND:


Compares files and displays occurrence of first differences.
SYNTAX:
Comp file1 file2
EXAMPLE:
[HTS171@vc2839 ~]$ cmp file f1
file f1 differ: byte 1, line 1
25. CUT COMMAND:
Cuts out selected fields from lines within lines.
SYNTAX:
cut file
EXAMPLE:
[HTS171@vc2839 ~]$ cat file1
visual program
[HTS171@vc2839 ~]$ cut file1 -c 5
a
26. PASTE COMMAND:
Combines text of lines in file1 with those in file2

[7]
SYNTAX:
paste file1 file2
EXAMPLE:
[HTS171@vc2839 ~]$ cat file1

visual program
[HTS171@vc2839 ~]$ cat file2
Commands
unix
[HTS171@vc2839 ~]$ paste file1 file2
visual program commands
unix
CONDITIONAL STATEMENTS:

IF & IF-THEN-ELSE:

if Command
Executes command and checks for successful command completion status
then commands
Executes commands when if completes successfully
test command
Runs command if condition holds
elif command
Executes command and checks completion status after failure of preceding if
else command
Executes commands when if check does not complete successfully
fi
nds the if…then structure

SWITCH CASE:

case x in y command
xecutes command if string x is found in pattern y

esac Ends the case…in structure

FOR LOOP:

for x
Sets up a command loop where x is the number of positional parameters
in list
Specifies a list of the number of times to execute for

DO-WHILE LOOP:

do command
Executes commands each time for loop is entered
done command
Ends the for…do structure
while command
ets up a loop to execute while commands is true
do commands
xecutes commands each time while loop is entered
done command
nds the while…..do structure

[8]
UNTIL:
until command
ets up a loop to execute until commands is true
do command
xecutes commands each time until loop is entered
done command
nds the until…..do structure
while true
ets up an execution loop stopped when a condition is no longer true
until false
Sets up an execution loop stopped when a condition is false

EDITING COMMANDS:

ed Invokes the line editor


-r Allows only reading of the file contents
Filename Specifies filename as the file to be edited

vi file1 Invokes the screen editor on file1


-R Allows only reading of the file contents
+linenum Positions cursor at linenum of the file
File2 file3 Allows file2 and file3 to be edited along with file1

COMMUNICATION COMMANDS:

1. MAILCOMMAND:
This sends a mail to another user.
SYNTAX:
Mailuser
EXAMPLE:
mail u
hh
^d
2. mailx Process mail interactively

3. mesg shows state of permission or denial of message from other users


-y Permits messages to be received from other users on the system
-n Prevents messages from being received from other users on the system

4.talk username Sets up a conversation with user username on a TCP/IP network

5. tty Provides a specific terminal tty for a user logged in more than once

6. uname Lists the name of the current system you are logged into
-n Shows the communication node name for the sytem
-rv Dispalys the operating system release and version of the machine

7.wall Writes a broadcast message to all local users

8.write user Writes an interactive message to a specific user named user

9. line Specifies a tty line for a user logged in on more than one line

Vi MODE COMMANDS

[9]
ENTERING INPUT MODE

a Appending typed text into the buffer immediately after the position of the cursor
i Inserting typed text into the buffer immediately before the position of the cursor
A Appends material at the end of the current line
I Inserts material at the beginning of the current line
o Opens up a line above the current line places the cursor there, and puts vi in input mode
O Opens up a line below the current line places the cursor there, and puts vi in input mode

EXITING VI

First get out of input mode by hitting ESC

:w Will write the contents of the editing buffer into the file
:wq Will write and quit
zz Which represents “last command” is equivalent
:x Exit and is also equivalent to :wq If you have made changes ,you regret you can cancel all the changes you have
made by quitting the editor without writing the buffer to a file
:q! “Quit and I really meant it”

MODIFYING TEXT:

rn Replace the current character


Rstring ESC Replaces the current characters with the string you type in.Characters are overwritten until you press
ESC.
cwstringESC Changes the current word by replacing it with whatever string you type.The change continuos until you
press ESC.
4cw will change the next four words
3c$ Will change the next three lines

DELETING TEXT:

x Deletes the current character


7x Will delete seven character
dw Deletes from the cursor to the end of the word
3dw Deletes next three words
d$ Deletes the end of the line
D Deletes the end of the line(a synonym for d$)
3d$ Deletes the end of the third line ahead
d) Deletes to the beginning of the next line

[10]
d} Deletes to the beginning of the next paragraph
d]] Deletes to the beginning of the next section
dd Deletes the current line
2dd deletes two lines
dRETURN Deletes two lines
dG Deletes from the cursor to the end of the file

[11]
RESULT:

Thus the UNIX commands was executed and the output has been verified

EX.NO:2(a) TO ILLUSTRATE THE USE OF fork () AND getpid () SYSTEM CALLS

AIM:

To create a process in the following hierarchy

Parent

Child1

Child2

Child3

ALGORITHM

1. Declare the necessary variables.


2. Parent process is the process of the program which is running.
3. Create the child1 process using fork() When parent is active.
4. Create the child2 process using fork() when child1 is active.
5. Create the child3 process using fork() when child2 is active.

PROGRAM:

#include<stdio.h>

void main()

int pid1,pid2,pid3;

printf("Parent id is %d and root id is %d\n",getpid(),getppid());

pid1=fork();

[12]
if(pid1==0)

printf("Process 1 id is %d and its parent id is %d\n",getpid(),getppid());

pid2=fork();

if(pid2==0)

printf("Process 2 id is %d and its parent id is %d\n",getpid(),getppid());

pid3=fork();

if(pid1==0&&pid2==0&&pid3==0)

printf("Process 3 id is %d and its parent id is %d\n",getpid(),getppid());

OUTPUT:

[cse1@minix ~]$ ./a.out

Parent id is 17569 and root id is 16216

Process 1 id is 17570 and its parent id is 17569

Process 2 id is 17571 and its parent id is 17570

Process 3 id is 17572 and its parent id is 17571

[13]
RESULT:
Thus the process id, value were printed by using the fork and getpid system calls.

EX.NO:2(b) TO DEMONSTRATE EXECLP ( ) FUNCTION

AIM:

To write a shell program to implement the execlp( ) function .

ALGORITHM:

1. Start the program.

2. Obtain the pid value using fork ( ) function.

3. If pid < 0, then print fork failed.

4. Else if pid = 0 , execlp( ) function will invoked .

5. Else print child process complete.

6. Terminate the program.


PROGRAM:

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <errno.h>

main(int argc,char *argv[])

int pid;

pid =fork();

if(pid<0)

printf(stderr,"Fork failed \n");

[14]
exit(-1);

else if(pid==0)

execlp("/bin/ls","ls",NULL);

else

wait(NULL);

printf("Child Complete");

OUTPUT:

[cse1@minix ~]$./a.out

bird gy mudit1.c sa.c zx1.c

bj.c h mudit.c sag.c zxc.c

bkr h1 mukesh.c saha zxcv

black.c h616 mukku sah.c zzz1

blue.c habib.c multan.c sahil zzz2

bn hada multi sahu

Child Complete

[15]
RESULT:

Thus the execlp function were implemented successfully.

EX NO:3 TO SIMULATE FILE OPEN, READ, WRITE OPERATIONS

AIM:

To write a shell program to simulate file open, read and write operations.

ALGORITHM:

1. Start the program


2. Define the buffer size,Pmode value
3. The open function used to open the file and the creat function used to create the file
4. To read or write a file assumed to exist already.
5. The returned value fildes is a file-descriptor used to denote the file in subsequent calls that read, write or
otherwise manipulate the file.
6. The function open returns -1 if any error occurs; otherwise, it returns a valid open file-descriptor.
7. If the file is brand new, creat creates it with the protection mode specified by the pmode argument.
8. Stop the execution
PROGRAM:

#include<stdio.h>

#define BUFSIZE 512

#define PMODE 0644

char *progname;

main(argc, argv)

int argc;

char *argv[ ];

int fd1, fd2, n;

char buf[BUFSIZE];

progname=argv[0];

[16]
if (argc != 3)

error("Usage: cp from to", progname);

if ((fd1 = open(argv[1], 0)) == -1)

error("cp: can't open %s", argv[1]);

if ((fd2 = creat(argv[2], PMODE)) == -1)

error("cp: can't create %s", argv[2]);

while ((n = read(fd1, buf, BUFSIZE)) > 0)

if (write(fd2, buf, n) != n)

error("cp: write error", (char *)0);

exit(0);

OUTPUT:

[cse1@minix ~]$ cat > f1

hai

hello

welcome

[1]+ Stopped cat > f1

[cse1@minix ~]$ cat >f2

[2]+ Stopped cat > f2

[cse1@minix ~]$ ./a.out f1 f2

[cse1@minix ~]$ cat f2

hai

hello

welcome

RESULT:

[17]
Thus the file operations were simulated successfully.

EX.NO: 4 (a) SIMULATION OF LS COMMAND

AIM:

To write a shell program to simulate the ls command

ALGORITHM:

1. Start the program


2. To define a pointer to a structure ,dirname predefined structure DIR and another pointer to a structure
called preaddir
3. The directory is opened using the opendir() function.
4. In the while loop read each entry using the readdir() function which returns a pointer.
5. If no pointer is returned the program is exited, else the name of the entry is displayed.
6. The closedir() function closes this open directory
7. Stop the program.
PROGRAM:

#include<stdio.h>

#include<sys/types.h>

#include<dirent.h>

main(argc,argv)

int argc;

char *argv[];

DIR *dirname;

struct dirent *rdir;

dirname=opendir(argv[1]);

while(1)

[18]
rdir=readdir(dirname);

if(rdir==NULL)

closedir(dirname);

exit(0);

printf("found entry in %s:%s\n",argv[1],rdir->d_name);

closedir(dirname);

exit(0);

OUTPUT:

[cse1@minix ~]$ ./a.out dir

found entry in dir:.

found entry in dir:..

RESULT:

Thus the ls command were simulated successfully

[19]
EX.NO. 4 (b) SIMULATION OF GREP COMMAND

AIM:

To write a shell program to simulator grep() operations.

ALGORITHM:

Step1: start the program

Step2: Using write() function enter the data to be stored in the file

Step3: Break the data storage by using the $ symbol

Step4: using fptr() enter the pattern to be searched in the file

Step5: Compare the search pattern by using strncmp()

Step6: Using fclose() close the file.

Step7: stop the program

PROGRAM:

#include<stdio.h>

#include<string.h>

void main()

FILE *fptr;

char ch;

int i;

char p[10],a[50];

fptr=fopen("input.txt","w");

printf("Enter the data to be stored in the file \n");

ch = getchar();

while(ch!='$')

[20]
{

fprintf(fptr,"%c",ch);

ch = getchar();

fclose(fptr);

printf("Enter the pattern tobe searched");

scanf("%s",p);

fptr=fopen("input.txt","r");

i=0;

while(!feof(fptr))

ch=getc(fptr);

if(ch!='\n')

a[i]=ch;

else

a[i]='\0';

if (strncmp(a,p,strlen(p))==0)

printf("%s\n",a);

i=-1;

i++;

fclose(fptr);

//getch();

[21]
OUTPUT:

[cse1@minix ~]$ ./a.out

Enter the data to be stored in the file

wel

welcome

well

cse

vel

Enter the pattern tobe searched : wel

wel

welcome

well

[22]
RESULT:

Thus the Grep command were simulated successfully.

EX NO : 5 INTER PROCESS COMMUNICATION USING PIPES.

AIM:

To write a shell program to simulate inter processcommunication using pipes.

ALGORITHM:

1.Start theprogram

2. Obtain the pid value using fork ( ) function

3.Using pipe () function create a pipe to allow bidirectional data flow.

4.using close() function close the one end of the pipe.

5.Enter the values in the pipe and check the sum of odd and even numbers inside the pipe and print the result

6.Stop the program

PROGRAM:

#include<sys/types.h>

#include<unistd.h>

#include<stdio.h>

int main ()

int c;

int pid;

int fd[2];

int n,i=0;

int t1,even=0,odd=0,r;

pid=pipe(fd);

if(pid!=0)

exit(0);

[23]
c=fork();

if(c!=0)

close(fd[0]);

printf("Enterthevalues \n");

while(n!=-99)

scanf("%d",&n);

write(fd[1],&n,sizeof(n));

else if(c==0)

close(fd[1]);

while(n!=-99)

read(fd[0],&n,sizeof(n));

r=n%2;

if(r==0)

even=even+n;

else if(r!=0 && n!=-99)

odd=odd+n;

printf("Sum of even numbers :%d \n Sum of odd numbers :%d \n",even,odd);

[24]
OUTPUT:

[cse1@minix ~]$ ./a.out

Enterthevalues

12 11 14 5 6

-99

Sum of even numbers :32

Sum of odd numbers :16

[25]
RESULT:

Thus the inter process communication using pipes have simulated

EX NO: 6 SEMAPHORE IMPLEMENTATION.

AIM:

To write a shell program to implement producer consumer process using semaphore

ALGORITHM :

1. Create two functions called producer and consumer.


2. Set semaphore variable as 1.
3. When producer active set the semaphore variable as 1 and allow producer to put data into the buffer and
don’t allow consumer to consume anything.
4. After producer complete the process release the semaphore and signal the consumer.
5. When consumer active again set the semaphore variable as 1 and allow the consumer to get data from
buffer and don’t allow the producer to add data.
6. After the consumer taken release the semaphore variable and signal the producer.

PROGRAM:

PRODUCER:

#include<stdio.h>

#include<sys/types.h>

#include<sys/sem.h>

#include<sys/shm.h>

main()

int i ,j ,r , SID , id ,*a , n , t ;

void wait(int id , short num);

void signal(int id , short num);

union pro

int val;

struct semid_ds *buf;

unsigned short array[3];

[26]
struct seminfo *_buf;

}arg;

printf("\n\t producer & consumer");

printf("\n\t -----------------------------");

printf("\n\t enter the number of terms :");

scanf("%d",&n);

id=shmget((key_t)125,(1*sizeof(int)),0766|IPC_CREAT|IPC_EXCL);

if(id == 0)

printf("\n\n shared memory is not created");

exit(0);

a=shmat(id,NULL,0700);

SID=semget((key_t)135,3,0700| IPC_CREAT|IPC_EXCL);

printf("\n\n SEMAID : %d",SID);

if(SID==0)

printf("\n\n semphore is not created");

exit (0);

arg.array[0]=1;

arg.array[1]=0;

arg.array[2]=1;

t=semctl(SID,0,SETALL,arg);

*(a+0)=n;

*(a+10)= 0;

t=semctl(SID,0,GETALL,arg);

printf("\n\n\t producer product");

[27]
printf("\n\t -----------------------------");

for(i=2;i<=n+2;i++)

wait(SID,2);

wait(SID,0);

scanf("%d",&r);

*(a+i) = r ;

signal(SID,0);

signal(SID,1);

while(*(a+1)==0);

if(*(a+1)== -99);

shmdt(a);

shmctl(id,IPC_RMID,NULL);

semctl(SID,0,IPC_RMID,NULL);

printf("\n\n");

CONSUMER:

#include<stdio.h>

#include<sys/types.h>

#include<sys/sem.h>

#include<sys/shm.h>

main()

int i,j,r,SID,id,*a,n,t;

[28]
void wait(int id , short num);

void signal(int id , short num);

union consum

int val;

struct semid_ds *buf;

unsigned short array[3];

struct seminfo *_buf;

}arg;

printf("\n\t consumer consuming a product");

printf("\n\t -----------------------------");

id=shmget((key_t)125,(1*sizeof(int)),0766);

if(id==0)

printf("\n\n shared memory is not created");

exit(0);

a=(int *)shmat(id,NULL,0766);

SID=semget((key_t)135,3,0700);

printf("\n\n %d",SID);

if(SID==0)

printf("\n\n semphore is not created");

exit(0);

n=*(a+0);

t=semctl(SID,0,GETALL,arg);

for(i=2;i<=n+2;i++)

[29]
{

wait(SID,1);

wait(SID,0);

printf("\n%d",*(a+i));

signal(SID,0);

signal(SID,2);

*(a+1)==0;

*(a+1)==-99;

shmdt(a);

void wait(int id,short num)

int t;

struct sembuf *op=(struct sembuf *)malloc(sizeof(struct sembuf));

op->sem_num= id;

op->sem_op= - 1;

t= semop(id,op,1);

void signal(int id , short num)

int t;

struct sembuf *op=(struct sembuf *)malloc(sizeof(struct sembuf));

op->sem_num = id;

op->sem_op = 1;

t= semop(id,op,1);

[30]
OUTPUT:

[cse1@minix ~]$ ./a.out

producer & consumer

Enter the number of terms : 5

SEMAID : 196612

producer product

12 10 24 51 71

sh-3.2$ ./a.out

consumer consuming a product

196612

12

10

24

51

71

[31]
RESULT:

Thus the producer consumer process was implanted and they were allowed to communicate via semaphore
successfully.

EX NO: 7 IMPLEMENTATION OF READER WRITER PROBLEM.

AIM:

To write a shell program to implement the reader writer problem

ALGORITHH:

1. Start the program.

2.Create three Semaphore variable MUTEX,WRITE and RWCNT for mutual exclusion, Writer process for both
read and write count respectively..

3. Now, create a process for both Reader and Writer.

4. During Reader process, issue WAIT to MUTEX and WRITE semaphores also increment RWCNT semaphore
then SIGNAL to MUTEX semaphore and display the file.

5. After reading a file, issue WAIT to MUTEX semaphore and decrement RWCNT semaphore then SIGNAL to
WRITE and MUTEX semaphores.

6. During Writing process, issue WAIT to WRITE semaphore then modify contents of the file. After updating the
file, issue SIGNAL to WRITE semaphore. Here no reading process is allowed.

7. Stop the program.

PROGRAM:
#include<stdio.h>

#define down 0

#define up 1

typedef int semaphore;

semaphore mutex=1;

semaphore db=1;

semaphore win=up,pwin=up;

int readq[10],writeq[10];

int rc=0,pro=0,a=0,rl=0;

int rbeg=0,rend=0,wbeg=0,wend=0;

int rcount=0,wcount=0;

[32]
void readerin(int);

void readerout();

void writerin(int);

void writerout();

main()

char ch,prev='n';

printf("\n\t\t READER-WRITER PROBLEM");

printf("\n\t\t ***************");

printf("\n");

printf("\n Initial state");

printf("\n The database is free to access");

printf("\n There are no readers or writers");

do

printf("\n");

printf("\n is there any reader or writer or null(r/w/n):");

ch=getchar();

putchar(ch);

switch(ch)

case 'r':

rcount++;

readerin(rcount);

break;

case 'w':

wcount++;

writerin(wcount);

[33]
break;

Default:

break;

if(prev=='r')

if(pro>0) {

a=a+1;

readerout();

if(prev=='w')

if(pwin==down)

writerout();

prev=ch;

pro=rc;

pwin=win;

}while(ch!='n');

printf("\n The process is continued .......");

printf("\n");

void readerin(int r)

if(win==down)

printf("\n The writer is changing the database");

[34]
printf("\n Reader %d is put in queue",r);

writeq[wend]=wcount;

wend++;

else {

mutex=down;

rc++;

if(rc==1)

db=down;

mutex=up;

printf("\n Reader %d is reading the database",r);

r=rc;

void readerout()

mutex=down;

rc--;

if(rc==0);

db=up;

mutex=up;

printf("\n Accessing Reader %d has finished Reading",a);

void writerin(int w)

if(win==down)

printf("\n previous writer is changing the database");

[35]
printf("\n Writer %d is Waiting",w);

writeq[wend]=w;

wend++;

} else

if(rc>0)

printf("\n Reader is accessing the database");

printf("\n Writer %d is Waiting",w);

writeq[wend]=w;

wend++;

else

if((wend-wbeg)>0)

printf("\n writer %d is waiting",wend);

writeq[wend]=w;

wend++;

w=writeq[wbeg];

wbeg++;

printf("\n writer %d is accessing the database",wbeg);

win=down;

db=down;

void writerout()

[36]
int r,w;

db=up;

win=up;

printf("\n Accessing writer finished his word");

if((rend-rbeg)>0)

do

r=readq[rbeg];

readerin(r);

rbeg++;

}while((rend-rbeg)>0);

else

if((wend-wbeg)>0)

w=writeq[wbeg];

wbeg++;

writerin(w);

OUTPUT:

[cse1@minix ~]$ ./a.out

READER-WRITER PROBLEM

Initial state

The database is free to access

There are no readers or writers

Is there any reader or writer or null(r/w/n): w

[37]
w

writer 0 is accessing the database

Is there any reader or writer or null(r/w/n):

Accessing writer finished his word

is there any reader or writer or null(r/w/n):r

Reader 1 is reading the database

is there any reader or writer or null(r/w/n):

Accessing Reader 1 has finished Reading

is there any reader or writer or null(r/w/n):r

Reader 2 is reading the database

is there any reader or writer or null(r/w/n):

Accessing Reader 2 has finished Reading

is there any reader or writer or null(r/w/n):n

The process is continued .......

[cse1@minix ~]$

[38]
RESULT:

Thus the reader writer problem was implemented successfully.

EX NO: 8 IMPLEMENTATION OF DINING PHILOSOPHER PROBLEM.

AIM:

To write a shell program to implement Dining philosopher problem.

ALOGORITHM:

1.Start the program.

2.Print the initial state of the philosopher

3. If the philosopher is in the hungry state use the function take(n-1).

4. If the philosopher is in the thinking state use the function drop(n-1).

5.Repeate the step 3 and step 4 until the process ends.

6.Stop the program

PROGRAM:

#include<stdio.h>

char state[10];

void test(int k)

if((state[(k+4)%5]!='e')&&(state[k]=='h')&&(state[(k+1)%5]!='e'))

state[k]='e';

void take(int i)

state[i]='h';

test(i);

[39]
}

void drop(int i)

state[i]='t';

test((i+4)%5);

test((i+1)%5);

main()

int i,n,opt=0;

printf("\t\t dining philosopher problem");

printf("\n\t\t_____________\n");

for(i=0;i<5;i++)

state[i]='t';

printf("Initial state of dining philosopher");

printf("\n\t philosopher state");

for(i=0;i<5;i++)

printf("\n\n\t%d\t%c\t",i+1,state[i]);

while(opt<3)

printf("\n\tMenu\n1.hungry\n2.thinking\n3.exit\n");

scanf("%d",&opt);

switch(opt)

[40]
{

case 1:

printf("\n\t enter which is philosopher is hungry");

scanf("%d",&n);

take(n-1);

break;

case 2:

printf("Thinking");

scanf("%d",&n);

drop(n-1);

break;

if(opt!=3)

printf("\n\n\t\t state of each philosopher \n");

printf("__________");

printf("\n\t\t philosopher no.\t state");

for(i=0;i<5;i++)

printf("\t\t%d\t%c\t\n\n",i+1,state[i]);

OUTPUT:

[cse1@minix ~]$ ./a.out

Dining philosopher problem

Initial state of dining philosopher

philosopher state

[41]
1 t

2 t

3 t

4 t

5 t

Menu

1. Hungry

2. Thinking

3. Exit

Enter which is philosopher is hungry: 3

state of each philosopher

philosopher no. state

1 t

2 t

3 e

4 t

5 t

Menu

1. Hungry

2. Thinking

3. Exit

Thinking

state of each philosopher

philosopher no. state

1 t

[42]
2 t

3 e

4 t

5 t

Menu

1 Hungry

2. Thinking

3. Exit

Enter which is philosopher is hungry4

state of each philosopher

philosopher no. state

1 t

2 t

3 e

4 h

5 t

Menu

1 Hungry

2. Thinking

3.Exit

Thinking

state of each philosopher

philosopher no. state

[43]
1 t

2 t

3 e

4 h

5 t

Menu

1. Hungry

2. Thinking

3. Exit

Enter which is philosopher is hungry 2

state of each philosopher

philosopher no. state

1 t

2 h

3 e

4 h

5 t

Menu

1. Hungry

2. Thinking

3. Exit

[44]
RESULT:

Thus the dining philosopher problem was implemented successfully

EX NO: 9 BANKER’S ALGORITHM.

AIM:

To write a shell program to avoid deadlock using Banker’s Algorithm.

ALOGORITHM:

1. Enter the total number of process to be synchronized using banker’s algorithm.


2. Enter the total number of resources shared by the processes.

3. For each resource i,

3a.enter the number of instances available.(ie)

avail[i]=m,there are m instances of resource i available.

4.For each process j,

4a.enter the maximum resource demand for each process.(ie)

max[j][i]=k,process j may request atmost k resource

instances of the resource type i.

4b.enter the allocated resource instances for each resource

type.(ie)

alloc[j][i]=k,process j is allocated k resource instances of the resource type i.

4c.calculate each processes need of resource instances for each resource type.(ie)

need[j][i]=max[j][i]-alloc[j][i].

5.For each process j and each resource type i,

5a.if need[j][i] >avail[i],

then the sequence of process is not safe.

else, the sequence of process is safe and hence calculate

[45]
alloc[j][i]=alloc[j][i]+need[j][i]

avail[i]=avail[i]-need[j][i]

PROGRAM:

#include<stdio.h>

#include<unistd.h>

struct process

int id,status,max[10],alloc[10],need[10];

};

struct process pro[10];

int available[10];

void alloc(int,int);

main()

int i,j;

int p,r;

int res[10],req[10],rp;

int flag,flag1;

char ch;

printf("\n Enter the number of process:");

scanf("%d",&p);

printf("\n Enter the number of resources:");

scanf("%d",&r);

printf("\n Enter the maximum resources available\n");

for(i=0;i<r;i++)

[46]
scanf("%d",&res[i]);

available[i]=res[i];

printf("\n Enter the maximum resources required by each process\n");

for(i=0;i<p;i++)

pro[i].id=i;

pro[i].status=0;

printf("\n For process P%d\n",i);

for(j=0;j<r;j++)

scanf("%d",&pro[i].max[j]);

printf("\n Enter the allocation values\n");

for(i=0;i<p;i++)

printf("\n For process P%d\n",i);

for(j=0;j<r;j++)

scanf("%d",&pro[i].alloc[j]);

for(i=0;i<r;i++)

for(j=0;j<p;j++)

available[i]-=pro[j].alloc[i];

printf("\n Available resources \n");

for(i=0;i<r;i++)

printf("\t%d",available[i]);

while(1)

[47]
printf("\n Is there any request:(y/n)");

scanf("%s",&ch);

if(ch=='n')break;

printf("Enter the process No.:");

scanf("%d",&rp);

printf("\nEnter the resource values of request:");

for(i=0;i<r;i++)

scanf("%d",&req[i]);

flag=0;

for(i=0;i<r;i++)

if(req[i]<=available[i])flag++;

if(flag==r)

printf("\nResource have allocate to process p%d",rp);

for(i=0;i<r;i++)

pro[rp].alloc[i]+=req[i];

available[i]-=req[i];

else if(flag!=r)

printf("\n Available resource is lesser than the request");

exit(0);

for(i=0;i<p;i++)

for(j=0;j<r;j++)

[48]
pro[i].need[j]=pro[i].max[j]-pro[i].alloc[j];

printf("\n\n MAXIMUM RESOURCE REQUIRED");

for(i=0;i<p;i++)

printf("\nP%d",pro[i].id);

for(j=0;j<r;j++)

printf("\t%d",pro[i].max[j]);

printf("\n\nRESOURCE ALLOCATION\n");

for(i=0;i<p;i++)

printf("\nP%d",pro[i].id);

for(j=0;j<r;j++)

printf("\t%d",pro[i].alloc[j]);

printf("\n\nNEED\n");

for(i=0;i<p;i++)

printf("\nP%d",pro[i].id);

for(j=0;j<r;j++)

printf("\t%d",pro[i].need[j]);

printf("\n\nAVAILABLE RESOURCES\n");

for(i=0;i<r;i++)

printf("\t%d",available[i]);

for(i=0;i<p;i++)

allo(r,p);

flag1=0;

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

if(pro[i].status==1)

flag1++;

if(flag1==p)

printf("\n System is in safe state\n");

else if(flag1!=p)

printf("\n System is in unsafe state\n");

void allo(int r,int p)

int i,j,flag;

for(i=0;i<p;i++)

flag=0;

if(pro[i].status==0)

for(j=0;j<r;j++)

if(pro[i].need[j]<=available[j])

flag++;

if(flag==r)

pro[i].status=1;

printf("\n\n\nP%d is executed\nAfter execution",i);

for(j=0;j<r;j++)

available[j]+=pro[i].alloc[j];

printf("\nAvailable resource is");

for(j=0;j<r;j++)

printf("\t%d",available[j]);

break;

[50]
}

OUTPUT:

[cse1@minix ~]$ ./a.out

Enter the no of process : 5

Enter the no of resources :3

Enter the maximum resources available : 10 5 7

Enter the maximum resources required by each process

For process p0

753

For process p1

322

For process p2

902

For process p3

222

For process p4

433

Enter the allocation values

For process p0

010

For process p1

200

For process p2

302

For process p3

[51]
211

For process p4

002

Available resources

3 3 2

Is there any request :(Y/N) n

Maximum resource required

P0 7 5 3

P1 3 2 2

P2 9 0 2

P3 2 2 2

P4 4 3 3

Resource Allocation

P0 0 1 0

P1 2 0 0

P2 3 0 2

P3 2 1 1

P4 0 0 2

Need

P0 7 4 3

P1 1 2 2

P2 6 0 0

P3 0 1 1

P4 4 3 1

Available Resources

3 3 2

P1 is executed

[52]
After execution
Available resource is 5 3 2

P3 is executed
After execution
Available resource is 7 4 3

P0 is executed
After execution
Available resource is 7 5 3

P2 is executed
After execution
Available resource is 10 5 5

P4 is executed
After execution
Available resource is 10 5 7
System is in safe state

[53]
RESULT:

Thus the deadlock avoidance using banker’s algorithm was executed successfully

EX NO: 10 DEKKER’S ALGORITHM

AIM:

To write a shell program to solve mutual exclusion problem by using Dekker’s Algorithm

ALGORITHM:

1. Start the program.

2. The mutual exclusion requirement is assured.

3. Every process checks the other flag after setting its own. If both are set, the turn variable is used to allow only one
process to proceed.

4. The trun variable is only considered when both processes are using, or trying to use, the resource.

5. The process with the turn will (eventually) discover the other flag free and will proceed.

6. Stop the program.

PROGRAM:

#include<stdio.h>

#include<sys/ipc.h>

#include<sys/shm.h>

void dekker_start(int *s2,int i)

int j=1-i;

s2[i]=1;

while(s2[j])

if (s2[2]==j)

s2[i]=0;

while(s2[2]==j);

[54]
s2[i]=1;

void dekker_exit(int *s2,int i)

int j=1-i;

s2[2]=j;

s2[i]=0;

void read_string(char *s1,char tmp[],int in)

int i=0;

do

tmp[i++]=s1[in++];

while(s1[in-1]!='\0');

void write_string(char *s1,char tmp[],int in)

int len,i;

len=strlen(tmp);

for(i=0;i<len;i++)

s1[in++]=tmp[i];

s1[in++]='\0';

void swap(char tmp[])

[55]
{

int len,i;

char t;

len=strlen(tmp);

for(i=0;i<len-1;i+=2)

if(tmp[i]!='\0')

t=tmp[i];

tmp[i]=tmp[i+1];

tmp[i+1]=t;

void reverse(char tmp[])

int len,i,j=0;

char t[20];

len=strlen(tmp);

for(i=len-1;i>=0;i--)

t[j++]=tmp[i];

t[j]='\0';

strcpy(tmp,t);

main()

char *s1;

int *s2;

[56]
char tmp[20];

int id1,id2,pid,i,j,in=0,inptr=0,cnt=0,n;

printf("\Enter the total no of strings:");

scanf("%d",&n);

id1=shmget(IPC_PRIVATE,50*sizeof(char),0700|IPC_CREAT|IPC_EXCL);

if(id1==-1)

printf("Error in shared memory 1 get \n");

exit(1);

id2=shmget(IPC_PRIVATE,4*sizeof(int),0700|IPC_CREAT|IPC_EXCL);

if(id2==-1)

printf("Error in shared memory 2 get \n");

exit(1);

s1=(char *)shmat(id1,NULL,0700);

if(s1==(char *)-1)

printf("Error in shared memory 1 attach \n");

exit(1);

s2=(int *)shmat(id2,NULL,0700);

if(s2==(int *)-1)

printf("Error in shared memory 2 attach \n");

exit(1);

[57]
s2[0]=0;

s2[1]=0;

s2[2]=0;

printf("\n\tEnter the strings\n");

printf("\n\t--------------------\n");

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

printf("\n Enter the strings %d :",i);

scanf("%s",tmp);

for(j=0;j<strlen(tmp);j++)

s1[in]=tmp[j];

in++;

s1[in]='\0';

in++;

printf("\n\tCHILD PROCESS(p1) (reverse the string)\n");

pid=fork();

if(pid!=0)

printf("\n\t PARENT PROCESS(P0) (Swapping characters)\n");

do

dekker_start(s2,0);

read_string(s1,tmp,inptr);

swap(tmp);

write_string(s1,tmp,inptr);

[58]
read_string(s1,tmp,inptr);

printf("\t%s\n",tmp);

inptr=inptr+strlen(tmp)+1;

dekker_exit(s2,0);

cnt++;

while(cnt!=n);

wait(&i);

cnt=0;

in=0;

do

read_string(s1,tmp,in);

in=in+strlen(tmp)+1;

cnt++;

}while(cnt!=n);

if(shmdt(s1)==-1)

printf("Errors in shared memory 1 detach\n");

exit(1);

if(shmdt(s2)==-1)

printf("Errors in shared memory 2 detach\n");

exit(1);

if(shmctl(id1,IPC_RMID,0)==-1)

[59]
{

printf("Errors in shared memory 1 deletion\n");

exit(1);

if(shmctl(id2,IPC_RMID,0)==-1)

printf("Errors in shared memory 2 deletion\n");

exit(1);

else

do

dekker_start(s2,1);

read_string(s1,tmp,inptr);

reverse(tmp);

write_string(s1,tmp,inptr);

read_string(s1,tmp,inptr);

printf("\t%s\n",tmp);

inptr=inptr+strlen(tmp)+1;

dekker_exit(s2,1);

cnt++;

while(cnt!=n);

[60]
OUTPUT:

[vtu1011@minix ~]$ ./a.out

Enter the total no of strings:3

Enter the strings

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

Enter the strings 0 :apple

Enter the strings 1 :orange

Enter the strings 2 :mango

CHILD PROCESS(p1) (reverse the string)

elppa

egnaro

ognam

PARENT PROCESS(P0) (Swapping characters)

leppa

geanor

goanm

[vtu1011@minix ~]$

[61]
RESULT:

Thus the Dekker’s algorithm was implemented successfully.

EX NO: 11 FIFO - PAGE REPLACEMENT ALGORITHM

AIM:

To implement FIFO page replacement algorithm for the given reference string.

ALGORITHM:

FIFO page replacement algorithm replaces the oldest page that is brought into memory.

1. Enter the number of page frames in main memory.

2. Enter the number of pages in the reference string.

3. Enter each page in the reference string.

4. The frames are initially considered empty.


     For each page in the reference string check availability in the page frame
         if page is not present,
                       Increment page fault.
                       Replace the oldest page brought into memory

5.Print the page frame allocation of the reference string for each iteration.

6. Print the number of page faults for the reference string.

PROGRAM:

#include <stdio.h>

int main()

int main_mem,cur=0,i,j,fault,page[100],page_mem[100],flag,num;

for(i=0;i<100;i++)

page_mem[i]=-2;

printf("\n\n Enter No of Pages in main memory:");

scanf("%d",&main_mem);

printf("\n Enter no of page refernces:");

[62]
scanf("%d", &num);

for(i=0;i<num;i++)

printf("\n Enter page reference: ");

scanf("%d", &page[i]);

printf("\n\t\tFIFO Paging\n\n");

for(i=0;i<main_mem;i++)

printf("\tpage %d", i+1);

for(i=0;i<num;i++)

for(j=0;j<main_mem; j++)

if(page[i]==page_mem[j])

flag=1;

break;

if(!flag)

page_mem[cur]=page[i];

fault++;

printf("\n\n");

for (j=0;j<main_mem;j++)

printf("\t%d", page_mem[j]);

printf("\n\n");

if(!flag &&cur<main_mem-1)

cur++;

[63]
else if(!flag)

cur=0;

flag=0;

printf("\n\n No of page faults: %d", fault);

OUTPUT:

[vtu1011@minix ~]$ ./a.out

Enter No of Pages in main memory:3

Enter no of page refernces:10

Enter page reference: 1

Enter page reference: 2

Enter page reference: 3

Enter page reference: 1

Enter page reference: 2

Enter page reference: 3

[64]
Enter page reference: 4

Enter page reference: 5

Enter page reference: 6

Enter page reference: 7

FIFO Paging

page 1 page 2 page 3

1 -2 -2

1 2 -2

1 2 3

1 2 3

1 2 3

1 2 3

4 2 3

4 5 3

4 5 6

7 5 6

No of page faults: 7 [vtu1011@minix ~]$

[65]
RESULT:

Thus the page replacement algorithm was executed successfully.

Ex .No : 12 MEMORY ALLOCATION TECHNIQUES

AIM:

To implement first fit and best fit memory allocation algorithm

ALGORITHM:

First fit Placement Algorithm :

First fit placement algorithm allocates the first free block in main memory the process fits

1.Enter the number of free blocks, the base address & block size of each block in the main memory.

2.Enter the size of the process to be fitted.

3.For each i free block in memory

If block size[i] >= process size

block size[i] -=process size; block address[i] +=process size

Best fit Placement Algorithm:

Best fit placement algorithm searches the entire list of free blocks in main memory and allocates the smallest free
block that is big enough for the process to be fitted.

1.Enter the number of free blocks,the base address & block size of each block in the main memory.

2.Enter the size of the process to be fitted.

3.Sort the free blocks in the ascending order of the block size.

4.For each i free block in memory

If block size[i] >= process size

block size[i] -=process size; block address[i] +=process size

PROGRAM:

#include<unistd.h>

struct process

int size,status,allo;

[66]
}p[10];

struct partition

int id,size,status,frag;

}pa[10];

int pro,part;

int frag1=0;frag2=0,frag3=0;

void first();

void best();

void worst();

void getdata();

void reset();

main()

int n;

printf("\n Enter the number of Partition :");

scanf("%d",&part);

printf("\n Enter the number of process :");

scanf("%d",&pro);

getdata();

do

printf("\n1-First Fit \n2-Best Fit \n3-Worst Fit\n");

printf("\n Enter your choice :");

scanf("%d",&n);

if(n==1)

first();

else if(n==2)

[67]
best();

else if(n==3)

worst();

}while(n <=3);

if(frag1<frag2)

if(frag1<frag3)

printf("\n\n First Fit Is efficient\n\n");

else

printf("\n\n Worst Fit is efficeinet\n\n");

else

if(frag2<frag3)

printf("\n\n Best Fit is efficient\n\n");

else

printf("\n\n worst fit is efficient\n\n");

void getdata()

int i,k;

printf("\n Enter the process Size\n");

for(i=0;i<pro;i++)

printf("\n Size of %d process :" ,i);

scanf("%d",&p[i].size);

p[i].status=0;

printf("Enter the partition size\n");

for(k=0;k<part;k++)

[68]
printf("\n size of %d partition :" ,k);

scanf("%d",&pa[k].size);

pa[k].id=k;

pa[k].status=0;

pa[k].frag=0;

void reset()

int i;

for(i=0;i<pro;i++)

p[i].status=0;

p[i].allo=-1;

for(i=0;i<part;i++)

pa[i].status=0;

pa[i].frag=-1;

void first()

int i,j;

for(i=0;i<pro;i++)

for(j=0;j<part;j++)

if((p[i].status==0) && (pa[j].status==0) && (p[i].size<=pa[j].size))

[69]
{

p[i].status=1;

pa[j].status=1;

pa[j].frag=pa[j].size-p[i].size;

p[i].allo=pa[j].id;

break;

frag1=0;

for(i=0;i<part;i++)

if (pa[i].status==1)

frag1+=pa[i].frag;

else if(pa[i].status==0)

frag1+=pa[i].size;

printf("\n First Fit\n");

printf("\n process Process Size Partition Partitionsize\n");

for(i=0;i<pro;i++)

if(p[i].status==1)

printf("\n\t%d\t%d\t\t%d\t%d",(i),p[i].size,p[i].allo,pa[p[i].allo].size);

for(i=0;i<pro;i++)

if(p[i].status==0)

printf("\n\n There is no space to allocate p%d",i);

printf("\n\n Total fragmentation: %d\n",frag1);

reset();

void best()

[70]
{

struct partition t[10];

int min, t1,t2;

int i,j;

for(i=0;i<part;i++)

t[i].id=pa[i].id;

t[i].size=pa[i].size;

t[i].status=0;

t[i].frag=0;

for(i=0;i<part;i++)

for(j=0;j<=(part-1);j++)

if(t[j].size>t[j+1].size)

t1=t[j].size;

t[j].size=t[j+1].size;

t[j+1].size=t1;

t2=t[j].id;

t[j].id=t[j+1].id;

t[j+1].id=t2;

for(i=0;i<pro;i++)

for(j=0;j<part;j++)

if((p[i].status==0)&&(t[j].status==0)&&(p[i].size<=t[j].size))

[71]
{

p[i].status=1;

t[j].status=1;

t[j].frag=t[j].size-p[i].size;

p[i].allo=j;

break;

frag2=0;

for(i=0;i<part;i++)

if(t[i].status==1)

frag2 +=t[i].frag;

else if(pa[i].status==0)

frag2=t[i].size;

printf("\n Best Fit \n");

printf("\n Process process Size Segmentation Segmentation Size\n");

for(i=0;i<pro;i++)

if(p[i].status==1)

printf("\n\t%d\t%d\t\t%d\t%d",i,p[i].size,t[p[i].allo].id,t[p[i].allo].size);

for(i=0;i<pro;i++)

if(p[i].status==0)

printf("\n\n There is no space to allocate p%d",i);

printf("\n\nTotal fragmentation : %d\n",frag2);

reset();

void worst()

[72]
{

struct partition t[10];

int min,t1,t2;

int i,j;

for(i=0;i<part;i++)

t[i].id=pa[i].id;

t[i].size=pa[i].size;

t[i].status=0;

t[i].frag=0;

for(i=0;i<part;i++)

for(j=0;j<(part-1);j++)

if(t[j].size<t[j+1].size)

t1=t[j].size;

t[j].size=t[j+1].size;

t[j+1].size=t1;

t2=t[j].id;

t[j].id=t[j+1].id;

for(i=0;i<pro;i++)

if((p[i].status==0)&&(t[j].status==0)&&(p[i].size<=t[j].size))

p[i].status=1;

t[j].status=1;

t[j].frag=t[j].size-p[i].size;

[73]
p[i].allo=j;

break;

frag3=0;

for(i=0;i<part;i++)

if(t[i].status==1)

frag3+=t[i].frag;

else if(pa[i].status==0)

frag3+=t[i].size;

printf ("\n Worst Fit\n");

printf("\n Process process Size Segmentation Segmentation Size\n");

for(i=0;i<pro;i++)

if(p[i].status==1)

printf("\n\t%d\t%d\t\t%d\t%d",i,p[i].size, t[p[i].allo].id,t[p[i].allo].size);

for(i=0;i<pro;i++)

if(p[i].status==0)

printf("\n\n There is no space to allocate p%d",i);

printf("\n\nTotal fragmentation : %d\n",frag3);

reset();

OUTPUT:

[exam1@localhost ~]$ ./a.out

Enter the no of partition :5

Enter the no of process :4

Enter the process size

[74]
Size of 0 process :212

Size of 1 process :417

Size of 2 process :112

Size of 3 process :426

Enter the partition size

Size of 0 partition: 100

Size of 1 partition: 500

Size of 2 partition: 200

Size of 3 partition: 300

Size of 4 partition: 600

1 – First Fit

2 – Best Fit

3 – Worst Fit

Enter ur choice :1

First Fit

Process process size partition partition size

0 212 1 500

1 417 4 600

2 112 2 200

There is no space to allocate p3

Total fragmentation: 959

1 – First Fit

2 – Best Fit

3 – Worst Fit

Enter ur choice :2

Best Fit

Process process size segmentation segmentation size

0 212 3 300

[75]
1 417 1 500

2 112 2 200

3 426 4 600

Total fragmentation: 533

1 – First Fit

2 – Best Fit

3 – Worst Fit

Enter ur choice :3

Worst Fit

Process process size segmentation segmentation size

0 212 4 600

1 417 1 500

2 112 3 300

There is no space to allocate p3

Total fragmentation: 959

1 – First Fit

2 – Best Fit

3 – Worst Fit

Enter ur choice :4

Best fit is efficient

[76]
RESULT:

Thus the memory allocation technique was executed successfully.

Ex No: 13(a) PAGING

AIM
To simulate paging by writing a c program using LINUX.

ALGORITHM
1. Start the program

2. Declare the variables.

3. Get the page table values.

4. Get the page size, page number and the value for displacement.

5. Calculate the physical address and display it.

6. Terminate the program.

PROGRAM:

#include<stdio.h>

main()

int i,f,d,ps,pn,pt[4][2],pa,x;

printf("enter the page table values\n");

printf("i f\n");

for(i=1;i<=4;i++)

for(f=1;f<=2;f++)

#include<stdio.h>

main()

int i,f,d,ps,pn,pt[4][2],pa,x;

printf("enter the page table values\n");

[77]
printf("i f\n");

for(i=1;i<=4;i++)

for(f=1;f<=2;f++)

scanf("%d",&pn);

pt[i][f]=pn;

printf("**********\n");

printf("Enter the page size \n");

scanf("%d",&ps);

printf("Enter the diplacement\n");

scanf("%d",&d);

printf("Enter the page no \n");

scanf("%d",&pn);

for(i=1;i<=4;i++)

if(pn==pt[i][1])

x=pt[i][2];

pa=(ps*x)+d;

printf("pa=(%d*%d)+%d \n", ps,x,d);

printf("\n Physical Address: %d \n",pa);

[78]
OUTPUT:

[exam1@localhost ~]$ ./a.out

enter the page table values

i f

1 5

2 6

3 4

4 1

**********

Enter the page size

Enter the diplacement

Enter the page no

pa=(3*5)+2

Physical Address: 17

pa=(3*3)+2

Physical Address: 11

[exam1@localhost ~]$

[79]
RESULT:

Thus the Linux kernel program to simulate paging was executed successfully.

Ex No: 13(b) SEGMENTATION

AIM
To write a c program to simulate segmentation using LINUX.

ALGORITHM
1.Get the number of entities in the segment table.
2. Get the values for segment table, ie seg-no, limit, base.
3. Get the segment number.
4. If it is valued get the byte to be referenced and that byte is within the limit, then
physical address is calculated.
5. If that byte is not within the limit, then print “ cannot refer this address”.
6. If the segment no is not valid then print “ Invalid segment no”.
7. Stop the program.

PROGRAM
#include<stdio.h>

main()

int n,x,y,sc,pa,ba,ab,li,b[10],l[10],i[10],j;

y=-1;

printf("Enter the no of entries in segment table \n");

scanf("%d", &n);

printf("Segno-limit base \n");

for(x=0;x<n;x++)

scanf("%d", &i[x]);

scanf("%d", &l[x]);

scanf("%d", &b[x]);

printf("Enter the segment no \n");

scanf("%d", &sc);

[80]
for(j=0;j<n;j++)

if(i[j]==sc)

y=1;

ba=b[j];

li=l[j];

}}

if(y<0)

printf("Invalid Seg no \n");

exit(0);

printf("Enter the byte to be referenced \n");

scanf("%d", &ab);

if(ab>li)

printf("Cannot reference this address \n");

printf("limit only %d",li);

exit(0);

pa=ba+ab;

printf("The physical address is \n");

printf("%d\n",pa);

[81]
OUTPUT
[staff@linux-router staff]$ ./a.out

Enter the no of entries in segment table

Segno-limit base

1 100 50

2 200 160

3 500 470

4 1400 920

Enter the segment no

Enter the byte to be referenced

100

The physical address is

260

[staff@linux-router staff]$ .

RESULT:

Thus the Linux kernel program to simulate segmentation was executed successfully.

[82]

You might also like