unix lab m

52
Ex.No:1 UNIX COMMANDS Introduction: The UNIX operating system developed at Bell laboratories are among the notable success in the field of operating system. UNIX system provides a friendly environment for program development and text processing. They make it easy to combine programs with one another. This encourages a modular total oriented building block approach to program design. BASIC UNIX COMMANDS 1. date command: The date command tells us the current date and time Format: $date 2. who command: This command gives us the details of who have logged into the Unix System. Format: $who $who am i which tells us to when we had logged in and the system name for connection being used 3. man command: This command prints manual page Format: 1

Upload: legy86

Post on 02-Apr-2015

268 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: UNIX Lab M

Ex.No:1 UNIX COMMANDS

Introduction:

The UNIX operating system developed at Bell laboratories are among the notable

success in the field of operating system. UNIX system provides a friendly environment

for program development and text processing. They make it easy to combine programs

with one another. This encourages a modular total oriented building block approach to

program design.

BASIC UNIX COMMANDS

1. date command:

The date command tells us the current date and time

Format:

$date

2. who command:

This command gives us the details of who have logged into the Unix

System.

Format:

$who

$who am i

which tells us to when we had logged in and the system name for connection

being used

3. man command:

This command prints manual page

Format:

$man<command name>

Example:

$man who

Usage of Directory commands:

1. pwd command:

It tells us the full path from the current directory

Format:

$pwd

1

Page 2: UNIX Lab M

2. ls command:

The ls command displays the list of files in a current directory

Format:

$ls

The ls command comes with different options. Some of them are given here,

ls-l List files in login format. The files are displayed along with there mode, number

of links, owner of files, file size, modification date and time of file name

ls-t List in order of last modification time(most recent file)

ls-a List all entries, including hidden files

ls-b List directory files instead of contents

ls-p Put a slash after each directory

ls-u List in order of last access time

3. mkdir command :

This command helps us to make a directory

Format:

$mkdir <directory name>

Example: mkdir cape

4. cd Command:

This command helps us to change from working directory to any other directory

specified

Example: Assume that you are working in the directory path/user/you

$mkdir book This makes a new directory

$cd book Used to change the directory

$pwd Go to it

/user/you/book

$cd.. This is used to move up one level in file system.

$cd..

$pwd

/user/you

$cd This helps to return to home directory.

2

Page 3: UNIX Lab M

5. rmdir Command:

This command is used to remove a directory specified in the command .

Format: $rmdir<directory name>

Example: $rmdir book

Usage of file command :

1) cat command:

This command helps us to count the content of the file we specify. If we don’t

specify the name of the file ,it takes input from standard input.

Format : $cat [path] filename

Example: $cat xyz

Example: $cat cape1

Have a nice day

Ctrl+l

2) cp Command:

This command helps us to create the copies of a ordinary file.

Format : $cp[path]sourcefilename[path]destinatiosnfilename

Example: $cp cape1 cape2

3) ln Command:

This command is used to establish a additional filename for the same directory file.

Format : $ln oldfilename new filename

Example: $ln cape1 cape2

4) mv Command:

This command is used to move the contents from one file to another file.

Format : $mv Source Destination

Example: $mv cape1 cape2

5) rm Command:

This command is used to remove one or more files from a directory. This can be

used to delete all file as well as the directory.

Format: $rm [path] file

6) echo Command:

This command is used to display on the screen.

3

Page 4: UNIX Lab M

Format : $echo “Message”

Example: $echo “UNIX”

UNIX

7) read Command:

This command is used in shell script. This command waits for the user to in pact

the value of the variable.

Format : $read variable name

Important Keys to Remember:

Enter Key -Execute command in the escape model & start a new line in the insert

mode.

Esc Key -Return the vi editor to the command mode.

“/” -Helps to search for a particular string with in the file.

“?” -Works the same way as “/”

“:” -Used when we want to specify a command.

Three modes:

1) Esc mode.

2) Insert mode.

3) Command mode.

Esc mode:

Movement of the Cursor:

h or backspace:left

l or spacebar :right

k or - :up

j or + :down

Some More Cursor Movements:

w - Moves forward by word.

b - Moves backward by word.

e - Last character of the word.

^ - Beginning of the line.

$ - End of the line.

L - Last line of the file.

4

Page 5: UNIX Lab M

Screen Commands:

Ctrl+F - moves forward direction by screen.

