SlideShare a Scribd company logo
1 of 29
Download to read offline
MCS206: Unix Operating Systems Lab
INDEX
S.No Date Program Page
Number
1 24/08/2021 Write programs using the following system calls of UNIX
operating system: fork, exec, getpid, exit, wait, close, stat, opendir,
readdir
2-7
2 31/08/2021 Write programs using the I/O system calls of UNIX operating
system (open, read, write, etc)
8-10
3 07/09/2021 Write C programs to simulate UNIX commands like ls, grep, etc. 11
4 14/09/2021 Given the list of processes, their CPU burst times and arrival
times, display/print the Gantt chart for FCFS and SJF. For each
of the scheduling policies, compute and print the average waiting
time and average turnaround time.
12-13
5 21/09/2021 Given the list of processes, their CPU burst times and arrival
times, display/print the Gantt chart for Priority and Round robin.
For each of the scheduling policies, compute and print the average
waiting time and average turnaround time.
14-17
6 28/09/2021 Developing Application using Inter Process communication (using
shared memory, pipes or message queues)
18
7 29/09/2021 Implement the Producer – Consumer problem using semaphores
(using UNIX system calls)
19-20
8 05/10/2021 Implement some memory management schemes – I 21-22
9 12/10/2021 Implement some memory management schemes – II 23-25
10 26/10/2021 Implement any file allocation technique (Linked, Indexed or
Contiguous)
26-29
2 | P a g e
Experiment No: 1 Write programs using the following system calls of UNIX operating
system: fork, exec, getpid, exit, wait, close, stat, opendir, readdir
AIM: Write programs using the following system calls of UNIX operating system:
fork, exec, getpid, exit, wait, close, stat, opendir, readdir
PROCEDURE:
a) fork(): Existing process can start a new process using fork() system call. It takes no arguments.
• If fork() returns a negative value, the creation of a child process was unsuccessful.
• If the child process is created successfully,
Once the child process has been created, then both the parent and child continue execution from
inside the fork() call. This means that the next action for both processes is to return from fork() with
its return value.
o fork() returns a zero to the child process.
o fork() returns the process ID of the child process, to the parent as shown below
The prototype for the fork() system call
#inciude <unistd.h>
pid_t fork(void);
b) getpid() system call: A process can use function getpid() to retrieve the process ID assigned to this
process.
c) exec() system call:
When you use the shell to run a command (ls, say) then at some point the shell will execute a fork() call to
get a new process running. Having done that, how does the shell then get ls to run in the child process instead
of the duplicate copy of the shell, which is what will be running immediately after the fork() call?
The solution in this case is to use an exec() system call. The simplest version of exec(). The prototype of
execv() system call is
int execv(pathname, argv);
The prototype for execv() shows that it only takes two parameters, the first is the full pathname to the
command to execute and the second is the argv value you want to pass into the new program.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables pid,pid1,pid2.
STEP 3: Call fork() system call to create process.
3 | P a g e
STEP 4: If pid==-1, exit.
STEP 5: if pid == 0 , and print the process id of child and execute hello.c program.
STEP 6: else , print the process id of parent
STEP 7:Stop the program
Program:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
pid_t p;
p = fork();
if(p==-1)
{
printf(“There is an error while calling fork()”);
}
if(p==0)
{
printf(“We are in the child process with pid = %dn”,getpid());
printf(“Calling hello.c from child processn”);
char *args[] = {“Hello”, “C”, “Programming”, NULL};
execv(“./hello”, args);
}
else
{
printf(“We are in the parent process with pid=%d”,getpid());
}
return 0;
}
Output:
We are in Parent Process with pid=4790
We are in Child Process with pid = 4791
Calling hello.c from child process
We are in hello.c
Wait() and exit() system calls
d) wait() system call:
The answer to the question of what the parent process does while the child process runs is quite simple —
either it waits for the child process to terminate or it just gets on with whatever else it needs to do.
In order to wait for a child process to terminate, a parent process will just execute a wait() system call. This
call will suspend the parent process until any of its child processes terminates, at which time the wait() call
returns and the parent process can continue.
The prototype for the wait() call is:
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status);
The return value from wait is the PID of the child process which terminated. The parameter to wait() is a
pointer to a location which will receive the child’s exit status value when it terminates.
4 | P a g e
e) exit() system call:
When a process terminates it executes an exit() system call, either directly in its own code, or indirectly via
library code. The prototype for the exit() call is:
#include <std1ib.h>
void exit(int status);
The exit() call has no return value as the process that calls it terminates and so could not receive a value
anyway. Notice, however, that exit() does take a parameter value — status.
exit() also returns the status parameter value to the parent process via the location pointed to by the wait()
parameter.
Program:
#include<stdio.h>
#include<sys/wait.h>
#include<unistd.h>
int main()
{
if (fork()== 0)
printf(“HC: hello from childn”);
else
{
printf(“HP: hello from parent, parent will start waiting for child to terminaten”);
wait(NULL);
printf(“CT: child has terminatedn”);
}
printf(“Byen”);
return 0;
}
5 | P a g e
Ouput:
HP: hello from parent, parent will start waiting for child to terminate
HC: hello from child
HC: Bye
CT: child has terminated // this sentence does
// not print before HC
// because of wait.
Bye
f) opendir ( ), readdir() system calls
DESCRIPTION:
The opendir( ) function opens a directory stream corresponding to the directory named by the d_name
argument. The directory stream is positioned at the first entry. The readdir( ) function returns a pointer to a
structure representing the directory entry at the current position in the directory stream specified by the
argument dir, and positions the directory stream at the next entry
PROGRAM: using opendir ( ), readdir ( ) system calls
#include <dirent.h>
#include <stdio.h>
int main(void)
{
DIR *d;
struct dirent *dir;
d = opendir(“.”);
if (d)
{
while ((dir = readdir(d)) != NULL)
{
printf(“%sn”, dir->d_name);
}
closedir(d);
}
return(0);
}
OUTPUT:
student@NNRG310:~/oslab$ cc dirsystemcalls.c
student@NNRG310:~/oslab$ ./a.out
f1.txt
f2.txt
.
fcfs.c
system calls programs.docx
sjf.c
a.out
.~lock.system calls programs.docx#
read.c
6 | P a g e
write.c
close.c
rr.c
dirsystemcalls.c
priority.c
f4.txt
f3.txt
..
open.c
g) stat ( ) system call
DESCRIPTION:
int stat(const char *path, struct stat *buf);
These functions return information about a file. No permissions are required on the file itself, but — in the
case of stat() and lstat() — execute (search) permission is required on all of the directories in path that lead
to the file.
PROGRAM: using stat ( ) system call
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
int main(int argc, char **argv)
{
if(argc!=2)
return 1;
struct stat fileStat;
if(stat(argv[1],&fileStat) < 0)
return 1;
printf(“Information for %sn”,argv[1]);
printf(“---------------------------n”);
printf(“File Size: tt%ld bytesn”,fileStat.st_size);
printf(“Number of Links: t%dn”,fileStat.st_nlink);
printf(“File inode: tt%lun”,fileStat.st_ino);
printf(“File Permissions: t”);
printf( (S_ISDIR(fileStat.st_mode)) ? “d” : “-“);
printf( (fileStat.st_mode & S_IRUSR) ? “r” : “-“);
printf( (fileStat.st_mode & S_IWUSR) ? “w” : “-“);
printf( (fileStat.st_mode & S_IXUSR) ? “x” : “-“);
printf( (fileStat.st_mode & S_IRGRP) ? “r” : “-“);
printf( (fileStat.st_mode & S_IWGRP) ? “w” : “-“);
printf( (fileStat.st_mode & S_IXGRP) ? “x” : “-“);
printf( (fileStat.st_mode & S_IROTH) ? “r” : “-“);
printf( (fileStat.st_mode & S_IWOTH) ? “w” : “-“);
printf( (fileStat.st_mode & S_IXOTH) ? “x” : “-“);
printf(“nn”);
return 0;
}
OUTPUT:
student@NNRG310:~/oslab$ cc stat.c
student@NNRG310:~/oslab$ ./a.out read.c
Information for read.c
7 | P a g e
------------------------------------------------
File Size: 455 bytes
Number of Links: 1
File inode: 794292
File Permissions: -rw-rw-r—
8 | P a g e
Experiment- 2
AIM: Write programs using the I/O system calls of UNIX/LINUX operating system
a) open ( ) system call
DESCRIPTION:
Used to open the file for reading, writing or both. This function returns the file descriptor or in case of
an error -1. The number of arguments that this function can have is two or three. The third argument is used
only when creating a new file. When we want to open an existing file only two arguments are used.
PROGRAM: using open ( ) system call
//using open() system call
#include<stdio.h>
#include<fcntl.h>
#include<errno.h>
extern int errno;
int main()
{
int fd=open("f3.txt",O_RDONLY | O_CREAT);
printf("fd=%dn",fd);
if (fd==-1)
{
printf("error Number %dn",errno);
perror("program");
}
return 0;
}
OUTPUT:
student@NNRG310:~/oslab$ cc open.c
student@NNRG310:~/oslab$ ./a.out
fd=3
b) read ( ) system call
DESCRIPTION:
Syntax:
size_t read (int fd, void* buf, size_t cnt);
From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input into the memory
area indicated by buf. A successful read() updates the access time for the file.
PROGRAM: using read ( ) system call
// read system Call read.c file
#include<stdio.h>
#include <fcntl.h>
#include<stdlib.h>
#include <unistd.h>
int main()
{
int fd,sz;
char *c = (char *) calloc(100, sizeof(char));
fd = open("f3.txt", O_RDONLY);
if (fd==-1)
9 | P a g e
{
perror("r1");
exit(1);
}
sz=read(fd,c,13);
printf("called read(%d, c, 10). returned that" " %d bytes were read.n", fd, sz);
c[sz] = '0';
printf("Those bytes are as follows: %sn", c);
return 0;
}
OUTPUT:
ca> f3.txt
From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input into the memory
area indicated by buf.
student@NNRG310:~/oslab$ cc read.c
student@NNRG310:~/oslab$ ./a.out
called read(3, c, 10). returned that 13 bytes were read.
Those bytes are as follows: From the file
c) write ( ) system call
DESCRIPTION:
size_t write (int fd, void* buf, size_t cnt);
Writes cnt bytes from buf to the file or socket associated with fd. If cnt is zero, write ( ) simply returns 0
without attempting any other action.
PROGRAM: using write ( ) system call
// C program to illustrate
// write system Call
#include<stdio.h>
#include <fcntl.h>
#include<stdlib.h>
#include <unistd.h>
#include<string.h>
int main( )
{
int sz;
int fd = open("f4.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd ==-1)
{
perror("r1");
exit(1);
}
sz = write(fd, "hello linux", strlen("hello linux"));
printf("called write(%d, "hello linux", %d). It returned %dn", fd,
strlen("hello linux"), sz);
close(fd);
return 0;
}
OUTPUT:
student@NNRG310:~/oslab$ cc write.c
student@NNRG310:~/oslab$ ./a.out
10 | P a g e
called write(3, "hello linux", 11). It returned 11
student@NNRG310:~/oslab$ cat f4.txt
hello linux
d) close ( ) system call
DESCRIPTION:
int close(int fd);
Tells the operating system you are done with a file descriptor and Close the file which pointed by fd.
PROGRAM: using close ( ) system call
// C program to illustrate close system Call
#include<stdio.h>
#include <fcntl.h>
#include<stdlib.h>
#include <unistd.h>
int main()
{
int fd1 = open("f3.txt", O_RDONLY);
if (fd1==-1)
{
perror("c1");
exit(1);
}
printf("opened the fd = % dn", fd1);
// Using close system Call
if (close(fd1)==-1)
{
perror("c1");
exit(1);
}
printf("closed the fd.n");
return 0;
}
OUTPUT:
student@NNRG310:~/oslab$ ./a.out
opened the fd = 3
closed the fd.
11 | P a g e
Experiment No: 3
AIM: Write C programs to simulate UNIX commands like ls, grep, etc.
PROCEDURE:
a) grep command: The grep filter searches a file for a particular pattern of characters, and displays all lines
that contain that pattern.
Example:
if geekfile.txt contains the data below:
unix is great os. unix is opensource. unix is free os. learn operating system.
Then the following command
$grep -c "unix" geekfile.txt
will give ouput:
2
as option -c prints only a count of the lines that match a pattern
b) ls command
ls command lists all files and subdirectories
Program:
#include<stdio.h>
#include<dirent.h>
main()
{
char dirname[10];
DIR*p;
struct dirent *d;
printf("Enter directory namen");
scanf("%s",dirname);
p=opendir(dirname);
if(p==NULL)
{
perror("Cannot find directory");
exit(-1);
}
while(d=readdir(p))
printf("%sn",d->d_name);
}
Output:
All files and subdirectories of current directory
12 | P a g e
Experiment No: 4
AIM: Given the list of processes, their CPU burst times and arrival times, display/printthe Gantt chart for
FCFS and SJF. For each of the scheduling policies, compute and print the average waiting time and average
turnaround time.
PROCEDURE
a) FCFS CPU scheduling
DESCRIPTION:
For FCFS scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. The
scheduling is performed on the basis of arrival time of the processes irrespective of their other parameters.
Each process will be executed according to its arrival time. Calculate the waiting time and turnaround time of
each of the processes accordingly.
Program:
#include <stdio.h>
int main()
{
int n;
printf("enter number of process ");
scanf("%d",&n);
int bt[n],i,wt[n],sumwt=0,ta[n],sumta=0;
wt[0]=0;
printf("enter the cpu burst time");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
wt[i+1]=bt[i]+wt[i];
ta[i]=wt[i]+bt[i];
sumwt=sumwt+wt[i];
sumta=sumta+ta[i];
}
printf("average waiting time = %dn",sumwt/n);
printf("average turn around time = %d",sumta/n);
return 0;
}
Output:
enter number of process 3
enter the cpu burst time
24
3
3
average waiting time = 17
average turn around time = 27
13 | P a g e
b) SJF CPU scheduling
DESCRIPTION:
For SJF(Shortest Job First) scheduling algorithm, read the number of processes/jobs in the system, their CPU
burst times. Arrange all the jobs in order with respect to their burst times. There may be two jobs in queue
with the same execution time, and then FCFS approach is to be performed. Each process will be executed acco
ding to the length of its burst time. Then calculate the waiting time and turnaround time of each of the processes
accordingly.
Program:
#include <stdio.h>
int main()
{
int n;
printf("enter number of process ");
scanf("%d",&n);
int bt[n],i,j,wt[n],sumwt=0,ta[n],sumta=0;
wt[0]=0;
printf("enter the cpu burst time");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(bt[i] > bt[j])
{
int temp=bt[i];
bt[i]=bt[j];
bt[j]=temp;
}
}
}
wt[0]=0;
for(i=0;i<n;i++)
{
wt[i+1]=bt[i]+wt[i];
ta[i]=wt[i]+bt[i];
sumwt=sumwt+wt[i];
sumta=sumta+ta[i];
}
printf("average waiting time = %dn",sumwt/n);
printf("average turn around time = %d",sumta/n);
return 0;
}
Output:
enter number of process
4
enter the cpu burst time
14 | P a g e
6
8
7
3
average waiting time = 7
average turn around time = 13
15 | P a g e
Experiment No: 5:
AIM: Given the list of processes, their CPU burst times and arrival times, display/printthe Gantt chart for
Priority and Round robin. For each of the scheduling policies, compute and print the average waiting time and
average turnaround time.
a) Priority CPU Scheduling
DESCRIPTION:
For priority scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times, and
the priorities. Arrange all the jobs in order with respect to their priorities. There may be two jobs in queue with
the same priority, and then FCFS approach is to be performed. Each process will be executed according to its
priority. Calculate the waiting time and turnaround time of each of the processes accordingly.
Program:
#include <stdio.h>
struct process
{
int prio,bt;
};
int main()
{
int n;
printf("enter number of process ");
scanf("%d",&n);
int i,j,wt[n],sumwt=0,ta[n],sumta=0;
struct process p[n],temp;
printf("enter the cpu burst time and their priorities");
for(i=0;i<n;i++)
{
scanf("%d%d", &p[i].bt,&p[i].prio);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(p[i].prio > p[j].prio)
{
temp=p[i];
p[i]=p[j];
p[j]=temp;
}
}
}
wt[0]=0;
for(i=0;i<n;i++)
{
wt[i+1]=wt[i]+p[i].bt;
ta[i]=wt[i]+p[i].bt;
sumwt=sumwt+wt[i];
sumta=sumta+ta[i];
16 | P a g e
}
printf("average waiting time = %dn",sumwt/n);
printf("average turn around time = %d",sumta/n);
return 0;
}
Output:
enter number of process
5
enter the cpu burst time and their priorities
10 3
1 1
2 4
1 5
5 2
average waiting time = 8
average turn around time = 12
b) Round Robin Scheduling
DESCRIPTION:
For round robin scheduling algorithm, read the number of processes/ jobs in the system, their CPU burst times,
and the size of the time slice. Time slices are assigned to each process in equal portions and in circular order,
handling all processes execution. This allows every process to get an equal chance.
Here in the program, waiting time is calculated by using the below formula
waitingTime=CompletionTime-CPUBurstTime
Program:
#include<stdio.h>
int main()
{
int n;
printf("enter number of process ");
scanf("%d",&n);
int i,j,bt[n],rem[n],wt[n],sumwt=0,ta[n],sumta=0,quantum;
printf("enter the cpu burst time ");
for(i=0;i<n;i++)
{
scanf("%d",&bt[i]);
rem[i]=bt[i];
}
printf("enter time quantum");
scanf("%d",&quantum);
int t = 0; // Current time
// Keep traversing processes in round robin manner until all of them are not done.
while (1)
{
int flag=1;
for (int i = 0 ; i < n; i++)
17 | P a g e
{
// If reamining burst time of a process is greater than 0 then only need to process further
if (rem[i] > 0)
{
flag=0; // There is a pending process
if (rem[i] > quantum)
{
t += quantum;
rem[i] = rem[i]-quantum;
}
else
{
t = t + rem[i];
wt[i] = t - bt[i];
sumwt=sumwt+wt[i];
sumta=sumta+t;
// As the process gets fully executed make its remaining burst time = 0
rem[i] = 0;
}
}
}
// If all processes are done
if (flag == 1)
break;
}
printf("average waiting time = %dn",sumwt/n);
printf("average turn around time = %d",sumta/n);
return 0;
}
Output:
enter number of process
3
enter the cpu burst time
10 5 8
enter time quantum
2
average waiting time = 12
average turn around time = 19
18 | P a g e
Experiment No: 6:
a) Developing Application using Inter Process communication using pipes
AIM: Program to write and read two messages using pipe.
Algorithm:
Step 1 − Create a pipe.
Step 2 − Send a message to the pipe.
Step 3 − Retrieve the message from the pipe and write it to the standard output.
Step 4 − Send another message to the pipe.
Step 5 − Retrieve the message from the pipe and write it to the standard output.
Program:
#include<stdio.h>
#include<unistd.h>
int main()
{
int pipefds[2];
int returnstatus;
char writemessages[2][20]={"Hi", "Hello"};
char readmessage[20];
returnstatus = pipe(pipefds);
if (returnstatus == -1)
{
printf("Unable to create pipen");
return 1;
}
printf("Writing to pipe - Message 1 is %sn", writemessages[0]);
write(pipefds[1], writemessages[0], sizeof(writemessages[0]));
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Reading from pipe – Message 1 is %sn", readmessage);
printf("Writing to pipe - Message 2 is %sn", writemessages[0]);
write(pipefds[1], writemessages[1], sizeof(writemessages[0]));
read(pipefds[0], readmessage, sizeof(readmessage));
printf("Reading from pipe – Message 2 is %sn", readmessage);
return 0;
}
Output:
Writing to pipe - Message 1 is Hi
Reading from pipe – Message 1 is Hi
Writing to pipe - Message 2 is Hi
Reading from pipe – Message 2 is Hell
19 | P a g e
Experiment No: 7
AIM: To Implement the Producer – Consumer problem using semaphores (using UNIX system calls)
DESCRIPTION: The producer consumer problem is a synchronization problem. There is a fixed size buffer
and the producer produces items and enters them into the buffer. The consumer removes the items from the
buffer and consumes them. A producer should not produce items into the buffer when the consumer is
consuming an item from the buffer and vice versa. So the buffer should only be accessed by the producer or
consumer at a time.
PROGRAM: Producer – Consumer problem using semaphores
#include<stdio.h>
#include<stdlib.h>
int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("n1.Producern2.Consumern3.Exit");
while(1)
{
printf("nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1: if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full!!");
break;
case 2: if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
}
}
return 0;
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
20 | P a g e
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("nProducer produces the item %d",x);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}
OUTPUT:
student@NNRG310:~/oslab$ cc pc.c
student@NNRG310:~/oslab$ ./a.out
1.Producer
2.Consumer
3.Exit
Enter your choice:1
Producer produces the item 1
Enter your choice:2
Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:1
Producer produces the item 1
Enter your choice:1
Producer produces the item 2
Enter your choice:2
Consumer consumes item 2
Enter your choice:2
Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:3
student@NNRG310:~/oslab$
21 | P a g e
Experiment No: 8 Implement some memory management schemes – I
IMPLEMENTATION OF THE FIFO PAGE REPLACEMENT ALGORITHMS
AIM:
To write a UNIX C program to implement FIFO page replacement algorithm.
DESCRIPTION :
The FIFO Page Replacement algorithm associates with each page the time when that page was brought into
memory. When a page must be replaced, the oldest page is chosen . There is not strictly necessary to record
the time when a page is brought in. By creating a FIFO queue to hold all pages in memory and by replacing
the page at the head of the queue. When a page is brought into memory, insert it at the tail of the queue.
ALGORITHM:
1. Start the process
2. Declare the size with respect to page length
3. Check the need of replacement from the page to memory
4. Check the need of replacement from old page to new page in memory
5. Format queue to hold all pages
6. Insert the page require memory into the queue
7. Check for bad replacement and page fault
8. Get the number of processes to be inserted
9. Display the values
10. Stop the process
PROGRAM:
#include<stdio.h>
main()
{
int i, j, k, f, pf=0, count=0, rs[25], m[10], n;
printf("n Enter the length of reference string -- ");
scanf("%d",&n);
printf("n Enter the reference string -- ");
for(i=0;i<n;i++)
scanf("%d",&rs[i]);
printf("n Enter no. of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
m[i]=-1;
printf("n The Page Replacement Process is -- n");
for(i=0;i<n;i++)
{
for(k=0;k<f;k++)
{
if(m[k]==rs[i])
break;
}
if(k==f)
{
m[count++]=rs[i];
pf++;
}
for(j=0;j<f;j++)
22 | P a g e
printf("t%d",m[j]);
if(k==f)
printf("tPF No. %d",pf);
printf("n");
if(count==f)
count=0;
}
printf("n The number of Page Faults using FIFO are %d",pf);
}
OUTPUT
Enter the length of reference string – 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter no. of frames -- 3
The Page Replacement Process is –
7 -1 -1 PF No. 1
7 0 -1 PF No. 2
7 0 1 PF No. 3
2 0 1 PF No. 4
2 0 1
2 3 1 PF No. 5
2 3 0 PF No. 6
4 3 0 PF No. 7
4 2 0 PF No. 8
4 2 3 PF No. 9
0 2 3 PF No. 10
0 2 3
0 2 3
0 1 3 PF No. 11
0 1 2 PF No. 12
0 1 2
0 1 2
7 1 2 PF No. 13
7 0 2 PF No. 14
7 0 1 PF No. 15
The number of Page Faults using FIFO are 15
RESULT:
Thus a UNIX C program to implement FIFO page replacement is executed successfully.
23 | P a g e
Experiment No: 9: Implement some memory management schemes -II
a) IMPLEMENTATION OF LRU PAGE REPLACEMENT ALGORITHM
AIM: To write UNIX C program a program to implement LRU page replacement algorithm.
DESCRIPTION:
The Least Recently Used replacement policy chooses to replace the page which has not been referenced for
the longest time. This policy assumes the recent past will approximate the immediate future. The operating
system keeps track of when each page was referenced by recording the time of reference or by maintaining a
stack of references.
ALGORITHM:
1. Start the process
2. Declare the size
3. Get the number of pages to be inserted
4. Get the value
5. Declare counter and stack
6. Select the least recently used page by counter value
7. Stack them according the selection.
8. Display the values
9. Stop the process
PROGRAM:
#include<stdio.h>
main()
{
int i, j , k, min, rs[25], m[10], count[10], flag[25], n, f, pf=0, next=1;
printf("Enter the length of reference string -- ");
scanf("%d",&n);
printf("Enter the reference string -- ");
for(i=0;i<n;i++)
{
scanf("%d",&rs[i]);
flag[i]=0;
}
printf("Enter the number of frames -- ");
scanf("%d",&f);
for(i=0;i<f;i++)
{
count[i]=0;
m[i]=-1;
}
printf("nThe Page Replacement process is -- n");
for(i=0;i<n;i++)
{
for(j=0;j<f;j++)
{
if(m[j]==rs[i])
{
flag[i]=1;
count[j]=next;
24 | P a g e
next++;
}
}
if(flag[i]==0)
{
if(i<f)
{
m[i]=rs[i];
count[i]=next;
next++;
}
else
{
min=0;
for(j=1;j<f;j++)
if(count[min] > count[j])
min=j;
m[min]=rs[i];
count[min]=next;
next++;
}
pf++;
}
for(j=0;j<f;j++)
printf("%dt", m[j]);
if(flag[i]==0)
printf("PF No. -- %d" , pf);
printf("n");
}
printf("nThe number of page faults using LRU are %d",pf);
}
OUTPUT
Enter the length of reference string -- 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter the number of frames -- 3
The Page Replacement process is --
7 -1 -1 PF No. -- 1
7 0 -1 PF No. -- 2
7 0 1 PF No. -- 3
2 0 1 PF No. -- 4
2 0 1
2 0 3 PF No. -- 5
2 0 3
4 0 3 PF No. -- 6
4 0 2 PF No. -- 7
4 3 2 PF No. -- 8
0 3 2 PF No. -- 9
0 3 2
0 3 2
1 3 2 PF No. -- 10
1 3 2
1 0 2 PF No. -- 11
25 | P a g e
1 0 2
1 0 7 PF No. -- 12
1 0 7
1 0 7
The number of page faults using LRU are 12
RESULT:
Thus a UNIX C program to implement LRU page replacement is executed successfully.
26 | P a g e
Experiment No: 10: Implement any file allocation technique (Linked, Indexed or Contiguous)
a) SEQUENTIAL FILE ALLOCATION
AIM: To implement sequential file allocation technique.
ALGORITHM:
Step 1: Start the program.
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations to each in sequential order.
a). Randomly select a location from available location s1= random(100);
b). Check whether the required locations are free from the selected location.
c). Allocate and set flag=1 to the allocated locations.
Step 5: Print the results fileno, length , Blocks allocated.
Step 6: Stop the program
PROGRAM:
#include<stdio.h>
int main()
{
int f[50],i,st,j,len,c,k;
for(i=0;i<50;i++)
f[i]=0;
printf("n Enter the starting block & length of file");
scanf("%d%d",&st,&len);
for(j=st;j<(st+len);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("n%d->%d",j,f[j]);
}
else
{
printf("Block already allocated");
break;
}
}
if(j==(st+len))
printf("n the file is allocated to disk");
}
Output:
Enter the starting block & length of file
4 5
4->1
5->1
6->1
7->1
8->1
The file is allocated to disk
27 | P a g e
b) LINKED FILE ALLOCATION AIM:
AIM: To write a C program to implement File Allocation concept using the technique Linked List
Technique.
ALGORITHM:
Step 1: Start the Program
Step 2: Get the number of files.
Step 3: Allocate the required locations by selecting a location randomly
Step 4: Check whether the selected location is free.
Step 5: If the location is free allocate and set flag =1 to the allocated locations.
Step 6: Print the results file no, length, blocks allocated.
Step 7: Stop the execution
PROGRAM:
#include<stdio.h>
main()
{
int f[50],p,i,j,k,a,st,len,n,c; clrscr();
for(i=0;i<50;i++)
f[i]=0;
printf("Enter how many blocks that are already allocated");
scanf("%d",&p);
printf("nEnter the blocks no.s that are already allocated");
for(i=0;i<p;i++)
{
scanf("%d",&a);
f[a]=1;
}
printf("Enter the starting index block & length");
scanf("%d%d",&st,&len);
k=len;
for(j=st;j<(k+st);j++)
{
if(f[j]==0)
{
f[j]=1;
printf("n%d->%d",j,f[j]);
}
else
{
printf("n %d->file is already allocated",j); k++;
}
}
}
OUTPUT:
Enter how many blocks are already allocated 3
Enter the blocks no’s that are already allocated 4 7 9
Enter the starting index block & length 3 7
3-> 1
28 | P a g e
4-> File is already allocated 5->1
6->1
7-> File is already allocated 8->1
9-> File is already allocated 10->1
11->1
12->1
RESULT:
Thus the program to implement the linked file allocation was executed successfully
c) INDEXED FILE ALLOCATION
AIM: To write a C program to implement file Allocation concept using the indexed allocation Technique
ALGORITHM:
Step 1: Start the Program
Step 2: Get the number of files.
Step 3: Get the memory requirement of each file.
Step 4: Allocate the required locations by selecting a location randomly. Step 5: Print the results file
no,length, blocks allocated.
Step 6: Stop the execution.
PROGRAM
#include<stdio.h>
int f[50],i,k,j,inde[50],n,c,count=0,p;
main()
{
for(i=0;i<50;i++)
f[i]=0;
x:
printf("enter index blockt");
scanf("%d",&p);
if(f[p]==0)
{
f[p]=1;
printf("enter no of files on indext");
scanf("%d",&n);
}
else
{
printf("Block already allocatedn");
goto x;
}
for(i=0;i<n;i++)
scanf("%d",&inde[i]);
for(i=0;i<n;i++)
if(f[inde[i]]==1)
{
printf("Block already allocated");
goto x;
}
for(j=0;j<n;j++)
f[inde[j]]=1;
29 | P a g e
printf("n allocated");
printf("n file indexed");
for(k=0;k<n;k++)
printf("n %d->%d:%d",p,inde[k],f[inde[k]]);
}
OUTPUT:
Enter index block 9
Enter no of files on index 3 1 2 3
Allocated
File indexed 9-> 1:1
9-> 2:1
9->3:1
RESULT :
Thus the program to implement the indexed file allocation was executed successfully

