You are on page 1of 37

1. Unix C program Implementing the Process system calls.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/wait.h>

int main() {
pid_t forkStatus;

forkStatus = fork();

/* Child... */
if (forkStatus == 0) {
printf("Child is running, processing.\n");
sleep(5);
printf("Child is done, exiting.\n");

/* Parent... */
} else if (forkStatus != -1) {
printf("Parent is waiting...\n");

wait(NULL);
printf("Parent is exiting...\n");

} else {
perror("Error while calling the fork function");

return 0;

Output :
Parent is waiting...
Child is running, processing.
Child is done, exiting.
Parent is exiting...

AAGAC DEPARTMENT OF COMPUTER SCIENCE


2. Unix Program to Implementing I/O system calls.

// C program to illustrate
// open system call
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
extern int errno;
int main()
{
// if file does not have in directory
// then file foo.txt is created.
int fd = open("foo.txt", O_RDONLY | O_CREAT);

printf("fd = %d/n", fd);

if (fd ==-1)
{
// print which type of error have in a code
printf("Error Number % d\n", errno);

// print program detail "Success or failure"


perror("Program");
}
return 0;
}

// C program to illustrate close system Call


#include<stdio.h>
#include <fcntl.h>
int main()
{
int fd1 = open("foo.txt", O_RDONLY);
if (fd1 < 0)
{
perror("c1");
exit(1);
}
printf("opened the fd = % d\n", fd1);

// Using close system Call


if (close(fd1) < 0)
{
perror("c1");
exit(1);
}
printf("closed the fd.\n");

AAGAC DEPARTMENT OF COMPUTER SCIENCE


Output:

opened the fd = 3
closed the fd.

// C program to illustrate close system Call


#include<stdio.h>
#include<fcntl.h>
int main()
{
// assume that foo.txt is already created
int fd1 = open("foo.txt", O_RDONLY, 0);
close(fd1);

// assume that baz.tzt is already created


int fd2 = open("baz.txt", O_RDONLY, 0);

printf("fd2 = % d\n", fd2);


exit(0);
}
Output:
fd2 = 3

// C program to illustrate
// read system Call
#include<stdio.h>
#include <fcntl.h>
int main()
{
int fd, sz;
char *c = (char *) calloc(100, sizeof(char));

fd = open("foo.txt", O_RDONLY);
if (fd < 0) { perror("r1"); exit(1); }

sz = read(fd, c, 10);
printf("called read(% d, c, 10). returned that"
" %d bytes were read.\n", fd, sz);
c[sz] = '\0';
printf("Those bytes are as follows: % s\n", c);
}
Output:
called read(3, c, 10). returned that 10 bytes were read.
Those bytes are as follows: 0 0 0 foo.

AAGAC DEPARTMENT OF COMPUTER SCIENCE


3. Unix C program Implementing IPC using message queues.

IPC_STAT − Copies information of the current values of each member of struct msqid_ds to the passed
structure pointed by buf. This command requires read permission on the message queue.

IPC_SET − Sets the user ID, group ID of the owner, permissions etc pointed to by structure buf.

IPC_RMID − Removes the message queue immediately.

IPC_INFO − Returns information about the message queue limits and parameters in the structure
pointed by buf, which is of type struct msginfo

MSG_INFO − Returns an msginfo structure containing information about the consumed system
resources by the message queue.

 The third argument, buf, is a pointer to the message queue structure named struct msqid_ds. The
values of this structure would be used for either set or get as per cmd.

This call would return the value depending on the passed command. Success of IPC_INFO and
MSG_INFO or MSG_STAT returns the index or identifier of the message queue or 0 for other operations
and -1 in case of failure. To know the cause of failure, check with errno variable or perror() function.

Having seen the basic information and system calls with regard to message queues, now it is time to
check with a program.

Let us see the description before looking at the program −

Step 1 − Create two processes, one is for sending into message queue (msgq_send.c) and another is for
retrieving from the message queue (msgq_recv.c)

Step 2 − Creating the key, using ftok() function. For this, initially file msgq.txt is created to get a unique
key.

Step 3 − The sending process performs the following.

 Reads the string input from the user


 Removes the new line, if it exists
 Sends into message queue
 Repeats the process until the end of input (CTRL + D)
 Once the end of input is received, sends the message “end” to signify the end of the process

AAGAC DEPARTMENT OF COMPUTER SCIENCE


Step 4 − In the receiving process, performs the following.

 Reads the message from the queue


 Displays the output
 If the received message is “end”, finishes the process and exits

To simplify, we are not using the message type for this sample. Also, one process is writing into the
queue and another process is reading from the queue. This can be extended as needed i.e., ideally one
process would write into the queue and multiple processes read from the queue.

Now, let us check the process (message sending into queue) – File: msgq_send.c

/* Filename: msgq_send.c */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define PERMS 0644


struct my_msgbuf {
long mtype;
char mtext[200];
};

int main(void) {
struct my_msgbuf buf;
int msqid;
int len;
key_t key;
system("touch msgq.txt");

if ((key = ftok("msgq.txt", 'B')) == -1) {


perror("ftok");
exit(1);
}

if ((msqid = msgget(key, PERMS | IPC_CREAT)) == -1) {


perror("msgget");
exit(1);
}
printf("message queue: ready to send messages.\n");
printf("Enter lines of text, ^D to quit:\n");
buf.mtype = 1; /* we don't really care in this case */

AAGAC DEPARTMENT OF COMPUTER SCIENCE


while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) {
len = strlen(buf.mtext);
/* remove newline at end, if it exists */
if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';
if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
perror("msgsnd");
}
strcpy(buf.mtext, "end");
len = strlen(buf.mtext);
if (msgsnd(msqid, &buf, len+1, 0) == -1) /* +1 for '\0' */
perror("msgsnd");

if (msgctl(msqid, IPC_RMID, NULL) == -1) {


perror("msgctl");
exit(1);
}
printf("message queue: done sending messages.\n");
return 0;
}

Compilation and Execution Steps

message queue: ready to send messages.


Enter lines of text, ^D to quit:
this is line 1
this is line 2
message queue: done sending messages.

Following is the code from message receiving process (retrieving message from queue) – File:
msgq_recv.c

/* Filename: msgq_recv.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#define PERMS 0644


struct my_msgbuf {
long mtype;
char mtext[200];
};

AAGAC DEPARTMENT OF COMPUTER SCIENCE


int main(void) {
struct my_msgbuf buf;
int msqid;
int toend;
key_t key;

if ((key = ftok("msgq.txt", 'B')) == -1) {


perror("ftok");
exit(1);
}

if ((msqid = msgget(key, PERMS)) == -1) { /* connect to the queue */


perror("msgget");
exit(1);
}
printf("message queue: ready to receive messages.\n");

for(;;) { /* normally receiving never ends but just to make conclusion


/* this program ends wuth string of end */
if (msgrcv(msqid, &buf, sizeof(buf.mtext), 0, 0) == -1) {
perror("msgrcv");
exit(1);
}
printf("recvd: \"%s\"\n", buf.mtext);
toend = strcmp(buf.mtext,"end");
if (toend == 0)
break;
}
printf("message queue: done receiving messages.\n");
system("rm msgq.txt");
return 0;
}