Ctrl+B - moves backward direction of the screen.

Ctrl+D - moves the cursor half of the screen in backward direction.

Ctrl+U - moves the cursor half of the screen in forward direction.

i/I - change to insert mode.

Insert mode:

I - invokes insert mode and insertion takes place at the beginning.

a - used for appending the text. Text is appended after the cursor position.

A - Used for appending the text. Text is appended at back end of the line.

O - Allows insertion by creating a blank line above the current line.

o - Allows insertion by creating a blank line below the current line.

R - It overwrites from current cursor position.

Command mode:

Esc+: -change to command mode.

Deleting data:

:u - undo all commands used in command prompt.

:set number - set the line number.

:2Jo - used to join operation.

:2co7 - second line is copied after seventh line.

:1,3co8 - first,second,third lines are copied after eighth line.

:3mo7 - move third line after seventh line.

:2d - to delete the second line.

:2,5d - to delete the set of lines.(2,3,4&5)

How to quit vi editor:

:q! - quit without writing the changes into disk file.

:wq - quit after writing the changes to the disk file.

Esc mode-deleting datas:

dd - delete the line in which cursor position.

dw - delete the single word.

x/del - to delete the single character at the cursor position.

X - delete the single character before the cursor position.

5

Page 6: UNIX Lab M

Ex.no:2 SIMULATION OF UNIX COMMAND (COPY)

AIM:

To write a c program to simulate the existing UNIX command (copy) using

system calls. Operating System (OS) LAB in LINUX environment

PROGRAM DESCRIPTION:

In this program we have to unit a c program that simulates the copy command

for moving an existing file into a new file. In this program three system calls

are used.

System calls used,

· open()

· close()

· create()

· read()

· write()

1. open ()

Syntax:

open(filename,int mode)

This system calls open the file specified in the syntax according to the mode of

operation given. The mode of operation here include

RDONLY WRONLY

RDWR

APPEND

6

Page 7: UNIX Lab M

ALGORITHM:

· Declare the argument counter and argument vector array (argc,argv).

· if argc<2>3, then display that the move command operation cannot be

performed.

· if argc==3, string compare argv[2] with “- I”. if it is true moves into the

interactive mode.

· Check whether the file in argv[1] exists using system call access.

· Unlink the file in argv[1] and check for error condition.

· if argc==2, then check whether the file in argv[1] exists using system call

‘access’.

· Unlink the file in argv[1] and check for error condition.

· if the file in argv[1] does not exist the exit the program.

PROGRAM SOURCE CODE

# include<stdio.h>

# define PERROR -1

main(argc ,argv)

int argc;

char *argv[];

{

char op;

7

Page 8: UNIX Lab M

if((argc<3)(argc>4))

{

fprintf(stderr,"ERROR");

exit(1);

}

if(argc==4)

{

printf("\n Are you sure to move the file (y/n)");

scanf("%c",&op);

if(tolower(op)==’y’)

{

if(link(argv[1],argv[2])==PERROR)

{

Perror(argv[0]);

}

if(unlink(argv[1]==PERROR)

{

Perror(argv[1]);

}

}

else

{

else(1);

}

if(argc==3)

{

if(link(argv[1],argv[2])==PERROR)

{

Perror(argv[1]);

8

Page 9: UNIX Lab M

}

}

Else

{

exit(1);

}

}

if(argc==3)

{

if(link(argv[1],argv[2])==PERROR)

{

Perror(argv[1]);

}

}

exit(1);

}

CONCLUSION:

Thus the c programs to simulate the existing UNIX command (CCPY) using

the available system calls was written and executed successfully.

9

Page 10: UNIX Lab M

Ex.no:3 Get Process ID

Aim:

To write a C program to perform the system call to get the process ID.

Algorithm:

1. Start the program.

2. Using the main function print the hello world from the process ID.

3. Using the function getpid() print the processed.

4. If the value is not valid, exit from the main function.

5. Display the result.

6. Stop the execution.

Program:

#include<stdio.h>

int main(void)

{

printf(“hello world from process ID %d \n”, getpid());

exit(0);

}

10

Page 11: UNIX Lab M

Ex.no:4 Get Information about file

Aim:

To write a C program to get the information about file using UNIX Operating

System.

Algorithm:

1. Start the program

2. Declare the buffer status using structures.

3. Check the file which is given as input is found or not.

4. If it is exists then print the status of the file.

5. If it is less than zero then print file not found.

6. Stop the execution.

Program

#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>main(int argc, char **argv){

int i; struct stat buf; int exists; printf("\tSIZE \t USERID \t FILE NAME\n"); for (i = 1; i < argc; i++) {

exists = stat(argv[i], &buf); if (exists < 0)

{ fprintf(stderr, "%s not found\n", argv[i]);

} else

{ printf("\t%ld \t%d\t %s\n", buf.st_size,buf.st_uid, argv[i]);

} }

}