More Related Content

What's hot

Session initiation protocol SIP
Session initiation protocol SIPSession initiation protocol SIP
Session initiation protocol SIPLaraib Khan
 
Les algorithmes d'arithmetique
Les algorithmes d'arithmetiqueLes algorithmes d'arithmetique
Les algorithmes d'arithmetiquemohamed_SAYARI
 
System call (Fork +Exec)
System call (Fork +Exec)System call (Fork +Exec)
System call (Fork +Exec)Amit Ghosh
 
Apache Camel Netty component
Apache Camel Netty componentApache Camel Netty component
Apache Camel Netty componentssogabe
 
User datagram protocol
User datagram protocolUser datagram protocol
User datagram protocolMohd Arif
 
Homomorphic encryption
Homomorphic encryptionHomomorphic encryption
Homomorphic encryptionNamit Sinha
 
Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Socketsbabak danyal
 
Coursalgorithmique
CoursalgorithmiqueCoursalgorithmique
Coursalgorithmiquenicodeff
 
Intro to modern cryptography
Intro to modern cryptographyIntro to modern cryptography
Intro to modern cryptographyzahid-mian
 
Interprocess communication
Interprocess communicationInterprocess communication
Interprocess communicationSushil Singh
 
Trace kernel code tips
Trace kernel code tipsTrace kernel code tips
Trace kernel code tipsViller Hsiao
 