Compilation and Execution Steps

message queue: ready to receive messages.


recvd: "this is line 1"
recvd: "this is line 2"
recvd: "end"
message queue: done receiving messages.

AAGAC DEPARTMENT OF COMPUTER SCIENCE


Operating Systems Types

Single- And Multi-Tasking Operating Systems

A single-tasking system can only run one program at a time, while a multi-tasking
operating system allows more than one program to be running in concurrency. This is achieved by
time-sharing, dividing the available processor time between multiple processes that are each
interrupted repeatedly in time slices by a task-scheduling subsystem of the operating system.

Multi-tasking may be characterized in preemptive and co-operative types. In preemptive


multitasking, the operating system slices the CPU time and dedicates a slot to each of the
programs. Unix-like operating systems, e.g., Solaris, Linux, as well as AmigaOS support
preemptive multitasking.

Single- And Multi-User Operating Systems


Single-user operating systems have no facilities to distinguish users, but may allow
multiple programs to run in tandem. A multi-user operating system extends the basic concept of
multi-tasking with facilities that identify processes and resources, such as disk space, belonging to
multiple users, and the system permits multiple users to interact with the system at the same time.
Time-sharing operating systems schedule tasks for efficient use of the system and may also
include accounting software for cost allocation of processor time, mass storage, printing, and
other resources to multiple users.