11

Page 12: UNIX Lab M

Ex.no:5 Open and Read All Directories

Aim:

To write a C program to perform open and read all directories using UNIX

Operating Systems.

Algorithm:

1. Start the program

2. Declare the buffer status and directory as a structure.

3. Get the lists of directory names.

4. Print the status of the file which is present in the login.

5. If not, print the directory does not exist.

6. Stop the execution.

Program

#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<dirent.h>main(int argc,char **argv){

struct stat buf; int exists; DIR *d; struct dirent *de;d = opendir(".");if (d == NULL) {

fprintf(stderr,"DIR does not exit\n"); exit(1);

}printf("filename \t\t Size\n");

for (de = readdir(d); de != NULL; de = readdir(d)) {

exists = stat(de->d_name, &buf); if (exists < 0)

{ fprintf(stderr, "%s not found\n", de->d_name);

}else{

printf("%s\t\t %ld\n", de->d_name, buf.st_size); }

} }

12

Page 13: UNIX Lab M

Ex.no:6 Open and Read A Directory

Aim:

To write a C program to perform open and read a directory using UNIX Operating

Systems.

Algorithm:

1. Start the program

2. Declare the buffer status and directory as a structure.

3. Get the name of the directory name.

4. Print the status of the file which is present in that directory.

5. If not, print the directory does not exist.

6. Stop the execution.

Program

#include<stdio.h>#include<sys/types.h>#include<sys/stat.h>#include<dirent.h>main(int argc,char **argv){ struct stat buf; int exists; DIR *d; struct dirent *de;

d = opendir(argv[1]); if (d == NULL) {

fprintf(stderr,"DIR does not exit\n"); exit(1);

} printf("filename \t\t Size\n"); for (de = readdir(d); de != NULL; de = readdir(d)) { exists = stat(de->d_name, &buf);

if (exists > 0) { fprintf(stderr, "%s not found\n", de->d_name); }

else{

printf("%s\t\t %ld\n", de->d_name, buf.st_size); } } }

13

Page 14: UNIX Lab M

Ex.no:7 ROCESS MANAGEMENT USING FORK () AND EXECL()

Aim:

To manage the process using fork() and execl() system calls.

ALGORITHM:

· Start program.· System is used to call the child process.· fork() system call is assigned to fd variable.· if fd is equal to -1, then control is passed to main program.· if fd is equal to 0, date and time of child process is printed.· Stop the program.

PROGRAM

#include <stdio.h>void syst();main(){Syst("\bin\date","date");printf("now you are with parent process");return 0;}void syst(s1,s2)char *s1,*s2;{int fd,x;fd =fork();if (fd ==0){printf("now you are with current processs\n");x=execl(s1,s2,0);if(x==-1){perror(s1);}}wait();}

14

Page 15: UNIX Lab M

Ex.no:8 Create Child Process

Aim:

To write a C program for creating the child process in syatem call.

Algorithm:

1. Start the program

2. Get the pid value. Print the process for parent ID using the getpid() function.

3. Then fork another process using pid=fork().

4. If pid is less than zero then display as fork is failed.

5. If pid is equal to zero then display the child process and execute using bin.

6. If step4 and step5 is not valid then execute the parent process and child process as

complete.

7. Stop the execution.

Program

#include<stdio.h>int main(int argc,char *argv[]){int pid;printf("Parent Process ID %d\n",getpid());pid=fork();if(pid<0){fprintf(stderr,"Fork failed");exit(-1);}else if(pid==0){printf("Child process\n");printf("Process ID %d\n",getpid());execlp("/bin/ls","ls",NULL);}else{wait(NULL);printf("Child complete");exit(0);}}

15

Page 16: UNIX Lab M

Ex.no:9 Copying the Content of File

Aim:

To copy the content of a file using UNIX Operating System.

Algorithm:

1. Define variables, buffersize and mode.

2. Create the source with contents.

3. Open the source file in read mode.