Distance Vector Multicast Routing Protocol (DVMRP) : Combined Presentation
Distance Vector Multicast Routing Protocol (DVMRP) : Combined PresentationDistance Vector Multicast Routing Protocol (DVMRP) : Combined Presentation
Distance Vector Multicast Routing Protocol (DVMRP) : Combined PresentationSubhajit Sahu
 
vishal_sharma: python email sending software
vishal_sharma: python email sending software  vishal_sharma: python email sending software
vishal_sharma: python email sending software vishal sharma
 
Snooping protocols 3
Snooping protocols 3Snooping protocols 3
Snooping protocols 3Yasir Khan
 

What's hot (20)

TCP Vs UDP
TCP Vs UDP TCP Vs UDP
TCP Vs UDP
 
Session initiation protocol SIP
Session initiation protocol SIPSession initiation protocol SIP
Session initiation protocol SIP
 
Les algorithmes d'arithmetique
Les algorithmes d'arithmetiqueLes algorithmes d'arithmetique
Les algorithmes d'arithmetique
 
System call (Fork +Exec)
System call (Fork +Exec)System call (Fork +Exec)
System call (Fork +Exec)
 
Integrity Protection for Embedded Systems
Integrity Protection for Embedded SystemsIntegrity Protection for Embedded Systems
Integrity Protection for Embedded Systems
 