Distributed Operating Systems


A distributed operating system manages a group of distinct computers and makes them
appear to be a single computer. The development of networked computers that could be linked
and communicate with each other gave rise to distributed computing. Distributed computations
are carried out on more than one machine. When computers in a group work in cooperation, they
form a distributed system.

Embedded Operating Systems


Embedded operating systems are designed to be used in embedded computer systems.
They are designed to operate on small machines like PDAs with less autonomy. They are able to
operate with a limited number of resources. They are very compact and extremely efficient by
design. Windows CE and “Minix 3”are some examples of embedded operating systems.

AAGAC DEPARTMENT OF COMPUTER SCIENCE


Real-Time Operating Systems
A real-time operating system is an operating system that guarantees to process events or
data by a specific moment in time. A real-time operating system may be single- or multi-tasking,
but when multitasking, it uses specialized scheduling algorithms so that a deterministic nature of
behavior is achieved. An event-driven system switches between tasks based on their priorities or
external events while time-sharing operating systems switch tasks based on clock interrupts.

Process Scheduling
Processes are the Small Programs those are executed by the user according to their Request.
CPU Executes all the Process according to Some Rules or Some Schedule. Scheduling ist hat in
which each process have Some Amount of Time of CPU. Scheduling Provides Time of CPU to the
Each Process.

Types of Process Scheduling

1. FCFS Scheduling Algorithm

The First Come First Served (FCFS) Scheduling Algorithm is the simplest one. In this
algorithm the set of ready processes is managed as FIFO (first-in-first-out) Queue. The processes
are serviced by the CPU until completion in order of their entering in the FIFO queue.

A process once allocated the CPU keeps it until releasing the CPU either by terminating or
requesting I/O. For example, interrupted process is allowed to continujre running after interrupt
handling is done with.

2. SJF Scheduling Algorithm


The Shortest Job First Scheduling Algorithm chooses the process that has the smallest next
CPU burst.

3. SRTF: Shortest Remaining Time First


This is the preemptive version of SJF. The currently executing process will be preempted
from the CPU if a process with a shorter CPU burst time is arrived.

4. Round Robin Scheduling


This scheduling algorithm is designed especially for time sharing systems. It is similar to
FCFS scheduling, but preemption is added to switch between processes.

AAGAC DEPARTMENT OF COMPUTER SCIENCE


AIM: FIRST COME FIRST SERVE SCHEDULING

To write the program to implement CPU & scheduling algorithm for first come first serve scheduling.

ALGORITHM:

1. Start the program.


2. Get the number of processes and their burst time.
3. Initialize the waiting time for process 1 and 0.
4. Process for(i=2;i<=n;i++),wt.p[i]=p[i-1]+bt.p[i-1].
5. The waiting time of all the processes is summed then average value time is calculated.
6. The waiting time of each process and average times are displayed
7. Stop the program.

AAGAC DEPARTMENT OF COMPUTER SCIENCE


PROGRAM : ( FIRST COME FIRST SERVE SCHEDULING)

#include<stdio.h>
struct process
{
int pid; int bt; int wt,tt;
}p[10];