4. Create a destination file.

5. Copy the contents of source file into the destination file.

6. Verify the output.

Program:

#include<sys/types.h>#include<fcntl.h>#include<stdlib.h>#include<unistd.h>#define BUFF_SIZE 4096#define MODE 0666main(int argc,char *argv[]){int src,dest,in,out;char buf[BUFF_SIZE];if(argc!=3) exit(1);src=open(argv[1],O_RDONLY);if(src < 0) exit(2); dest=creat(argv[2],MODE);while(1){in=read(src,buf,BUFF_SIZE);if(in <= 0) break; out=write(dest,buf,in);if(out <= 0)break;}close(src);close(dest);exit(0);}

16

Page 17: UNIX Lab M

Ex.no:10 FIRST COME FIRST SERVE SCHEDULING

Aim:

To write a C program in UNIX environment to implement the First Come First

Serve scheduling with arrival time.

Algorithm:

1. Get the number of Processes.

2. Get also the CPU time and arrival time for each process from the user.

3. For each process the waiting time is equivalent to the CPU time of the previous

process.

4. The ratio of waiting time of all the processes to the number process will give the

average waiting time.

5. Display the output.

Program:

#include<stdio.h>#include<string.h>main(){ int p[10],x,at[10],bt[10],wt[10],ft[10],tat[10],i,n; int totw=0,tott=0,awt,atat; printf("\nEnter the no.of process"); scanf("%d",&n); printf("process A.T B.T\n"); for(i=0;i<n;i++) { scanf("%d%d%d",&p[i],&at[i],&bt[i]); } wt[0]=0; ft[0]=at[0]+bt[0]; tat[0]=wt[0]+bt[0]; for(i=1;i<n;i++) { wt[i]=ft[i-1]-at[i]; tat[i]=wt[i]+bt[i]; ft[i]=at[i]+bt[i]+wt[i];

17

Page 18: UNIX Lab M

} printf("\nprocess\tAT\tBT\tWT\tFT\tTAT"); for(i=0;i<n;i++) { printf("\n%d\t%d\t%d\t%d\t%d\t%d\n",p[i],at[i],bt[i],wt[i],ft[i],tat[i]); totw+=wt[i]; tott+=tat[i]; } awt=totw/n; atat=tott/n; printf("\n Average Waiting Time = %d",awt); printf("\n Average turn around Time= %id",atat);

}

18

Page 19: UNIX Lab M

Ex.no:11 ROUND ROBIN SCHEDULING

Aim:

To write a C program in UNIX environment to implement the Round Robin

Scheduling.

Algorithm:

1. Get the number of Processes.

2. Get also the Process time and arrival time for each process from the user.

3. For each process the waiting time is equivalent to the CPU time of the previous

process.

4. The ratio of waiting time of all the processes to the number process will give the

average waiting time.

5. Display the output.

Program:

#include<stdio.h>int main(){ int proc[20]; int n,i,j,k,exe[20],texe[20],quantum,cycle[20]; int tempwt=0; float avg=0,wait[20],wt=0,twt=0; int next=0,exec; printf("\n---ROUND ROBIN SCHEDULING-----\n"); printf("\n Enter the no of process:"); scanf("%d",&n); printf("\nEnter the time slice:"); scanf("%d",&quantum); for(i=1;i<=n;i++) { printf("\nEnter the process name:"); scanf("%d",&proc[i]); printf("\nEnter the service time:"); scanf("%d",&exe[i]); printf("\n----------------------------\n"); cycle[i]=1;

19

Page 20: UNIX Lab M

wait[i]=0; texe[i]=0; } for(i=1;i<=n;i++) { printf("\n Process Name:%d",proc[i]); printf("\t\tService Time:%d",exe[i]); } exe[0]=0; k=0; printf("\n Waiting time for each process\n"); do { k=k+1; next=0; exec=quantum; for(i=1;i<=n;i++) { if(cycle[i]==k) { if(exe[i]<quantum) { exec=exe[i]; } else { exec=quantum; } wait[i]=tempwt-texe[i]; texe[i]=texe[i]+exec; tempwt=tempwt+exec; } if(exe[i]>quantum) { cycle[i]=cycle[i]+1; exe[i]=exe[i]-quantum; next=1; } }}while(next==1);for(i=1;i<=n;i++){

20

Page 21: UNIX Lab M

printf("\n Process Name:%d",proc[i]); printf("\t\tWaiting time:%.2f",wait[i]);}for(i=1;i<=n;i++){ twt=twt+wait[i]; avg=twt/n;}printf("\n Average Waiting Time:");printf("%.2f",avg);return(0);}