Apache Camel Netty component
Apache Camel Netty componentApache Camel Netty component
Apache Camel Netty component
 
User datagram protocol
User datagram protocolUser datagram protocol
User datagram protocol
 
Homomorphic encryption
Homomorphic encryptionHomomorphic encryption
Homomorphic encryption
 
Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Sockets
 
Diffie-hellman algorithm
Diffie-hellman algorithmDiffie-hellman algorithm
Diffie-hellman algorithm
 
Coursalgorithmique
CoursalgorithmiqueCoursalgorithmique
Coursalgorithmique
 
Ch03
Ch03Ch03
Ch03
 
Intro to modern cryptography
Intro to modern cryptographyIntro to modern cryptography
Intro to modern cryptography
 
Interprocess communication
Interprocess communicationInterprocess communication
Interprocess communication
 
Ip header
Ip headerIp header
Ip header
 
Trace kernel code tips
Trace kernel code tipsTrace kernel code tips
Trace kernel code tips
 
Distance Vector Multicast Routing Protocol (DVMRP) : Combined Presentation
Distance Vector Multicast Routing Protocol (DVMRP) : Combined PresentationDistance Vector Multicast Routing Protocol (DVMRP) : Combined Presentation
Distance Vector Multicast Routing Protocol (DVMRP) : Combined Presentation
 