int main()
{
int i,n
float totwt,tottt,avg1,avg2;
clrscr();
printf("enter the no of process \n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("enter the burst time n");
scanf("%d",&p[i].bt);
}

p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n)
{
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
i ++;
}
i=1;
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
totwt=tottt=0;
printf("\n processid \t bt\t wt\t tt\n");
while(i<=n)
{
printf("\n\t%d \t%d \t%d \t%d",p[i].pid,p[i].bt,p[i].wt,p[i].tt); totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
avg1=totwt/n; avg2=tottt/n; printf("\navg1=%f \t avg2=%f\t",avg1,avg2);
getch();
return 0;
}

AAGAC DEPARTMENT OF COMPUTER SCIENCE


OUTPUT:

enter the no of process


3
enter the burst time 2
enter the burst time 4
enter the burst time 6

Process sid bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12

avg1=2.66 avg2=6.22

RESULT:

Thus the FIFO process scheduling program was executed and verified successfully.

AAGAC DEPARTMENT OF COMPUTER SCIENCE


EX.NO:4

DATE: SHORTEST JOB FIRST SCHEDULING

AIM:

To write a program to implement CPU scheduling algorithm for shortest job first scheduling.

ALGORITHM:

Start the program. Get the number of processes and their burst time.
Initialize the waiting time for process 1 as 0.
The processes are stored according to their burst time.
The waiting time for the processes are calculated a follows: for(i=2;i<=n;i++).wt.p[i]=p[i=1]+bt.p[i-1].
The waiting time of all the processes summed and then the average time is calculate
The waiting time of each processes and average time are displayed.
Stop the program.

AAGAC DEPARTMENT OF COMPUTER SCIENCE


PROGRAM: (SHORTEST JOB FIRST SCHEDULING)

#include<stdio.h>
#include<conio.h>
struct process
{

int pid; int bt;


int wt; int tt;
}p[10],temp;

int main()
{
int i,j,n,totwt,tottt;
float avg1,avg2;
clrscr();
printf("\nEnter the number of process:\t");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
p[i].pid=i;
printf("\nEnter the burst time:\t");
scanf("%d",&p[i].bt);
}
for(i=1;i<n;i++)
{
for(j=i+1;j<=n;j++)
{
if(p[i].bt>p[j].bt)
{
temp.pid=p[i].pid;
p[i].pid=p[j].pid;
p[j].pid=temp.pid;
temp.bt=p[i].bt;p[i].bt=p[j].bt;
p[j].bt=temp.bt;
}
}
}

p[1].wt=0;
p[1].tt=p[1].bt+p[1].wt;
i=2;
while(i<=n)
{
p[i].wt=p[i-1].bt+p[i-1].wt;
p[i].tt=p[i].bt+p[i].wt;
i++;
}

DEPARTMENT OF COMPUTER SCIENCE 20


i=1;
totwt=tottt=0;
printf("\nProcess id \tbt \twt \ttt");
while(i<=n)
{
printf("\n\t%d \t%d \t%d t%d\n",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++;
}
avg1=totwt/n; avg2=tottt/n;
printf("\nAVG1=%f\t AVG2=%f",avg1,avg2);
getch();
return 0;
}

OUTPUT:

enter the number of process 3


enter the burst time: 2
enter the burst time: 4
enter the burst time: 6
processid bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12

VG1=2.000000 AVG2=6.000000

RESULT:

Thus the SJF program was executed and verified successfully

DEPARTMENT OF COMPUTER SCIENCE 21


EX.NO:5

DATE:
PRIORITY SCHEDULING
AIM:

To write a ‘C’ program to perform priority scheduling.

ALGORITHM:

Start the program.


Read burst time, waiting time, turn the around time and priority.
Initialize the waiting time for process 1 and 0.
Based up on the priority process are arranged
The waiting time of all the processes is summed and then the average waiting time
The waiting time of each process and average waiting time are displayed based on the priority.
Stop the program.