21

Page 22: UNIX Lab M

Ex.no:12 IMPLEMENTATION OF PRIORITY SCHEDULING

Aim:

To write a C program in UNIX environment to implement the Priority

Scheduling.

Algorithm:

1. Get the no of Processes.

2. Get also the CPU time and Process time, Arrival time and the priority for each

process from the user.

3. Sort the CPU time of the processes according to the process priority in ascending

order.

4. For each process the waiting time is equivalent to the CPU time of the previous

process.

5. The ratio of waiting time of all the processes to the number process will give the

average waiting time.

6. Display the output.

Program:

#include<stdio.h>#include<string.h>main(){

int i,ptime[10],n,k=0,s=0,sum=0;char name[10][10],temp[25];int t,j,t1,prt[25];float awt,att;printf("enter the number of processes:");scanf("%d",&n);for(i=0;i<n;i++){

printf("Enter the name of the process");printf("%d\t",i+1);scanf("%s",name[i]);

}

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

22

Page 23: UNIX Lab M

printf("enter the process time for ");printf("%s\t",name[i]);scanf("%d",&ptime[i]);

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

printf("enter the priority for %s\t",name[i]);scanf("%d",&prt[i]);

}printf("processname\t processtime\t priority\n");for(i=0;i<n;i++){

printf("%s\t\t%d\t\t%d\n",name[i],ptime[i],prt[i]);}for(i=0;i<n;i++){

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

if(prt[i]<prt[j]){

t=prt[i];prt[i]=prt[j];prt[j]=t;t1=ptime[i];ptime[i]=ptime[j];ptime[j]=t1;strcpy(temp,name[j]);strcpy(name[j],name[i]);strcpy(name[i],temp);

}}

}printf("Process NAme\t Process time\t Priority\n");for(i=0;i<n;i++){

printf("%s\t\t%d\t\t%d\n",name[i],ptime[i],prt[i]);}printf("\t PRIORITY SCHEDULING\n");for(i=0;i<n;i++){

printf("Process %s from %d to %d \n\n",name[i],k,(k+ptime[i]));k=k+ptime[i];

}printf("Waiting time\n");for(i=0;i<=(n-1);i++)

23

Page 24: UNIX Lab M

{printf("Waiting time of %s is %d\n",name[i],s);if(i<(n-1)){

s+=ptime[i];sum+=s;

}}awt=(float)sum/n;printf("Average waiting time is:");printf("%2f\n\n",awt);sum=s=0;printf("Turn around time\n");for(i=0;i<n;i++){

s+=ptime[i];sum+=s;printf("Turn around time of %s is %d\n",name[i],s);

}att=(float)sum/n;printf("Average turn around time is ");printf("%2f\n",att);

}

24

Page 25: UNIX Lab M

Ex.no:13 IMPLEMENTATION OF SHORTEST JOB FIRST SCHEDULING

Aim:

To write a C program in UNIX environment to implement the Shortest Job First

Scheduling.

Algorithm:

1. Get the no of Processes.

2. Get also the CPU time and arrival time for each process from the user.

3. Sort the CPU time in ascending order.

4. For each process the waiting time is equivalent to the CPU time of the previous

process.

5. The ratio of waiting time of all the processes to the number process will give the

average waiting time.

6. Display the output.

Program:

#include<stdio.h>int main(){ int process[20];int n,i,j,exe[20],prior[20],temp;float avg=0,wait[20],wt=0,twt=0;printf("\n enter the no of process");scanf("%d",&n);for(i=1;i<=n;i++){ printf("enter the process name");scanf("%d",&process[i]);printf("\n enter the burst time");scanf("%d",&exe[i]);} for(i=1;i<=n;i++){ for(j=i+1;j<=n;j++){

25

Page 26: UNIX Lab M

if(exe[j]<exe[i]){ temp=process[i];process[i]=process[j];process[j]=temp;temp=exe[i];exe[i]=exe[j];exe[j]=temp;}}}for(i=1;i<=n;i++){printf("\n Process name %d",process[i]);printf("\t\t Burst time %d",exe[i]);}exe[0]=0;printf("\n Having time for each process\n");for(i=1;i<=n;i++){ wt=wt+exe[i-1];wait[i]=wt;twt=twt+wt;}for(i=1;i<=n;i++){ printf("\n Process name %d",process[i]);printf("\t\t Waiting time %2f",wait[i]);}avg=twt/n;printf("Average waiting time");printf("%2f",avg);return(0);}