vishal_sharma: python email sending software
vishal_sharma: python email sending software  vishal_sharma: python email sending software
vishal_sharma: python email sending software
 
How do event loops work in Python?
How do event loops work in Python?How do event loops work in Python?
How do event loops work in Python?
 
Snooping protocols 3
Snooping protocols 3Snooping protocols 3
Snooping protocols 3
 

Similar to Os lab final

System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsashukiller7
 
What is-a-computer-process-os
What is-a-computer-process-osWhat is-a-computer-process-os
What is-a-computer-process-osManish Singh
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docxwkyra78
 
OS presentation (1).pptx
OS presentation (1).pptxOS presentation (1).pptx
OS presentation (1).pptxJenish62
 
Lecture2 process structure and programming
Lecture2   process structure and programmingLecture2   process structure and programming
Lecture2 process structure and programmingMohammed Farrag
 
httplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxhttplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxadampcarr67227
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104swena_gupta
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104swena_gupta
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104swena_gupta
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk PemulaOon Arfiandwi
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communicationecomputernotes
 
04_ForkPipe.pptx
04_ForkPipe.pptx04_ForkPipe.pptx
04_ForkPipe.pptxvnwzympx
 
Mychurch File Upload
Mychurch File UploadMychurch File Upload
Mychurch File UploadJoe Suh
 
System Calls - Introduction
System Calls - IntroductionSystem Calls - Introduction
System Calls - IntroductionTo Sum It Up
 

Similar to Os lab final (20)

System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
 
Linux_C_LabBasics.ppt
Linux_C_LabBasics.pptLinux_C_LabBasics.ppt
Linux_C_LabBasics.ppt
 
process creation OS
process creation OSprocess creation OS
process creation OS
 
What is-a-computer-process-os
What is-a-computer-process-osWhat is-a-computer-process-os
What is-a-computer-process-os
 
Program Assignment Process ManagementObjective This program a.docx
Program Assignment  Process ManagementObjective This program a.docxProgram Assignment  Process ManagementObjective This program a.docx
Program Assignment Process ManagementObjective This program a.docx
 
OS presentation (1).pptx
OS presentation (1).pptxOS presentation (1).pptx
OS presentation (1).pptx
 
Lecture2 process structure and programming
Lecture2   process structure and programmingLecture2   process structure and programming
Lecture2 process structure and programming
 
httplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docxhttplinux.die.netman3execfork() creates a new process by.docx
httplinux.die.netman3execfork() creates a new process by.docx
 
Unix kernal
Unix kernalUnix kernal
Unix kernal
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
 
Lab report 201001067_201001104
Lab report 201001067_201001104Lab report 201001067_201001104
Lab report 201001067_201001104
 
LP-Unit3.docx
LP-Unit3.docxLP-Unit3.docx
LP-Unit3.docx
 
MPI
MPIMPI
MPI
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communication
 
04_ForkPipe.pptx
04_ForkPipe.pptx04_ForkPipe.pptx
04_ForkPipe.pptx
 
Virus lab
Virus labVirus lab
Virus lab
 
Mychurch File Upload
Mychurch File UploadMychurch File Upload
Mychurch File Upload
 
System Calls - Introduction
System Calls - IntroductionSystem Calls - Introduction
System Calls - Introduction
 

More from LakshmiSarvani6

More from LakshmiSarvani6 (6)

Excel notes
Excel notesExcel notes
Excel notes
 
Dbms important questions and answers
Dbms important questions and answersDbms important questions and answers
Dbms important questions and answers
 
Introduction to Data Science With R Notes
Introduction to Data Science With R NotesIntroduction to Data Science With R Notes
Introduction to Data Science With R Notes
 
Completeosnotes
CompleteosnotesCompleteosnotes
Completeosnotes
 
Os notes
Os notesOs notes
Os notes
 
Sql lab experiments
Sql lab experimentsSql lab experiments
Sql lab experiments
 