DEPARTMENT OF COMPUTER SCIENCE 22


PROGRAM: (PRIORITY SCHEDULING)

#include<stdio.h>

int main()
{
int bt[20],p[20],wt[20],tat[20],pr[20],i,j,n,total=0,pos,temp,avg_wt,avg_tat;
printf("Enter Total Number of Process:");
scanf("%d",&n);

printf("\nEnter Burst Time and Priority\n");


for(i=0;i<n;i++)
{
printf("\nP[%d]\n",i+1);
printf("Burst Time:");
scanf("%d",&bt[i]);
printf("Priority:");
scanf("%d",&pr[i]);
p[i]=i+1; //contains process number
}

//sorting burst time, priority and process number in ascending order using selection sort
for(i=0;i<n;i++)
{
pos=i;
for(j=i+1;j<n;j++)
{
if(pr[j]<pr[pos])
pos=j;
}

temp=pr[i];
pr[i]=pr[pos];
pr[pos]=temp;

temp=bt[i];
bt[i]=bt[pos];
bt[pos]=temp;

temp=p[i];
p[i]=p[pos];
p[pos]=temp;
}

wt[0]=0; //waiting time for first process is zero

//calculate waiting time


for(i=1;i<n;i++)
{
wt[i]=0;
DEPARTMENT OF COMPUTER SCIENCE 23
for(j=0;j<i;j++)
wt[i]+=bt[j];

total+=wt[i];
}

avg_wt=total/n; //average waiting time


total=0;

printf("\nProcess\t Burst Time \tWaiting Time\tTurnaround Time");


for(i=0;i<n;i++)
{
tat[i]=bt[i]+wt[i]; //calculate turnaround time
total+=tat[i];
printf("\nP[%d]\t\t %d\t\t %d\t\t\t%d",p[i],bt[i],wt[i],tat[i]);
}

avg_tat=total/n; //average turnaround time


printf("\n\nAverage Waiting Time=%d",avg_wt);
printf("\nAverage Turnaround Time=%d\n",avg_tat);

return 0;
}
OUTPUT:

enter the no of process:3


enter the burst time:2
enter the priority:3
enter the burst time:4
enter the priority:1
enter the burst time:6
enter the priority:2

process to bt wt tt
1 4 0 4 4
2 6 4 10 14
3 2 10 12 22

avg1=4.22 avg2=8.666

RESULT:

Thus the priority scheduling program was executed and verified successfully

DEPARTMENT OF COMPUTER SCIENCE 24


EX.NO:6

DATE:
ROUND ROBIN SCHEDULING
AIM:

To write a program to implement cpu scheduling for Round Robin Scheduling.

ALGORITHM:

Get the number of process and their burst time.


Initialize the array for Round Robin circular queue as ‘0’.
The burst time of each process is divided and the quotients are stored on the round Robin array.
According to the array value the waiting time for each process and the average time are calculated as line
the other scheduling.
The waiting time for each process and average times are displayed.
Stop the program.

DEPARTMENT OF COMPUTER SCIENCE 25


PROGRAM :( ROUND ROBIN SCHEDULING)

PROGRAM :( ROUND ROBIN SCHEDULING)

#include<stdio.h>
#include<conio.h>
struct process
{
int pid,bt,tt,wt;
};