26

Page 27: UNIX Lab M

Ex.no:14 IMPLEMENTATION OF PRODUCER CONSUMER PROBLEM

Aim:

To write a program in UNIX environment to implement Producer Consumer

problem.

Algorithm:

1. Start the program.

2. Initialize a buffer with size two.

3. Enter choice.

4. If the choice is one then enter the item.

5. If choice is two then consumer gets the items from buffer.

6. If the choice is three then exit from the program.

7. Stop the execution.

PROGRAM:

#include<stdio.h>

#include<stdlib.h>

int main()

{

int id,a[2],ch=0,i=0,j,m;

static int p=0;

do

{

printf("\n1.producer");

printf("\n2.consumer");

printf("\n3.quit");

printf("\nEnter choice");

scanf("%d",&ch);

switch(ch)

{

case 1:

printf("\nEnter item");

scanf("%d",&id);

27

Page 28: UNIX Lab M

if(i==2)

printf("\n Buffer is Full\n");

else

a[i++]=id;

printf("\t The Items produced and Entered are:\n");

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

printf("\t item %d:%d\n",j,a[j]);

m=i;

break;

case 2:

if(p==m)

printf("\n There is no item to remove\n");

else

{

id=a[p++];

printf("\n The item removed is %d\n",id);

printf("\n The items are:\n");

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

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

}

break;

case 3:

printf("\n Thank U");

exit(0);

break;

}

}while(ch!=3);return(0);

}

28

Page 29: UNIX Lab M

Ex.no:15 SIMULATION OF PAGING TECHNIQUES

Aim:

To write a C program in UNIX environment to implement the Paging Techniques

such as Best Fit, First Fit, Worst Fit.

Description:

The storage replacement strategies are used to determine where in the main

storage to place incoming program and data. These strategies are commonly used.

1. Best Fit:

An incoming job is placed in the hole in the main storage in which its fits most

lightly and leaves the smallest amount of unused space. It is the commonly used strategy.

2. Worst Fit:

An incoming job is placed in the main storage in the hole in which it fits worst.

After placing the program in the large hole, the remaining hole is large and is thus able to

hold a relatively large new program.

3. First Fit:

An incoming job is placed in the main storage in the first available hole enough to

hold it. This allows the placement decisions to be made quickly.

Algorithm:

1. Consider a matrix and assume each column of that matrix as a page and the

matrix itself as in main memory.

2. Fill elements in each page randomly according to the work of the user.

3. Get the elements to be placed in main memory from the user.

4. For best fit, first place the element where more elements are placed.

5. For worst fit, place the elements where less no of elements are placed.

6. For first fit, place the elements in the first page and so on according to the element

size.

7. Display the matrix on the screen.

29

Page 30: UNIX Lab M

FIRST FIT

#include<stdio.h>int n,fsize[10];void first(int);int main(){ int bsize[10],i,d; int ch,bs; printf("\n****FIRST FIT****"); printf("\nEnter the number of free blocks"); scanf("%d",&n); for (i=0;i<n;i++) { printf("\nEnter the size of %d blocks:",i+1); scanf("%d",&fsize[i]); } for(i=0;i<n;i++) { printf("\nsizeof %d block:|%d|",i+1,fsize[i]); } printf("\nEnter the size of block to be allocated:"); scanf("%d",&bs); first(bs); return(0);}void first(int size){ int i,alloc=0; for(i=0;i<n;i++) { if(size<=fsize[i]) { fsize[i]=fsize[i]-size; alloc=i+1; break; } } if(alloc!=0) { printf("\nAllocated block=%d",alloc); printf("\nAfter allocation\n"); }

30

Page 31: UNIX Lab M

else printf("\n Cannot be allocated:"); for(i=0;i<n;i++) { printf("\nSize of %d block:|%d|",i+1,fsize[i]); } }

BEST FIT