Recently uploaded

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Recently uploaded (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

Os lab final

  • 1. MCS206: Unix Operating Systems Lab INDEX S.No Date Program Page Number 1 24/08/2021 Write programs using the following system calls of UNIX operating system: fork, exec, getpid, exit, wait, close, stat, opendir, readdir 2-7 2 31/08/2021 Write programs using the I/O system calls of UNIX operating system (open, read, write, etc) 8-10 3 07/09/2021 Write C programs to simulate UNIX commands like ls, grep, etc. 11 4 14/09/2021 Given the list of processes, their CPU burst times and arrival times, display/print the Gantt chart for FCFS and SJF. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. 12-13 5 21/09/2021 Given the list of processes, their CPU burst times and arrival times, display/print the Gantt chart for Priority and Round robin. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. 14-17 6 28/09/2021 Developing Application using Inter Process communication (using shared memory, pipes or message queues) 18 7 29/09/2021 Implement the Producer – Consumer problem using semaphores (using UNIX system calls) 19-20 8 05/10/2021 Implement some memory management schemes – I 21-22 9 12/10/2021 Implement some memory management schemes – II 23-25 10 26/10/2021 Implement any file allocation technique (Linked, Indexed or Contiguous) 26-29
  • 2. 2 | P a g e Experiment No: 1 Write programs using the following system calls of UNIX operating system: fork, exec, getpid, exit, wait, close, stat, opendir, readdir AIM: Write programs using the following system calls of UNIX operating system: fork, exec, getpid, exit, wait, close, stat, opendir, readdir PROCEDURE: a) fork(): Existing process can start a new process using fork() system call. It takes no arguments. • If fork() returns a negative value, the creation of a child process was unsuccessful. • If the child process is created successfully, Once the child process has been created, then both the parent and child continue execution from inside the fork() call. This means that the next action for both processes is to return from fork() with its return value. o fork() returns a zero to the child process. o fork() returns the process ID of the child process, to the parent as shown below The prototype for the fork() system call #inciude <unistd.h> pid_t fork(void); b) getpid() system call: A process can use function getpid() to retrieve the process ID assigned to this process. c) exec() system call: When you use the shell to run a command (ls, say) then at some point the shell will execute a fork() call to get a new process running. Having done that, how does the shell then get ls to run in the child process instead of the duplicate copy of the shell, which is what will be running immediately after the fork() call? The solution in this case is to use an exec() system call. The simplest version of exec(). The prototype of execv() system call is int execv(pathname, argv); The prototype for execv() shows that it only takes two parameters, the first is the full pathname to the command to execute and the second is the argv value you want to pass into the new program. ALGORITHM: STEP 1: Start the program. STEP 2: Declare the variables pid,pid1,pid2. STEP 3: Call fork() system call to create process.
  • 3. 3 | P a g e STEP 4: If pid==-1, exit. STEP 5: if pid == 0 , and print the process id of child and execute hello.c program. STEP 6: else , print the process id of parent STEP 7:Stop the program Program: #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(int argc, char *argv[]) { pid_t p; p = fork(); if(p==-1) { printf(“There is an error while calling fork()”); } if(p==0) { printf(“We are in the child process with pid = %dn”,getpid()); printf(“Calling hello.c from child processn”); char *args[] = {“Hello”, “C”, “Programming”, NULL}; execv(“./hello”, args); } else { printf(“We are in the parent process with pid=%d”,getpid()); } return 0; } Output: We are in Parent Process with pid=4790 We are in Child Process with pid = 4791 Calling hello.c from child process We are in hello.c Wait() and exit() system calls d) wait() system call: The answer to the question of what the parent process does while the child process runs is quite simple — either it waits for the child process to terminate or it just gets on with whatever else it needs to do. In order to wait for a child process to terminate, a parent process will just execute a wait() system call. This call will suspend the parent process until any of its child processes terminates, at which time the wait() call returns and the parent process can continue. The prototype for the wait() call is: #include <sys/types.h> #include <sys/wait.h> pid_t wait(int *status); The return value from wait is the PID of the child process which terminated. The parameter to wait() is a pointer to a location which will receive the child’s exit status value when it terminates.
  • 4. 4 | P a g e e) exit() system call: When a process terminates it executes an exit() system call, either directly in its own code, or indirectly via library code. The prototype for the exit() call is: #include <std1ib.h> void exit(int status); The exit() call has no return value as the process that calls it terminates and so could not receive a value anyway. Notice, however, that exit() does take a parameter value — status. exit() also returns the status parameter value to the parent process via the location pointed to by the wait() parameter. Program: #include<stdio.h> #include<sys/wait.h> #include<unistd.h> int main() { if (fork()== 0) printf(“HC: hello from childn”); else { printf(“HP: hello from parent, parent will start waiting for child to terminaten”); wait(NULL); printf(“CT: child has terminatedn”); } printf(“Byen”); return 0; }
  • 5. 5 | P a g e Ouput: HP: hello from parent, parent will start waiting for child to terminate HC: hello from child HC: Bye CT: child has terminated // this sentence does // not print before HC // because of wait. Bye f) opendir ( ), readdir() system calls DESCRIPTION: The opendir( ) function opens a directory stream corresponding to the directory named by the d_name argument. The directory stream is positioned at the first entry. The readdir( ) function returns a pointer to a structure representing the directory entry at the current position in the directory stream specified by the argument dir, and positions the directory stream at the next entry PROGRAM: using opendir ( ), readdir ( ) system calls #include <dirent.h> #include <stdio.h> int main(void) { DIR *d; struct dirent *dir; d = opendir(“.”); if (d) { while ((dir = readdir(d)) != NULL) { printf(“%sn”, dir->d_name); } closedir(d); } return(0); } OUTPUT: student@NNRG310:~/oslab$ cc dirsystemcalls.c student@NNRG310:~/oslab$ ./a.out f1.txt f2.txt . fcfs.c system calls programs.docx sjf.c a.out .~lock.system calls programs.docx# read.c
  • 6. 6 | P a g e write.c close.c rr.c dirsystemcalls.c priority.c f4.txt f3.txt .. open.c g) stat ( ) system call DESCRIPTION: int stat(const char *path, struct stat *buf); These functions return information about a file. No permissions are required on the file itself, but — in the case of stat() and lstat() — execute (search) permission is required on all of the directories in path that lead to the file. PROGRAM: using stat ( ) system call #include <unistd.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char **argv) { if(argc!=2) return 1; struct stat fileStat; if(stat(argv[1],&fileStat) < 0) return 1; printf(“Information for %sn”,argv[1]); printf(“---------------------------n”); printf(“File Size: tt%ld bytesn”,fileStat.st_size); printf(“Number of Links: t%dn”,fileStat.st_nlink); printf(“File inode: tt%lun”,fileStat.st_ino); printf(“File Permissions: t”); printf( (S_ISDIR(fileStat.st_mode)) ? “d” : “-“); printf( (fileStat.st_mode & S_IRUSR) ? “r” : “-“); printf( (fileStat.st_mode & S_IWUSR) ? “w” : “-“); printf( (fileStat.st_mode & S_IXUSR) ? “x” : “-“); printf( (fileStat.st_mode & S_IRGRP) ? “r” : “-“); printf( (fileStat.st_mode & S_IWGRP) ? “w” : “-“); printf( (fileStat.st_mode & S_IXGRP) ? “x” : “-“); printf( (fileStat.st_mode & S_IROTH) ? “r” : “-“); printf( (fileStat.st_mode & S_IWOTH) ? “w” : “-“); printf( (fileStat.st_mode & S_IXOTH) ? “x” : “-“); printf(“nn”); return 0; } OUTPUT: student@NNRG310:~/oslab$ cc stat.c student@NNRG310:~/oslab$ ./a.out read.c Information for read.c
  • 7. 7 | P a g e ------------------------------------------------ File Size: 455 bytes Number of Links: 1 File inode: 794292 File Permissions: -rw-rw-r—
  • 8. 8 | P a g e Experiment- 2 AIM: Write programs using the I/O system calls of UNIX/LINUX operating system a) open ( ) system call DESCRIPTION: Used to open the file for reading, writing or both. This function returns the file descriptor or in case of an error -1. The number of arguments that this function can have is two or three. The third argument is used only when creating a new file. When we want to open an existing file only two arguments are used. PROGRAM: using open ( ) system call //using open() system call #include<stdio.h> #include<fcntl.h> #include<errno.h> extern int errno; int main() { int fd=open("f3.txt",O_RDONLY | O_CREAT); printf("fd=%dn",fd); if (fd==-1) { printf("error Number %dn",errno); perror("program"); } return 0; } OUTPUT: student@NNRG310:~/oslab$ cc open.c student@NNRG310:~/oslab$ ./a.out fd=3 b) read ( ) system call DESCRIPTION: Syntax: size_t read (int fd, void* buf, size_t cnt); From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input into the memory area indicated by buf. A successful read() updates the access time for the file. PROGRAM: using read ( ) system call // read system Call read.c file #include<stdio.h> #include <fcntl.h> #include<stdlib.h> #include <unistd.h> int main() { int fd,sz; char *c = (char *) calloc(100, sizeof(char)); fd = open("f3.txt", O_RDONLY); if (fd==-1)
  • 9. 9 | P a g e { perror("r1"); exit(1); } sz=read(fd,c,13); printf("called read(%d, c, 10). returned that" " %d bytes were read.n", fd, sz); c[sz] = '0'; printf("Those bytes are as follows: %sn", c); return 0; } OUTPUT: ca> f3.txt From the file indicated by the file descriptor fd, the read() function reads cnt bytes of input into the memory area indicated by buf. student@NNRG310:~/oslab$ cc read.c student@NNRG310:~/oslab$ ./a.out called read(3, c, 10). returned that 13 bytes were read. Those bytes are as follows: From the file c) write ( ) system call DESCRIPTION: size_t write (int fd, void* buf, size_t cnt); Writes cnt bytes from buf to the file or socket associated with fd. If cnt is zero, write ( ) simply returns 0 without attempting any other action. PROGRAM: using write ( ) system call // C program to illustrate // write system Call #include<stdio.h> #include <fcntl.h> #include<stdlib.h> #include <unistd.h> #include<string.h> int main( ) { int sz; int fd = open("f4.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd ==-1) { perror("r1"); exit(1); } sz = write(fd, "hello linux", strlen("hello linux")); printf("called write(%d, "hello linux", %d). It returned %dn", fd, strlen("hello linux"), sz); close(fd); return 0; } OUTPUT: student@NNRG310:~/oslab$ cc write.c student@NNRG310:~/oslab$ ./a.out
  • 10. 10 | P a g e called write(3, "hello linux", 11). It returned 11 student@NNRG310:~/oslab$ cat f4.txt hello linux d) close ( ) system call DESCRIPTION: int close(int fd); Tells the operating system you are done with a file descriptor and Close the file which pointed by fd. PROGRAM: using close ( ) system call // C program to illustrate close system Call #include<stdio.h> #include <fcntl.h> #include<stdlib.h> #include <unistd.h> int main() { int fd1 = open("f3.txt", O_RDONLY); if (fd1==-1) { perror("c1"); exit(1); } printf("opened the fd = % dn", fd1); // Using close system Call if (close(fd1)==-1) { perror("c1"); exit(1); } printf("closed the fd.n"); return 0; } OUTPUT: student@NNRG310:~/oslab$ ./a.out opened the fd = 3 closed the fd.
  • 11. 11 | P a g e Experiment No: 3 AIM: Write C programs to simulate UNIX commands like ls, grep, etc. PROCEDURE: a) grep command: The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. Example: if geekfile.txt contains the data below: unix is great os. unix is opensource. unix is free os. learn operating system. Then the following command $grep -c "unix" geekfile.txt will give ouput: 2 as option -c prints only a count of the lines that match a pattern b) ls command ls command lists all files and subdirectories Program: #include<stdio.h> #include<dirent.h> main() { char dirname[10]; DIR*p; struct dirent *d; printf("Enter directory namen"); scanf("%s",dirname); p=opendir(dirname); if(p==NULL) { perror("Cannot find directory"); exit(-1); } while(d=readdir(p)) printf("%sn",d->d_name); } Output: All files and subdirectories of current directory
  • 12. 12 | P a g e Experiment No: 4 AIM: Given the list of processes, their CPU burst times and arrival times, display/printthe Gantt chart for FCFS and SJF. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. PROCEDURE a) FCFS CPU scheduling DESCRIPTION: For FCFS scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. The scheduling is performed on the basis of arrival time of the processes irrespective of their other parameters. Each process will be executed according to its arrival time. Calculate the waiting time and turnaround time of each of the processes accordingly. Program: #include <stdio.h> int main() { int n; printf("enter number of process "); scanf("%d",&n); int bt[n],i,wt[n],sumwt=0,ta[n],sumta=0; wt[0]=0; printf("enter the cpu burst time"); for(i=0;i<n;i++) { scanf("%d",&bt[i]); wt[i+1]=bt[i]+wt[i]; ta[i]=wt[i]+bt[i]; sumwt=sumwt+wt[i]; sumta=sumta+ta[i]; } printf("average waiting time = %dn",sumwt/n); printf("average turn around time = %d",sumta/n); return 0; } Output: enter number of process 3 enter the cpu burst time 24 3 3 average waiting time = 17 average turn around time = 27
  • 13. 13 | P a g e b) SJF CPU scheduling DESCRIPTION: For SJF(Shortest Job First) scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times. Arrange all the jobs in order with respect to their burst times. There may be two jobs in queue with the same execution time, and then FCFS approach is to be performed. Each process will be executed acco ding to the length of its burst time. Then calculate the waiting time and turnaround time of each of the processes accordingly. Program: #include <stdio.h> int main() { int n; printf("enter number of process "); scanf("%d",&n); int bt[n],i,j,wt[n],sumwt=0,ta[n],sumta=0; wt[0]=0; printf("enter the cpu burst time"); for(i=0;i<n;i++) { scanf("%d",&bt[i]); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(bt[i] > bt[j]) { int temp=bt[i]; bt[i]=bt[j]; bt[j]=temp; } } } wt[0]=0; for(i=0;i<n;i++) { wt[i+1]=bt[i]+wt[i]; ta[i]=wt[i]+bt[i]; sumwt=sumwt+wt[i]; sumta=sumta+ta[i]; } printf("average waiting time = %dn",sumwt/n); printf("average turn around time = %d",sumta/n); return 0; } Output: enter number of process 4 enter the cpu burst time
  • 14. 14 | P a g e 6 8 7 3 average waiting time = 7 average turn around time = 13
  • 15. 15 | P a g e Experiment No: 5: AIM: Given the list of processes, their CPU burst times and arrival times, display/printthe Gantt chart for Priority and Round robin. For each of the scheduling policies, compute and print the average waiting time and average turnaround time. a) Priority CPU Scheduling DESCRIPTION: For priority scheduling algorithm, read the number of processes/jobs in the system, their CPU burst times, and the priorities. Arrange all the jobs in order with respect to their priorities. There may be two jobs in queue with the same priority, and then FCFS approach is to be performed. Each process will be executed according to its priority. Calculate the waiting time and turnaround time of each of the processes accordingly. Program: #include <stdio.h> struct process { int prio,bt; }; int main() { int n; printf("enter number of process "); scanf("%d",&n); int i,j,wt[n],sumwt=0,ta[n],sumta=0; struct process p[n],temp; printf("enter the cpu burst time and their priorities"); for(i=0;i<n;i++) { scanf("%d%d", &p[i].bt,&p[i].prio); } for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(p[i].prio > p[j].prio) { temp=p[i]; p[i]=p[j]; p[j]=temp; } } } wt[0]=0; for(i=0;i<n;i++) { wt[i+1]=wt[i]+p[i].bt; ta[i]=wt[i]+p[i].bt; sumwt=sumwt+wt[i]; sumta=sumta+ta[i];
  • 16. 16 | P a g e } printf("average waiting time = %dn",sumwt/n); printf("average turn around time = %d",sumta/n); return 0; } Output: enter number of process 5 enter the cpu burst time and their priorities 10 3 1 1 2 4 1 5 5 2 average waiting time = 8 average turn around time = 12 b) Round Robin Scheduling DESCRIPTION: For round robin scheduling algorithm, read the number of processes/ jobs in the system, their CPU burst times, and the size of the time slice. Time slices are assigned to each process in equal portions and in circular order, handling all processes execution. This allows every process to get an equal chance. Here in the program, waiting time is calculated by using the below formula waitingTime=CompletionTime-CPUBurstTime Program: #include<stdio.h> int main() { int n; printf("enter number of process "); scanf("%d",&n); int i,j,bt[n],rem[n],wt[n],sumwt=0,ta[n],sumta=0,quantum; printf("enter the cpu burst time "); for(i=0;i<n;i++) { scanf("%d",&bt[i]); rem[i]=bt[i]; } printf("enter time quantum"); scanf("%d",&quantum); int t = 0; // Current time // Keep traversing processes in round robin manner until all of them are not done. while (1) { int flag=1; for (int i = 0 ; i < n; i++)
  • 17. 17 | P a g e { // If reamining burst time of a process is greater than 0 then only need to process further if (rem[i] > 0) { flag=0; // There is a pending process if (rem[i] > quantum) { t += quantum; rem[i] = rem[i]-quantum; } else { t = t + rem[i]; wt[i] = t - bt[i]; sumwt=sumwt+wt[i]; sumta=sumta+t; // As the process gets fully executed make its remaining burst time = 0 rem[i] = 0; } } } // If all processes are done if (flag == 1) break; } printf("average waiting time = %dn",sumwt/n); printf("average turn around time = %d",sumta/n); return 0; } Output: enter number of process 3 enter the cpu burst time 10 5 8 enter time quantum 2 average waiting time = 12 average turn around time = 19
  • 18. 18 | P a g e Experiment No: 6: a) Developing Application using Inter Process communication using pipes AIM: Program to write and read two messages using pipe. Algorithm: Step 1 − Create a pipe. Step 2 − Send a message to the pipe. Step 3 − Retrieve the message from the pipe and write it to the standard output. Step 4 − Send another message to the pipe. Step 5 − Retrieve the message from the pipe and write it to the standard output. Program: #include<stdio.h> #include<unistd.h> int main() { int pipefds[2]; int returnstatus; char writemessages[2][20]={"Hi", "Hello"}; char readmessage[20]; returnstatus = pipe(pipefds); if (returnstatus == -1) { printf("Unable to create pipen"); return 1; } printf("Writing to pipe - Message 1 is %sn", writemessages[0]); write(pipefds[1], writemessages[0], sizeof(writemessages[0])); read(pipefds[0], readmessage, sizeof(readmessage)); printf("Reading from pipe – Message 1 is %sn", readmessage); printf("Writing to pipe - Message 2 is %sn", writemessages[0]); write(pipefds[1], writemessages[1], sizeof(writemessages[0])); read(pipefds[0], readmessage, sizeof(readmessage)); printf("Reading from pipe – Message 2 is %sn", readmessage); return 0; } Output: Writing to pipe - Message 1 is Hi Reading from pipe – Message 1 is Hi Writing to pipe - Message 2 is Hi Reading from pipe – Message 2 is Hell
  • 19. 19 | P a g e Experiment No: 7 AIM: To Implement the Producer – Consumer problem using semaphores (using UNIX system calls) DESCRIPTION: The producer consumer problem is a synchronization problem. There is a fixed size buffer and the producer produces items and enters them into the buffer. The consumer removes the items from the buffer and consumes them. A producer should not produce items into the buffer when the consumer is consuming an item from the buffer and vice versa. So the buffer should only be accessed by the producer or consumer at a time. PROGRAM: Producer – Consumer problem using semaphores #include<stdio.h> #include<stdlib.h> int mutex=1,full=0,empty=3,x=0; int main() { int n; void producer(); void consumer(); int wait(int); int signal(int); printf("n1.Producern2.Consumern3.Exit"); while(1) { printf("nEnter your choice:"); scanf("%d",&n); switch(n) { case 1: if((mutex==1)&&(empty!=0)) producer(); else printf("Buffer is full!!"); break; case 2: if((mutex==1)&&(full!=0)) consumer(); else printf("Buffer is empty!!"); break; case 3: exit(0); } } return 0; } int wait(int s) { return (--s); } int signal(int s) { return(++s);
  • 20. 20 | P a g e } void producer() { mutex=wait(mutex); full=signal(full); empty=wait(empty); x++; printf("nProducer produces the item %d",x); mutex=signal(mutex); } void consumer() { mutex=wait(mutex); full=wait(full); empty=signal(empty); printf("nConsumer consumes item %d",x); x--; mutex=signal(mutex); } OUTPUT: student@NNRG310:~/oslab$ cc pc.c student@NNRG310:~/oslab$ ./a.out 1.Producer 2.Consumer 3.Exit Enter your choice:1 Producer produces the item 1 Enter your choice:2 Consumer consumes item 1 Enter your choice:2 Buffer is empty!! Enter your choice:1 Producer produces the item 1 Enter your choice:1 Producer produces the item 2 Enter your choice:2 Consumer consumes item 2 Enter your choice:2 Consumer consumes item 1 Enter your choice:2 Buffer is empty!! Enter your choice:3 student@NNRG310:~/oslab$
  • 21. 21 | P a g e Experiment No: 8 Implement some memory management schemes – I IMPLEMENTATION OF THE FIFO PAGE REPLACEMENT ALGORITHMS AIM: To write a UNIX C program to implement FIFO page replacement algorithm. DESCRIPTION : The FIFO Page Replacement algorithm associates with each page the time when that page was brought into memory. When a page must be replaced, the oldest page is chosen . There is not strictly necessary to record the time when a page is brought in. By creating a FIFO queue to hold all pages in memory and by replacing the page at the head of the queue. When a page is brought into memory, insert it at the tail of the queue. ALGORITHM: 1. Start the process 2. Declare the size with respect to page length 3. Check the need of replacement from the page to memory 4. Check the need of replacement from old page to new page in memory 5. Format queue to hold all pages 6. Insert the page require memory into the queue 7. Check for bad replacement and page fault 8. Get the number of processes to be inserted 9. Display the values 10. Stop the process PROGRAM: #include<stdio.h> main() { int i, j, k, f, pf=0, count=0, rs[25], m[10], n; printf("n Enter the length of reference string -- "); scanf("%d",&n); printf("n Enter the reference string -- "); for(i=0;i<n;i++) scanf("%d",&rs[i]); printf("n Enter no. of frames -- "); scanf("%d",&f); for(i=0;i<f;i++) m[i]=-1; printf("n The Page Replacement Process is -- n"); for(i=0;i<n;i++) { for(k=0;k<f;k++) { if(m[k]==rs[i]) break; } if(k==f) { m[count++]=rs[i]; pf++; } for(j=0;j<f;j++)
  • 22. 22 | P a g e printf("t%d",m[j]); if(k==f) printf("tPF No. %d",pf); printf("n"); if(count==f) count=0; } printf("n The number of Page Faults using FIFO are %d",pf); } OUTPUT Enter the length of reference string – 20 Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 Enter no. of frames -- 3 The Page Replacement Process is – 7 -1 -1 PF No. 1 7 0 -1 PF No. 2 7 0 1 PF No. 3 2 0 1 PF No. 4 2 0 1 2 3 1 PF No. 5 2 3 0 PF No. 6 4 3 0 PF No. 7 4 2 0 PF No. 8 4 2 3 PF No. 9 0 2 3 PF No. 10 0 2 3 0 2 3 0 1 3 PF No. 11 0 1 2 PF No. 12 0 1 2 0 1 2 7 1 2 PF No. 13 7 0 2 PF No. 14 7 0 1 PF No. 15 The number of Page Faults using FIFO are 15 RESULT: Thus a UNIX C program to implement FIFO page replacement is executed successfully.
  • 23. 23 | P a g e Experiment No: 9: Implement some memory management schemes -II a) IMPLEMENTATION OF LRU PAGE REPLACEMENT ALGORITHM AIM: To write UNIX C program a program to implement LRU page replacement algorithm. DESCRIPTION: The Least Recently Used replacement policy chooses to replace the page which has not been referenced for the longest time. This policy assumes the recent past will approximate the immediate future. The operating system keeps track of when each page was referenced by recording the time of reference or by maintaining a stack of references. ALGORITHM: 1. Start the process 2. Declare the size 3. Get the number of pages to be inserted 4. Get the value 5. Declare counter and stack 6. Select the least recently used page by counter value 7. Stack them according the selection. 8. Display the values 9. Stop the process PROGRAM: #include<stdio.h> main() { int i, j , k, min, rs[25], m[10], count[10], flag[25], n, f, pf=0, next=1; printf("Enter the length of reference string -- "); scanf("%d",&n); printf("Enter the reference string -- "); for(i=0;i<n;i++) { scanf("%d",&rs[i]); flag[i]=0; } printf("Enter the number of frames -- "); scanf("%d",&f); for(i=0;i<f;i++) { count[i]=0; m[i]=-1; } printf("nThe Page Replacement process is -- n"); for(i=0;i<n;i++) { for(j=0;j<f;j++) { if(m[j]==rs[i]) { flag[i]=1; count[j]=next;
  • 24. 24 | P a g e next++; } } if(flag[i]==0) { if(i<f) { m[i]=rs[i]; count[i]=next; next++; } else { min=0; for(j=1;j<f;j++) if(count[min] > count[j]) min=j; m[min]=rs[i]; count[min]=next; next++; } pf++; } for(j=0;j<f;j++) printf("%dt", m[j]); if(flag[i]==0) printf("PF No. -- %d" , pf); printf("n"); } printf("nThe number of page faults using LRU are %d",pf); } OUTPUT Enter the length of reference string -- 20 Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 Enter the number of frames -- 3 The Page Replacement process is -- 7 -1 -1 PF No. -- 1 7 0 -1 PF No. -- 2 7 0 1 PF No. -- 3 2 0 1 PF No. -- 4 2 0 1 2 0 3 PF No. -- 5 2 0 3 4 0 3 PF No. -- 6 4 0 2 PF No. -- 7 4 3 2 PF No. -- 8 0 3 2 PF No. -- 9 0 3 2 0 3 2 1 3 2 PF No. -- 10 1 3 2 1 0 2 PF No. -- 11
  • 25. 25 | P a g e 1 0 2 1 0 7 PF No. -- 12 1 0 7 1 0 7 The number of page faults using LRU are 12 RESULT: Thus a UNIX C program to implement LRU page replacement is executed successfully.
  • 26. 26 | P a g e Experiment No: 10: Implement any file allocation technique (Linked, Indexed or Contiguous) a) SEQUENTIAL FILE ALLOCATION AIM: To implement sequential file allocation technique. ALGORITHM: Step 1: Start the program. Step 2: Get the number of files. Step 3: Get the memory requirement of each file. Step 4: Allocate the required locations to each in sequential order. a). Randomly select a location from available location s1= random(100); b). Check whether the required locations are free from the selected location. c). Allocate and set flag=1 to the allocated locations. Step 5: Print the results fileno, length , Blocks allocated. Step 6: Stop the program PROGRAM: #include<stdio.h> int main() { int f[50],i,st,j,len,c,k; for(i=0;i<50;i++) f[i]=0; printf("n Enter the starting block & length of file"); scanf("%d%d",&st,&len); for(j=st;j<(st+len);j++) { if(f[j]==0) { f[j]=1; printf("n%d->%d",j,f[j]); } else { printf("Block already allocated"); break; } } if(j==(st+len)) printf("n the file is allocated to disk"); } Output: Enter the starting block & length of file 4 5 4->1 5->1 6->1 7->1 8->1 The file is allocated to disk
  • 27. 27 | P a g e b) LINKED FILE ALLOCATION AIM: AIM: To write a C program to implement File Allocation concept using the technique Linked List Technique. ALGORITHM: Step 1: Start the Program Step 2: Get the number of files. Step 3: Allocate the required locations by selecting a location randomly Step 4: Check whether the selected location is free. Step 5: If the location is free allocate and set flag =1 to the allocated locations. Step 6: Print the results file no, length, blocks allocated. Step 7: Stop the execution PROGRAM: #include<stdio.h> main() { int f[50],p,i,j,k,a,st,len,n,c; clrscr(); for(i=0;i<50;i++) f[i]=0; printf("Enter how many blocks that are already allocated"); scanf("%d",&p); printf("nEnter the blocks no.s that are already allocated"); for(i=0;i<p;i++) { scanf("%d",&a); f[a]=1; } printf("Enter the starting index block & length"); scanf("%d%d",&st,&len); k=len; for(j=st;j<(k+st);j++) { if(f[j]==0) { f[j]=1; printf("n%d->%d",j,f[j]); } else { printf("n %d->file is already allocated",j); k++; } } } OUTPUT: Enter how many blocks are already allocated 3 Enter the blocks no’s that are already allocated 4 7 9 Enter the starting index block & length 3 7 3-> 1
  • 28. 28 | P a g e 4-> File is already allocated 5->1 6->1 7-> File is already allocated 8->1 9-> File is already allocated 10->1 11->1 12->1 RESULT: Thus the program to implement the linked file allocation was executed successfully c) INDEXED FILE ALLOCATION AIM: To write a C program to implement file Allocation concept using the indexed allocation Technique ALGORITHM: Step 1: Start the Program Step 2: Get the number of files. Step 3: Get the memory requirement of each file. Step 4: Allocate the required locations by selecting a location randomly. Step 5: Print the results file no,length, blocks allocated. Step 6: Stop the execution. PROGRAM #include<stdio.h> int f[50],i,k,j,inde[50],n,c,count=0,p; main() { for(i=0;i<50;i++) f[i]=0; x: printf("enter index blockt"); scanf("%d",&p); if(f[p]==0) { f[p]=1; printf("enter no of files on indext"); scanf("%d",&n); } else { printf("Block already allocatedn"); goto x; } for(i=0;i<n;i++) scanf("%d",&inde[i]); for(i=0;i<n;i++) if(f[inde[i]]==1) { printf("Block already allocated"); goto x; } for(j=0;j<n;j++) f[inde[j]]=1;
  • 29. 29 | P a g e printf("n allocated"); printf("n file indexed"); for(k=0;k<n;k++) printf("n %d->%d:%d",p,inde[k],f[inde[k]]); } OUTPUT: Enter index block 9 Enter no of files on index 3 1 2 3 Allocated File indexed 9-> 1:1 9-> 2:1 9->3:1 RESULT : Thus the program to implement the indexed file allocation was executed successfully