int main()
{
struct process x[10],p[30];
int i,j,k,tot=0,m,n;
float wttime=0.0,tottime=0.0,a1,a2;
clrscr();
printf("\nEnter the number of process:\t");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
x[i].pid=i;
printf("\nEnter the Burst Time:\t");
scanf("%d",&x[i].bt);
tot=tot+x[i].bt;
}
printf("\nTotal Burst Time:\t%d",tot);
p[0].tt=0;
k=1;
printf("\nEnter the Time Slice:\t");
scanf("%d",&m);
for(j=1;j<=tot;j++)
{
for(i=1;i<=n;i++)
{
if(x[i].bt !=0)
{
p[k].pid=i;
if(x[i].bt-m<0)
{
p[k].wt=p[k-1].tt;

DEPARTMENT OF COMPUTER SCIENCE 26


p[k].bt=x[i].bt;
p[k].tt=p[k].wt+x[i].bt;
x[i].bt=0;
k++;
}
else
{
p[k].wt=p[k-1].tt;
p[k].tt=p[k].wt+m;
x[i].bt=x[i].bt-m; k++;
}

}
}
}

printf("\nProcess id \twt \ttt");


for(i=1;i<k;i++)
{
printf("\n\t%d \t%d \t%d",p[i].pid,p[i].wt,p[i].tt);
wttime=wttime+p[i].wt;
tottime=tottime+p[i].tt;
a1=wttime/n;
a2=tottime/n;
}
printf("\n\nAverage Waiting Time:\t%f",a1);
printf("\n\nAverage TurnAround Time:\t%f",a2);
getch();
return 0;
}

OUTPUT:

enter the no of process: 3


enter the burst time 3
enter the burst time 5
enter the burst time 7
total burst time : 15

enter the time slice: 2

process id wt tt
1 0 2
2 2 4
3 4 6
1 6 7

DEPARTMENT OF COMPUTER SCIENCE 27


process id wt tt
2 7 9
3 9 11
2 11 12
3 12 14
3 14 15

avg waiting time: 21.666666


avg turnaround time: 26.666666

DEPARTMENT OF COMPUTER SCIENCE 28


8. Unix Program Implementing pipe processing.

Algorithm

Step 1 − Create a pipe.

Step 2 − Create a child process.

Step 3 − Parent process writes to the pipe.

Step 4 − Child process retrieves the message from the pipe and writes it to the standard output.

Step 5 − Repeat step 3 and step 4 once again.

Source Code: pipewithprocesses.c

#include<stdio.h>
#include<unistd.h>
int main() {
int pipefds[2];
int returnstatus;
int pid;
char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
returnstatus = pipe(pipefds);
if (returnstatus == -1) {
printf("Unable to create pipe\n");
return 1;
}
pid = fork();

// Child process
if (pid == 0) {
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Child Process - Reading from pipe – Message 1 is %s\n", readmessage);
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Child Process - Reading from pipe – Message 2 is %s\n", readmessage);
} else { //Parent process
printf("Parent Process - Writing to pipe - Message 1 is %s\n", writemessages[0]);
write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
printf("Parent Process - Writing to pipe - Message 2 is %s\n", writemessages[1]);
write(pipefds[1], writemessages[1], sizeof(writemessages[1]));

DEPARTMENT OF COMPUTER SCIENCE 29


}
return 0;
}
Execution
Parent Process - Writing to pipe - Message 1 is Hi
Parent Process - Writing to pipe - Message 2 is Hello
Child Process - Reading from pipe – Message 1 is Hi
Child Process - Reading from pipe – Message 2 is Hello

DEPARTMENT OF COMPUTER SCIENCE 30


9. Unix Program Implementing first fit, best fit algorithm for memory management.

Memory Management is one of the services provided by OS which is needed for Optimized
memory usage of the available memory in a Computer System.

For this purpose OS uses 3 methods:-

1. First Fit
2. Best Fit
3. Worst Fit

What is Best Fit Memory Management Scheme?

One of the simplest methods for memory allocation is to divide memory into several
fixed-sized partitions. Each partition may contain exactly one process. In this multiple-partition
method, when a partition is free, a process is selected from the input queue and is loaded into the
free partition. When the process terminates, the partition becomes available for another process.
The operating system keeps a table indicating which parts of memory are available and which
are occupied. Finally, when a process arrives and needs memory, a memory section large enough
for this process is provided. When it is time to load or swap a process into main memory, and if
there is more than one free block of memory of sufficient size, then the operating system must
decide which free block to allocate. Best-fit strategy chooses the block that is closest in size to
the request. First-fit chooses the first available block that is large enough. Worst-fit chooses the
largest available block.