#include<stdio.h>int n,fsize[10];void best(int);int main(){ int bsize[10],i,j; int ch,bs; printf("\n*****BEST FIT*****"); printf("\n Enter the number of free blocks:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the size of %d block:",i+1); scanf("%d",&fsize[i]); } for(i=0;i<n;i++) { printf("\nSize of %d block:|%d|",i+1,fsize[i]); } printf("\nEnter the size of block to be allocated"); scanf("%d",&bs); best(bs); return(0);}void best(int size){ int i,alloc=0,min=fsize[n-1]; for(i=n-1;i>=0;i--) { if(size<=fsize[i]&&fsize[i]<=min) { min=fsize[i]; alloc=i+1; } } if(alloc!=0) {

31

Page 32: UNIX Lab M

printf("\nAllocated block=%d",alloc); fsize[alloc-1]=fsize[alloc-1]-size; printf("\nAfter allocation"); } else printf("\nCannot be allocated"); for(i=0;i<n;i++) { printf("\nSize of %d block:|%d|",i+1,fsize[i]); }}

WORST FIT

#include<stdio.h>int n,fsize[10];void worst(int);int main(){ int bsize[10],i,j; int ch,bs; printf("\n*****WORST FIT*****"); printf("\nEnter the number of free blocks:"); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the size of %d block:",i+1); scanf("%d",&fsize[i]); } for(i=0;i<n;i++) { printf("\nSize of %d block:|%d|",i+1,fsize[i]); } printf("\nEnter the size of block to be allocated"); scanf("%d",&bs); worst(bs); return(0);}void worst(int size){ int i,alloc=0,max=fsize[n-1]; for(i=n-1;i>=0;i--) { if(size<=fsize[i]&&fsize[i]>=max) { max=fsize[i]; alloc=i+1; }

32

Page 33: UNIX Lab M

} if(alloc!=0) { printf("\nAllocated block=%d",alloc); fsize[alloc-1]=fsize[alloc-1]-size; printf("\nAfter allocation"); } else printf("\nCannot be allocated");for(i=0;i<n;i++) { printf("\nSize of %d block:|%d|",i+1,fsize[i]); }}

33

Page 34: UNIX Lab M

Ex.no:16 INTER PROCESS COMMUNICATION

Aim:

34

Page 35: UNIX Lab M

35

Page 36: UNIX Lab M

36

Page 37: UNIX Lab M

Inter process communication between Two process through pipe()

Program

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<sys/uio.h>#include<sys/ipc.h>main(){int pid,pfd[2],a,b,c,i,n,as;if(pipe(pfd)==-1){printf("error in pipe connection.\n ");exit(1);}pid=fork();if(pid!=0){printf("parents process.\n")close(pfd[0]);printf("Enter the number");write(pfd[1,])close(pfd[1]);exit(0);}else{printf("child process.\n");read(pfd[0],&n,sizeof(n));a=0;b=0;i=1;printf("fibanocci series is");printf("%d\t%d\t",a,b);while(i<(n-1)){c=a+b;printf("%d\t",c);a=b;b=c;;i++;}close(pfd[0]);}}

Inter process communication between Three process through pipe()37

Page 38: UNIX Lab M

#include<stdio.h>#include<unistd.h>#include<sys/types.h>#include<sys/uio.h>#include<sys/ipc.h>main(){int pid,int i,n;if(pipe(pfd1)==-1){printf("error in pipe1 ");exit(1);}if(pipe(pfd2)==-1){printf("proces-1");printf("\n error in pipe2 ");exit(1);}pid1=fork();if(pid1==-1){prinf("\n error in fork1.");exit(1);}if(pfd1!=0){printf("process");close(pfd1[10]);printf("\n Enter the element");for(i=0;i<5;i++){scanf("%d",&n);write(pfd1[1],&n,sizeof(n));}close(pfd1[1]);exit(0);}else{printf("\n process2");pid2=fork();if(pid2==-1){printf("\n error in pipe2");exit(1);}close(pfd1[1]);if(pid2!=0){while(read(pfd1[0],&n,sizeof(n))){flag=1;for(i=2;i<(n-1);i++){if(n%i==0)

38

Page 39: UNIX Lab M

{write(pfd2[1],&n,sizeof(n));flag=0;break;}}if(flag==1)printf("\n %d is prime.",n);elseprintf("\n %d is not prime");}close(pfd2[1]);exit(0);}else{close(pfd2[1]);while(read(pfd2[0],&n,sizeof(n)))\{if(n%2==0)printf("\n %d is even.",n);elseprintf("\n %d is odd.",n);}close(pfd2[0]);exit(0);}}

39