Best Fit Algorithm

1. Get no. of Processes and no. of blocks.


2. After that get the size of each block and process requests.
3. Then select the best memory block that can be allocated using the above definition.
4. Display the processes with the blocks that are allocated to a respective process.
5. Value of Fragmentation is optional to display to keep track of wasted memory.
6. Stop.

Worst Fit program

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - First Fit");

DEPARTMENT OF COMPUTER SCIENCE 31


printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
{
ff[i]=j;
break;
}
}
}
frag[i]=temp;
bf[ff[i]]=1;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

DEPARTMENT OF COMPUTER SCIENCE 32


INPUT
Enter the number of blocks: 3
Enter the number of files: 2

Enter the size of the blocks:-


Block 1: 5
Block 2: 2
Block 3: 7

Enter the size of the files:-


File 1: 1
File 2: 4

OUTPUT
File No File Size Block No Block Size Fragment
1 1 1 5 4
2 4 3 7 3

b) Best-fit

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,lowest=10000;
static int bf[max],ff[max];
clrscr();
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);

DEPARTMENT OF COMPUTER SCIENCE 33


}
for(i=1;i<=nf;i++)
{
for(j=1;j<=nb;j++)
{
if(bf[j]!=1)
{
temp=b[j]-f[i];
if(temp>=0)
if(lowest>temp)
{
ff[i]=j;

lowest=temp;
}
}
}
frag[i]=lowest;
bf[ff[i]]=1;
lowest=10000;
}
printf("\nFile No\tFile Size \tBlock No\tBlock Size\tFragment");
for(i=1;i<=nf && ff[i]!=0;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

INPUT
Enter the number of blocks: 3
Enter the number of files: 2

Enter the size of the blocks:-


Block 1: 5
Block 2: 2
Block 3: 7

Enter the size of the files:-


File 1: 1
File 2: 4

DEPARTMENT OF COMPUTER SCIENCE 34


OUTPUT

File No File Size Block No Block Size Fragment


1 1 2 2 1
2 4 1 5 1

c) First-fit

#include<stdio.h>
#include<conio.h>
#define max 25
void main()
{
int frag[max],b[max],f[max],i,j,nb,nf,temp,highest=0;
static int bf[max],ff[max];
clrscr();
printf("\n\tMemory Management Scheme - Worst Fit");
printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of files:");
scanf("%d",&nf);
printf("\nEnter the size of the blocks:-\n");
for(i=1;i<=nb;i++)
{
printf("Block %d:",i);
scanf("%d",&b[i]);
}
printf("Enter the size of the files :-\n");
for(i=1;i<=nf;i++)
{
printf("File %d:",i);
scanf("%d",&f[i]);
}
for(i=1;i<=nf;i++)
{

for(j=1;j<=nb;j++)
{
if(bf[j]!=1) //if bf[j] is not allocated
{
temp=b[j]-f[i];
if(temp>=0)

DEPARTMENT OF COMPUTER SCIENCE 35


if(highest<temp)
{
ff[i]=j;
highest=temp;
}
}
}
frag[i]=highest;
bf[ff[i]]=1;
highest=0;
}
printf("\nFile_no:\tFile_size :\tBlock_no:\tBlock_size:\tFragement");
for(i=1;i<=nf;i++)
printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,f[i],ff[i],b[ff[i]],frag[i]);
getch();
}

INPUT

Enter the number of blocks: 3


Enter the number of files: 2

Enter the size of the blocks:-


Block 1: 5
Block 2: 2
Block 3: 7

Enter the size of the files:-


File 1: 1
File 2: 4

OUTPUT
File No File Size Block No Block Size Fragment
1 1 3 7 6
2 4 1 5 1

DEPARTMENT OF COMPUTER SCIENCE 36


EX.NO:10 PRODUCER-CONSUMER PROBLEM USING SEMOPHERES
DATE:

AIM: PRODUCER-CONSUMER PROBLEM USING SEMOPHERES

To implement producer/consumer problem using semaphore.

ALGORITHM:
1. Declare variable for producer & consumer as pthread-t-tid produce tid consume.
2. Declare a structure to add items, semaphore variable set as struct.
3. Read number the items to be produced and consumed.
4. Declare and define semaphore function for creation and destroy.
5. Define producer function.
6. Define consumer function.
7. Call producer and consumer.
8. Stop the execution.

DEPARTMENT OF COMPUTER SCIENCE 37


PROGRAM: (PRODUCER-CONSUMER PROBLEM)

#include<stdio.h>
void main()
{
int buffer[10], bufsize, in, out, produce, consume, choice=0; in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf("\n1. Produce \t 2. Consume \t3. Exit");
printf("\nEnter your choice: =");
scanf("%d", &choice);
switch(choice)
{
case 1:
if((in+1)%bufsize==out)
printf("\nBuffer is Full");
else
{
printf("\nEnter the value: ");
scanf("%d", &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
break;
case 2:
if(in == out)
printf("\nBuffer is Empty");
else
{
consume = buffer[out];
printf("\nThe consumed value is %d", consume); out = (out+1)%bufsize;
}
break;
}
}
}

DEPARTMENT OF COMPUTER SCIENCE 38


OUTPUT:
1. Produce
2. Consume
3. Exit
Enter your choice: 2
Buffer is Empty
1. Produce
2. Consume
3. Exit
Enter your choice: 1
Enter the value: 100
1. Produce
2. Consume
3. Exit
Enter your choice: 2
The consumed value is 100
1. Produce
2. Consume
3. Exit
Enter your choice: 3

RESULT:

Thus the producer consumer program was executed and verified successfully

DEPARTMENT OF COMPUTER SCIENCE 39


EX.NO: 11 A Shell Program to find factorial of a given number

DATE :

AIM: To implement Shell program to find factorial of a given number

Algorithm
1. Get a number

2. Use for loop or while loop to compute the factorial by using the below formula

3. fact(n) = n * n-1 * n-2 * .. 1

4. Display the result.

Program :

#shell script for factorial of a number


#factorial using while loop

echo "Enter a number"


read num

fact=1

while [ $num -gt 1 ]


do
fact=$((fact * num)) #fact = fact * num
num=$((num - 1)) #num = num - 1
done

echo $fact

DEPARTMENT OF COMPUTER SCIENCE 40


Output

Enter a number : 3

Enter a number: 4

24

Enter a number : 5

120

DEPARTMENT OF COMPUTER SCIENCE 41


EX.NO: 12 A shell program to generate Fibonacci number

DATE:

AIM : A Shell program to generate Fibonacci series

Start

Declare variables i, a,b , show


Initialize the variables, a=0, b=1, and show =0
Enter the number of terms of Fibonacci series to be printed
Print First two terms of series
Use loop for the following steps
-> show=a+b
-> a=b
-> b=show
-> increase value of i each time by 1
-> print the value of show
End

DEPARTMENT OF COMPUTER SCIENCE 42


Program

clear
echo "Program to Find Fibonacci Series"
echo "How many number of terms to be generated ?"
read n
x=0
y=1
i=2
echo "Fibonacci Series up to $n terms :"
echo "$x"
echo "$y"
while [ $i -lt $n ]
do
i=`expr $i + 1 `
z=`expr $x + $y `
echo "$z"
x=$y
y=$z
done

Output :

Program to Find Fibonacci Series


How many number of terms to be generated ?
5
Fibonacci Series up to $n terms :
0
0
1
2
3

DEPARTMENT OF COMPUTER SCIENCE 43

You might also like