You are on page 1of 67

Ex No :1 BASICS OF UNIX COMMANDS

I File and Directory Related commands


1) pwd
This command prints the current working directory
[user@sys108 ~]$ pwd
/home/user

2) ls
This command displays the list of files in the current working directory.
$ls –l Lists the files in the long format
$ls –t Lists in the order of last modification time
$ls –d Lists directory instead of contents
$ls -u Lists in order of last access time
[user@sys108 ~]$ ls
hello.txt first.c perl1 sample hai.c

3) cd
This command is used to change from the working directory to any other directory specified.
$cd directoryname
[user@sys108 ~]$ cd jean
[user@sys108 jean]$

4) cd ..
This command is used to come out of the current working directory.
$cd ..
[user@sys108 jean]$ cd ..
[user@sys108 ~]$

5) mkdir
This command helps us to make a directory.
$mkdir directoryname
[user@sys108 ~]$ mkdir jean
[user@sys108 ~]$ ls
hello.txt first.c perl1 sample hai.c jean

6) rmdir
This command is used to remove a directory specified in the command line. It requires the
specified directory to be empty before removing it.
$rmdir directoryname
[user@sys108 ~]$ rmdir jean
hello.txt first.c perl1 sample hai.c

7) cat
This command helps us to list the contents of a file we specify.
$cat [option][file]
cat > filename – This is used to create a new file.
cat >>filename – This is used to append the contents of the file
[user@sys108 ~]$ cat > jean1
Have a Good Day
[user@sys108 ~]$ cat >> jean1
Welcome
[user@sys108 ~]$ cat jean1
Have a Good Day
Welcome
8) cp
This command helps us to create duplicate copies of ordinary files.
$cp source destination
[user@sys108 ~]$ cp jean1 jean2
[user@sys108 ~]$ cat jean2
Have a Good Day
Welcome

9) mv
This command is used to move or rename files.
$mv source destination
[user@sys108 ~]$ mv jean1 jean3
[user@sys108 ~]$ cat jean3
Have a Good Day
Welcome

10) ln
This command is to establish an additional filename for the same ordinary file.
$ln firstname secondname
user@sys108 ~]$ ln jean2 cse1

11) rm
This command is used to delete one or more files from the directory.
$rm [option] filename
$rm –i Asks the user if he wants to delete the file mentioned.
$rm –r Recursively delete the entire contents of the directory as well as the
directory itself.
[user@sys108 ~]$ rm jean2

II) Process and status information commands


1) who
This command gives the details of who all have logged in to the UNIX system currently.
$ who
[user@sys108 ~]$ who
user tty1 2014-11-11 19:16 (:0)
user pts/0 2014-11-11 19:19 (:0.0)
user pts/1 2014-11-11 19:19 (:0.0)

2) who am i
This command tells us as to when we had logged in and the system’s name for the
connection being used. $who am i
[user@sys108 ~]$ who am i
user pts/0 2014-11-11 19:19 (:0.0)

3) date
This command displays the current date in different formats.
+%D mm/dd/yy +%w Day of the week
+%H Hr-00 to 23 +%a Abbr.Weekday
+%M Min-00 to 59 +%h Abbr.Month
+%S Sec-00 to 59 +%r Time in AM/PM
+%T HH:MM:SS +%y Last two digits of the year
[user@sys108 ~]$ date
Tue Nov 11 19:39:14 IST 2014
4) echo
This command will display the text typed from the keyboard.
$echo
[user@sys108 ~]$ echo welcome to 2015
welcome to 2015

III Text related commands


1. head
This command displays the initial part of the file. By default it displays first ten lines of the
file.
$head [-count] [filename]
[user@sys108 ~]$ head -1 jean3
Have a Good Day

2. tail
This command displays the later part of the file. By default it displays last ten lines of the
file.
$tail [-count] [filename]
[user@sys108 ~]$ tail -1 jean3
Welcome

3. wc
This command is used to count the number of lines, words or characters in a file.
$wc [-lwc] filename
[user@sys108 ~]$ wc -lwc jean3
2 4 24 jean3

4. find
The find command is used to locate files in a directory and in a subdirectory.
The –name option
This lists out the specific files in all directories beginning from the named
directory. Wild cards can be used.
The –type option
This option is used to identify whether the name of files specified are
ordinary files or directory files. If the name is a directory then use “-type d
“and if it is a file then use “-type f”.
The –mtime option
This option will allow us to find that file which has been modified before
or after a specified time. The various options available are –mtime n(on a
particular day),-mtime +n(before a particular day),-mtime –n(after a particular
day)
The –exec option
This option is used to execute some commands on the files that are found
by the find command.
[user@sys108 ~]$ find fc.c
fc.c

IV File Permission commands


1) chmod
Changes the file/directory permission mode: $ chmod 777 file1
Gives full permission to owner, group and others
$ chmod o-w file1
Removes write permission for others.
[user@sys108 ~]$ chmod 777 welcome.txt
V Useful Commands:
1) exit - Ends your work on the UNIX system.
[user@sys108 ~]$ exit
exit
There are stopped jobs.

2) Ctrl-l or clear
Clears the screen.
[user@sys108 ~]$ clear
[user@sys108 ~]$

3) Ctrl-c
Stops the program currently running.

4) Ctrl-z
Pauses the currently running program.

5) man COMMAND
Looks up the UNIX command COMMAND in the online manual pages.
[user@sys108 ~]$ man
What manual page do you want?
[user@sys108 ~]$ man ls

6) history
List all commands typed so far.
[user@sys108 ~]$ history
109 man
110 man help
111 man ls
112 history

7) more FILE
Display the contents of FILE, pausing after each screenful.
There are several keys which control the output once a screenful has been printed.
<enter> Will advance the output one line at a time.
<space bar> Will advance the output by another full screenful.
"q" Will quit and return you to the UNIX prompt.
[user@sys108 ~]$ more jean3
Have a Good Day
Welcome

8) less FILE
"less" is a program similar to "more", but which allows backward movement
in the file as well as forward movement.
[user@sys108 ~]$ less jean3
Have a Good Day
Welcome
jean3 (END)

9) lpr FILE
To print a UNIX text or PostScript file, type the following command at the system
prompt:
[user@sys108 ~]$ lpr jean3
lpr: Error - no default destination available.
Ex. No: 2(a)Implementation of UNIX system calls : fork, exec, getpid, exit, wait, close

AIM
To write a program for implementing process management using the following
system calls of UNIX operating system: fork, exec, getpid, exit, wait, close.

ALGORITHM
1. Read the input from the command line.
2. Use fork() system call to create process, getppid() system call used to get the par-
ent process ID and getpid() system call used to get the current process ID
3. execvp() system call used to execute that command given on that command line
argument
4. execlp() system call used to execute specified command.
5. Open the directory at specified in command line input.
6. Display the directory contents.

PROGRAM

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char * argv[])
{
char * ls_args[3] = { "ls", "-l", NULL} ;
pid_t c_pid, pid;
int status;
c_pid = fork();
if (c_pid == 0)
{
printf("Child: executing ls\n");
execvp( ls_args[0], ls_args);
perror("execve failed");
}
else if (c_pid > 0)
{
if( (pid = wait(&status)) < 0)
{
perror("wait");
_exit(1);
}
printf("Parent: finished\n");
}else
{
perror("fork failed");
_exit(1);
}
return 0;
}
OUTPUT
[user@sys108 ~]$ cc simulate.c
[user@sys108 ~]$ ./a.out
Child: executing
Hello.txt
Sample.txt
Second.txt
Parent: finished

RESULT
Thus the program for implementation of various UNIX system calls was executed
successfully
Ex No:2 (b) Implementation of Unix system calls : opendir, readdir.

AIM
To write a program for implementing the following directory system calls of UNIX
operating system: opendir, readdir.

ALGORITHM
1.Open the directory specified in command line input.
2. Display the directory contents.

PROGRAM
#include<sys/types.h>
#include<dirent.h>
#include<stdio.h>
main(int c,char* arg[])
{
DIR *d;
struct dirent *r;
d=opendir(arg[1]);
printf("\n\t Name of the Files \n");
while((r=readdir(d)) != NULL)
printf("\t %s \n",r->d_name);
}

OUTPUT
[user@sys108 ~]$ cc dr.c
[user@sys108 ~]$ ./a.out lab_print
Name of the Files
pri_output.doc
sjf_output.doc
fcfs_output.doc
rr_output.doc
ipc_pipe_output.doc
pro_con_prob_output.doc

RESULT
Thus the program for implementing directory system calls was successfully executed.
Ex No: 3 SIMULATION OF UNIX COMMANDS

AIM
To write a C program to simulate UNIX commands like ls,cp,grep.

ALGORITHM
1. Create a file using cat command.
2. Simulate ls command to list all the files in current working directory
3. Open the file in read mode and copy the contents of the file.
4. Input the word to be searched in the file.
5. Display the word if searching is successful.

PROGRAM
(i) ls
#include <sys/types.h>
#include <sys/dir.h>
#include <sys/param.h>
#include <stdio.h>
#define FALSE 0
#define TRUE 1
extern int alphasort();
char pathname[MAXPATHLEN];
main() {
int count,i;
struct dirent **files;
int file_select();
if (getwd(pathname) == NULL )
{
printf("Error getting pathn");
}
printf("Current Working Directory = %sn",pathname);
count = scandir(pathname, &files, file_select, alphasort);
if (count <= 0)
{
printf("No files in this directoryn");
}
printf("Number of files = %dn",count);
for (i=1;i<count;++ i)
printf("%s \n",files[i-1]->d_name);
}
int file_select(struct direct *entry)
{
if ((strcmp(entry->d_name, ".") == 0) ||(strcmp(entry->d_name, "..") == 0))
return (FALSE);
else
return (TRUE);
}

OUTPUT
[user@sys108 ~]$ gcc list.c
[user@sys108 ~]$./a.out
Current working directory=/home/student/
Number of files=57
(ii) cp
#include<sys/types.h>
#include<sys/stat.h>
#include<stdio.h>
#include<fcntl.h>
main( int argc,char *argv[] )
{
int i,fd1,fd2;
char *file1,*file2,buf[2];
file1=argv[1];
file2=argv[2];
printf("file1=%s file2=%s",file1,file2);
fd1=open(file1,O_RDONLY,0777);
fd2=creat(file2,0777);
while(i=read(fd1,buf,1)>0)
write(fd2,buf,1);
close(fd1);
close(fd2);
}

OUTPUT
[user@sys108 ~]$ cat > first.txt
hello
hai
[user@sys108 ~]$ gcc copy.c
[user@sys108 ~]$ ./a.out first.txt second.txt
[user@sys108 ~]$ cat second.txt
hello
hai

(iii) grep
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include<string.h>
#include <fcntl.h>
void match_pattern(char *argv[])
{
int fd,r,j=0;
char temp,line[100];
if((fd=open(argv[2],O_RDONLY)) != -1)
{
while((r=read(fd,&temp,sizeof(char)))!= 0)
{
if(temp!='\n')
{
line[j]=temp;
j++;
}
else
{
if(strstr(line,argv[1])!=NULL)
printf("%s\n",line);
memset(line,0,sizeof(line));
j=0;
}

}
}
}

main(int argc,char *argv[])


{
struct stat stt;
if(argc==3)
{
if(stat(argv[2],&stt)==0)
match_pattern(argv);
else
{
perror("stat()");
exit(1);
}
}
}

OUTPUT
[user@sys108 ~]$ cc grep.c
[user@sys108 ~]$ ./a.out hello first.txt
hello

RESULT
Thus the C program to simulate UNIX commands like ls,cp,grep was executed
successfully.
Ex.No : 4(a) COMPARISON OF TWO STRINGS

AIM
To write a shell program to compare the two strings.

ALGORITHM
1. Enter into the vi editor and go to the insert mode for entering the code
2. Read the first string.
3. Read the second string
4. Compare the two strings using the if loop
5. If the condition satisfies then print that two strings are equal else print two
strings are not equal.
6. Enter into the escape mode for the execution of the result and verify the output

PROGRAM
echo “enter the first string”
read str1
echo “enter the second string”
read str2
if [ $str1 = $str2 ]
then
echo “strings are equal”
else
echo “strings are unequal”
fi

OUTPUT
[user@sys108 ~]$ vi compare.sh
[user@sys108 ~]$ sh compare.sh
Enter first string: hai
Enter second string: cse
strings are unequal

RESULT
Thus the shell program to compare the two strings is executed and output is verified
successfully.
Ex.No: 4(b) MAXIMUM OF THREE NUMBERS

AIM
To write a shell program to find greatest of three numbers.

ALGORITHM
1. Declare the three variables.
2. Check if A is greater than B and C.
3. If so print A is greater.
4. Else check if B is greater than C.
5. If so print B is greater.
6. Else print C is greater.

PROGRAM
echo "Enter A"
read a
echo "Enter B"
read b
echo "Enter C"
read c
if [ $a -gt $b -a $a -gt $c ]
then
echo "A is greater"
elif [ $b -gt $a -a $b -gt $c ]
then
echo "B is greater"
else
echo "C is greater"
fi

OUTPUT
[user@sys108 ~]$ vi greater.sh
[user@sys108 ~]$ sh greater.sh
Enter A:23
Enter B:45
Enter C:67
C is greater

RESULT
Thus the shell program to find the maximum of three numbers is executed and output
is verified successfully.
Ex: No : 5(a) FCFS SCHEDULING

AIM
To write a C program to implement FCFS scheduling algorithm.

ALGORITHM

1. Get the number of processes and their burst time.


2. Initialize the waiting time for process 1 and 0.
3. The waiting time for the other processes are calculated as follows:
for(i=2;i<=n;i++),wt.p[i]=p[i-1]+bt.p[i-1].
4. The waiting time of all the processes is summed then average value time is
calculated.
5. The waiting time of each process and average times are displayed.

PROGRAM
#include<stdio.h>
struct process
{
int pid; int bt; int wt,tt;
}
p[10];
int main(){
int i,n,totwt,tottt,avg1,avg2;
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;
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=%d \t avg2=%d \t",avg1,avg2);
return 0;
}
OUTPUT
[user@sys108 ~]$ vi first.c
[user@sys108 ~]$ cc first.c
[user@sys108 ~]$ ./a.out
Enter the no 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
avg1=2 avg2=6

RESULT
Thus the FCFS program for scheduling was executed and verified successfully.
Ex: No : 5(b) SJF SCHEDULING

AIM
To write a C program to implement Shortest Job First scheduling algorithm.

ALGORITHM

1. Initialize the waiting time for process 1 as 0.


2. The processes are stored according to their burst time.
3. The waiting time for the processes are calculated as follows:
for(i=2;i<=n;i++).wt.p[i]=p[i=1]+bt.p[i-1].
4. The waiting time of all the processes summed and then the average time is
calculated.
5. The waiting time of each processes and average time are displayed.

PROGRAM

#include<stdio.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;
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++; }
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);
return 0;
}

OUTPUT
[user@sys108 ~]$ vi shortest.c
[user@sys108 ~]$ cc shortest.c
[user@sys108 ~]$ ./a.out
Enter the number of process: 3
Enter the burst time: 2
Enter the burst time: 4
Enter the burst time: 6
Process id bt wt tt
1 2 0 2
2 4 2 6
3 6 6 12
AVG1=2.000000 AVG2=6.000000

RESULT
Thus the SJF program was executed and verified successfully.
Ex. No : 5(c) PRIORITY SCHEDULING

AIM
To write a C program to implement priority scheduling algorithm.

ALGORITHM

1. Read burst time, waiting time, turnaround time and priority.


2. Initialize the waiting time for process 1 and 0
3. Based up on the priority process are arranged.
4. The waiting time for other processes are calculated based on priority.
5. The waiting time of all the processes is summed and then the average waiting time is
calculated.
6. The waiting time of each process and average waiting time are displayed based on the
priority.

PROGRAM

#include<stdio.h>
struct process{
int pid; int bt; int wt; int tt; int prior;
} p[10],temp;
int main(){
int i,j,n,totwt,tottt,arg1,arg2;
printf("Enter the number of process");
scanf("%d",&n);
for(i=1;i<=n;i++){
p[i].pid=i;
printf("Enter the burst time");
scanf("%d",&p[i].bt);
printf("\n Enter the priority");
scanf("%d",&p[i].prior);
}
for(i=1;i<n;i++){
for(j=i+1;j<=n;j++){
if(p[i].prior>p[j].prior){
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;
temp.prior=p[i].prior;
p[i].prior=p[j].prior;
p[j].prior=temp.prior;
}}}
p[i].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;
totwt=tottt=0;
printf("\n process \t bt \t wt \t tt");
while(i<=n){
printf("\n%d\t %d\t %d\t %d\t",p[i].pid,p[i].bt,p[i].wt,p[i].tt);
totwt=p[i].wt+totwt;
tottt=p[i].tt+tottt;
i++; }
arg1=totwt/n;
arg2=tottt/n;
printf("\n arg1=%d \t arg2=%d\t",arg1,arg2);
return 0;
}

OUTPUT
[user@sys108 ~]$ vi priority.c
[user@sys108 ~]$ cc priority.c
[user@sys108 ~]$ ./a.out
Enter the number 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 bt wt tt
2 4 0 4
3 6 4 10
1 2 10 12

avg1=4 avg2=8

RESULT
Thus the priority scheduling program was executed and verified successfully.
Ex: No : 5(d) ROUND ROBIN SCHEDULING

AIM
To write a C program to implement Round Robin Scheduling algorithm.

ALGORITHM

1. Initialize the array for Round Robin circular queue as ‘0’.

2. The burst time of each process is divided and the quotients are stored on the round
robin array.

3. According to the array value the waiting time for each process and the average time
are calculated as line the other scheduling.

4. The waiting time for each process and average times are displayed.

PROGRAM
#include<stdio.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;
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;
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);
return 0; }

OUTPUT
[user@sys108 ~]$ vi roundrobin.c
[user@sys108 ~]$ cc roundrobin.c
[user@sys108 ~]$ ./a.out
Enter the number 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
2 7 9
3 9 11
2 11 12
3 12 14
3 14 15
Average Waiting Time: 21.666666
Average TurnAround Time: 26.666666

RESULT
Thus the Round Robin scheduling program was executed and verified successfully.
Ex.No : 6 IMPLEMENTATION OF SEMAPHORE

AIM
To implement Producer Consumer problem using Semaphore.

ALGORITHM
1. Union a variable “mysemun” as integer type to implement semaphore.
2. A buffer “sembuf” variable for producer consumer is written
3. In producer, buffer “sembuf” full condition is checked and if it is full then it is
displayed.
4. In consumer, buffer “sembuf” empty condition is checked and a message displayed.
5. Producer produces an element sequentially from main().and a message displayed.
6. Consumer consumes an element sequentially from main().and a message displayed.
7. The producer consumer produces messages are displayed till the user defines in the
program.

PROGRAM
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/sem.h>
#include<sys/shm.h>
#define num 10
#define se 10
#define sf 0
int main()
{
int rc,pid,semid;
int shmid,status,i;
char elem;
union semun
{
int val;
}mysemun;
struct sembuf waitempty={se,-1,SEM_UNDO};
struct sembuf signalempty={se,1,IPC_NOWAIT};
struct sembuf waitfull={sf,-1,SEM_UNDO};
struct sembuf signalfull={sf,1,IPC_NOWAIT};
struct shmid_ds myshmid_ds;
void *shmptr;
semid=semget(IPC_PRIVATE,2,0666 | IPC_CREAT);
mysemun.val=num;
semctl(semid,se,SETVAL,mysemun);
mysemun.val=0;
semctl(semid,sf,SETVAL,mysemun);
shmid=shmget(IPC_PRIVATE,num,0666 | IPC_CREAT);
pid=fork();
if(pid==0)
{
shmptr=shmat(shmid,0,SHM_R);
for(i=0;i<10;i++)
{
semop(semid,&waitfull,1);
elem=*((char *)shmptr+(i%num));
printf("consumed element %c\n",elem);
semop(semid,&signalempty,1);
sleep(1);
}
exit(0);
}
else
{
shmptr=shmat(shmid,0,SHM_W);
for(i=0;i<10;i++)
{
semop(semid,&waitempty,1);
elem='i'+i;
printf("produced element %c\n",elem);
*((char *)shmptr+(i%num))=elem;
semop(semid,&signalfull,1);
sleep(2);
}
}
wait(&status);
shmctl(shmid,IPC_RMID,&myshmid_ds);
semctl(semid,se,IPC_RMID,mysemun);
exit(0);
}

OUTPUT
[user@sys108 ~]$ vi producer.c
[user@sys108 ~]$ cc producer.c
[user@sys108 ~]$ ./a.out
produced element r
consumed element r
produced element c
consumed element c
produced element d
consumed element d
produced element f
consumed element f
produced element h
consumed element h
produced element i
consumed element i
produced element j
consumed element j
produced element k
consumed element k
produced element l
consumed element l
produced element m
consumed element m

RESULT
Thus the Producer Consumer problem using Semaphore is written and executed successfully.
Ex.No: 7 IMPLEMENTATION OF SHARED MEMORY AND IPC
AIM
To write a C program to illustrate interprocess communication using Shared Memory system calls.
ALGORITHM
1. Create shared memory using shmget( ) system call
2. If successfull it returns positive value
3. Attach the created shared memory using shmat( ) systemcall.
4. Write to shared memory using shmsnd( ) system call
5. Read the contents from shared memory using shmrcv( ) systemcall
PROGRAM
#include <stdio.h>
#include <sys/shm.h>
#include <sys/stat.h>
int main () {
int segment_id;
char* shared_memory;
struct shmid_ds shmbuffer;
int segment_size;
const int shared_segment_size = 0x6400;
segment_id = shmget (IPC_PRIVATE, shared_segment_size,
IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR);
shared_memory = (char*) shmat (segment_id, 0, 0);
printf ("shared memory attached at address %p\n", shared_memory);
shmctl (segment_id, IPC_STAT, &shmbuffer);
segment_size = shmbuffer.shm_segsz;
printf ("segment size: %d\n", segment_size);
sprintf (shared_memory, "Hello, World");
shmdt (shared_memory);
shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0);
printf ("shared memory reattached at address %p\n", shared_memory);
printf ("%s\n", shared_memory);
shmdt (shared_memory);
shmctl (segment_id, IPC_RMID, 0);
return 0; }

OUTPUT
user@sys108 ~]$ ./a.out
shared memory attached at address 0xb774d000
segment size: 25600
shared memory reattached at address 0x5000000
Hello , World.

RESULT
Thus the program for Interprocess communication using Shared Memory system calls was executed
successfully.
Ex.No : 8 BANKERS ALGORITHM FOR DEAD LOCK AVOIDANCE

AIM
To implement Deadlock Avoidance by using Banker’s Algorithm in C.

ALGORITHM

1. Start the program.


2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether it’s possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety or not if we allow the request.
9. Stop the program.

PROGRAM
#include<stdio.h>
#include<process.h>
int main()
{
int allocation[10][5], max[10][5], need[10][5], available[3], flag[10], sq[10];
int n, r, i, j, k, count, count1 = 0;
printf("\n Input the number of processes running ( <10 )..");
scanf("%d", &n);
for (i = 0; i<10; i++)
flag[i] = 0;
printf("\n Input the number of resources ( <5 )..");
scanf("%d", &r);
printf("\n Input the allocation matrix for the processes in row major order..\n");
for (i = 0; i<n; i++)
{
printf("\n Process %d\n", i);
for (j = 0; j<r; j++)
{
printf("\n Resource %d\n", j);
scanf("%d", &allocation[i][j]);
}
}
printf("\n Input the no. of resources that a process can maximum have..\n");
for (i = 0; i<n; i++)
{
printf("\n Process %d\n", i);
for (j = 0; j<r; j++)
{
printf("\n Resource %d\n", j);
scanf("%d", &max[i][j]);
}
}
printf("\n Input the no. of available instances of each resource..\n");
for (i = 0; i<r; i++)
{
printf("\n Resource %d : ", i);
scanf("%d", &available[i]);
}
printf("\n The need matrix is as follows : \n");
for (i = 0; i<n; i++)
{
for (j = 0; j<r; j++)
{
need[i][j] = max[i][j] - allocation[i][j];
printf("\t %d", need[i][j]);
}
printf("\n");
}
do{
for (k = 0; k<n; k++)
{
for (i = 0; i<n; i++)
{
if (flag[i] == 0)
{
count = 0;
for (j = 0; j<r; j++)
{
if (available[j] >= need[i][j])
count++;
}
if (count == r)
{
count1++;
flag[i] = 1;
sq[count1 - 1] = i;
for (j = 0; j<r; j++)
{
available[j] = available[j] + allocation[i][j];
}
break;
}
}
}
}
if (count1 != n)
{
printf("\n---------------IT IS UNSAFE STATE---------------");
break;
}
} while (count1 != n);
if (count1 == n)
{
printf("\n *******************IT IS SAFE STATE*******************");
printf("\n The safe sequence is....\n");
for (i = 0; i<n; i++)
printf("\t P%d", sq[i]);
printf("\n");
printf("\n The available matrix is now : ");
for (i = 0; i<r; i++)
printf("\t %d", available[i]);
}
return 0;
}

OUTPUT

[user@sys108 ~]$ vi avoidance.c


[user@sys108 ~]$ cc avoidance.c
[user@sys108 ~]$ ./a.out
Input the number of processes running ( <10 )..2
Input the number of resources ( <5 )..2
Input the allocation matrix for the processes in row major order..
Process 0
Resource 0
1
Resource 1
0
Process 1
Resource 0
2
Resource 1
1
Input the no. of resources that a process can maximum have.
Process 0
Resource 0
2
Resource 1
1
Process 1
Resource 0
3
Resource 1
2
Input the no. of available instances of each resource..
Resource 0 : 8
Resource 1 : 4
The need matrix is as follows :
1 1
1 1

*******************IT'S A SAFE STATE*******************


The safe sequence is....
P0 P1
The available matrix is now : 11 5

RESULT
Thus deadlock avoidance by using Banker’s Algorithm in C was executed successfully.
Ex. No: 9 DEADLOCK DETECTION ALGORITHM

AIM
To write a C program to implement DeadLock Detection using Banker’s Algorithm.

ALGORITHM
1. Start the program.
2. Get the values of resources and processes.
3. Get the avail value.
4. After allocation find the need value.
5. Check whether its possible to allocate.
6. If it is possible then the system is in safe state.
7. Else system is not in safety state.
8. If the new request comes then check that the system is in safety or not if we allow the request.

PROGRAM
#include<stdio.h>
struct da
{
int max[10],a1[10],need[10],before[10],after[10];
}p[10];
void main()
{
int i,j,k,l,r,n,tot[10],av[10],cn=0,cz=0,temp=0,c=0;
printf("\n ENTER THE NO. OF PROCESSES:");
scanf("%d",&n);
printf("\n ENTER THE NO. OF RESOURCES:");
scanf("%d",&r);
for(i=0;i<n;i++)
{
printf("PROCESS %d \n",i+1);
for(j=0;j<r;j++)
{
printf("MAXIMUM VALUE FOR RESOURCE %d:",j+1);
scanf("%d",&p[i].max[j]);
}
for(j=0;j<r;j++)
{
printf("ALLOCATED FROM RESOURCE %d:",j+1);
scanf("%d",&p[i].a1[j]);
p[i].need[j]=p[i].max[j]-p[i].a1[j];
}
}
for(i=0;i<r;i++)
{
printf("ENTER TOTAL VALUE OF RESOURCE %d:",i+1);
scanf("%d",&tot[i]);
}
for(i=0;i<r;i++)
{
for(j=0;j<n;j++)
temp=temp+p[j].a1[i];
av[i]=tot[i]-temp;
temp=0;
}
printf("\n\t RESOURCES ALLOCATED NEEDED TOTAL AVAIL");
for(i=0;i<n;i++)
{
printf("\n P%d \t",i+1);
for(j=0;j<r;j++)
printf("%d",p[i].max[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].a1[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].need[j]);
printf("\t");
for(j=0;j<r;j++)
{
if(i==0)
printf("%d",tot[j]);
}
printf(" ");
for(j=0;j<r;j++)
{
if(i==0)
printf("%d",av[j]);
}
}
printf("\n\n\t AVAIL BEFORE\T AVAIL AFTER ");
for(l=0;l<n;l++)
{
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
if(p[i].need[j] >av[j])
cn++;
if(p[i].max[j]==0)
cz++;
}
if(cn==0 && cz!=r)
{
for(j=0;j<r;j++)
{
p[i].before[j]=av[j]-p[i].need[j];
p[i].after[j]=p[i].before[j]+p[i].max[j];
av[j]=p[i].after[j];
p[i].max[j]=0;
}
printf("\n P %d \t",i+1);
for(j=0;j<r;j++)
printf("%d",p[i].before[j]);
printf("\t");
for(j=0;j<r;j++)
printf("%d",p[i].after[j]);
cn=0;
cz=0;
c++;
break;
}
else
{
cn=0;cz=0;
}
}
}
if(c==n)
printf("\n THE ABOVE SEQUENCE IS A SAFE SEQUENCE");
else
printf("\n DEADLOCK OCCURED");
}

OUTPUT
[user@sys108 ~]$ vi deadlock1.c
[user@sys108 ~]$ cc deadlock1.c
[user@sys108 ~]$ ./a.out
ENTER THE NO. OF PROCESSES:4
ENTER THE NO. OF RESOURCES:3
PROCESS 1
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:1
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:0
PROCESS 2
MAXIMUM VALUE FOR RESOURCE 1:6
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:3
ALLOCATED FROM RESOURCE 1:5
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 3
MAXIMUM VALUE FOR RESOURCE 1:3
MAXIMUM VALUE FOR RESOURCE 2:1
MAXIMUM VALUE FOR RESOURCE 3:4
ALLOCATED FROM RESOURCE 1:2
ALLOCATED FROM RESOURCE 2:1
ALLOCATED FROM RESOURCE 3:1
PROCESS 4
MAXIMUM VALUE FOR RESOURCE 1:4
MAXIMUM VALUE FOR RESOURCE 2:2
MAXIMUM VALUE FOR RESOURCE 3:2
ALLOCATED FROM RESOURCE 1:0
ALLOCATED FROM RESOURCE 2:0
ALLOCATED FROM RESOURCE 3:2

ENTER TOTAL VALUE OF RESOURCE 1:9


ENTER TOTAL VALUE OF RESOURCE 2:3
ENTER TOTAL VALUE OF RESOURCE 3:6

RESOURCES ALLOCATED NEEDED TOTAL AVAIL


P1 322 100 222 936 112
P2 613 511 102
P3 314 211 103
P4 422 002 420

AVAIL BEFORE AVAIL AFTER


P2 010 623
P1 401 723
P3 620 934
P4 514 936
THE ABOVE SEQUENCE IS A SAFE SEQUENCE

RESULT
Thus the C program for Dead Lock Detection was executed successfully.
Ex.No:10 THREADING & SYNCHRONIZATION APPLICATIONS

AIM
To implement POSIX thread operations and synchronize using Mutex variable.

ALGORITHM
1. Start the process
2. Intialize mutex lock ,thread id and required other variables
3. Create POSIX threads using pthread_create
4. Define thread task by creating new function.
5. Synchronize threads using mutex lock and unlock variables
6. Using pthread_join allow threads to wait until parent process completes
7. Destroy the synchronization variable mutex using pthread_mutex_destroy

PROGRAM
#include<stdio.h>
#include<string.h>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
pthread_t tid[2];
int counter;
void* doSomeThing(void *arg)
{
unsigned long i = 0;
counter += 1;
printf("\n Task %d started\n", counter);
for(i=0; i<(0xFFFFFFFF);i++);
printf("\n Job %d finished\n", counter);
return NULL;
}
int main(void)
{
int i = 0;
int err;
while(i < 2) {
err = pthread_create(&(tid[i]), NULL, &doSomeThing, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
i++; }
pthread_join(tid[0], NULL);
pthread_join(tid[1], NULL);
return 0;
}
OUTPUT
cc thread.c -lpthread
[user@sys108 ~]$ ./a.out
Job 1 started
Job 2 started
Job 1 finished
Job 2 finished

RESULT
Thus the program for Threading & Synchronization is written and executed successfully.
Ex. No : 11(a) FIRST FIT MEMORY ALLOCATION

AIM
To write a C program to implement First fit Memory allocation technique

ALGORITHM
1. Enter the number of blocks and number of files.
2. Enter the size of the blocks.
3. Enter the size of the files.
4. First fit chooses the first available block that is large enough.
5. Display File number, File size, Occupied block number and size.

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

OUTPUT
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

File No File Size Block No Block Size Fragment


1 1 1 5 4
2 4 3 7 3

RESULT
Thus First fit Memory allocation technique was executed successfully.
Ex. No : 11(b) WORST FIT MEMORY ALLOCATION

AIM
To write a C program to implement Worst fit Memory allocation technique

ALGORITHM
1. Enter the number of blocks and number of files.
2. Enter the size of the blocks.
3. Enter the size of the files.
4. Worst fit occupies the largest available block.
5. Display File number, File size, occupied block number and size.

PROGRAM
#include<stdio.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];
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)
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]);
}
OUTPUT
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
File No File Size Block No Block Size Fragment
1 1 3 7 6
2 4 1 5 1

RESULT
Thus Worst fit Memory allocation technique was executed and verified
successfully.
CS8461-Operating Systems Department of CSE 2018-2019

Ex. No : 11(c) BEST FIT MEMORY ALLOCATION

AIM
To write a C program to implement Best fit Memory allocation technique

ALGORITHM
1. Enter the number of blocks and number of files.
2. Enter the size of the blocks.
3. Enter the size of the files.
4. Best fit chooses the block that is closest in size to the request.
5. Display File number, File size, occupied block number and size.

PROGRAM
#include<stdio.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];
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];

39
CS8461-Operating Systems Department of CSE 2018-2019

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]);
}

OUTPUT
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

File No File Size Block No Block Size Fragment


1 1 2 2 1
2 4 1 5 1

RESULT
Thus Best fit Memory allocation technique was executed and verified successfully.

40
CS8461-Operating Systems Department of CSE 2018-2019

Ex.No: 12 PAGING TECHNIQUE OF MEMORY MANAGEMENT

AIM
To implement the Memory management policy- Paging using C.

ALGORITHM
Step 1: Read all the necessary input from the keyboard.
Step 2: Pages - Logical memory is broken into fixed - sized blocks.
Step 3: Frames – Physical memory is broken into fixed – sized blocks.
Step 4: Calculate the physical address using the following
Physical address = ( Frame number * Frame size ) + offset
Step 5: Display the physical address.

PROGRAM
#include <stdio.h>
struct pstruct
{
int fno;
int pbit;
}ptable[10];

int pmsize,lmsize,psize,frame,page,ftable[20],frameno;

void info()
{
printf("\n\nMEMORY MANAGEMENT USING PAGING\n\n");
printf("\n\nEnter the Size of Physical memory: ");
scanf("%d",&pmsize);
printf("\n\nEnter the size of Logical memory: ");
scanf("%d",&lmsize);
printf("\n\nEnter the partition size: ");
scanf("%d",&psize);
frame = (int) pmsize/psize;
page = (int) lmsize/psize;
printf("\nThe physical memory is divided into %d no.of frames\n",frame);
printf("\nThe Logical memory is divided into %d no.of pages",page);
}

void assign()
{
int i;
for (i=0;i<page;i++)
{
ptable[i].fno = -1;
ptable[i].pbit= -1;
}
41
CS8461-Operating Systems Department of CSE 2018-2019

for(i=0; i<frame;i++)
ftable[i] = 32555;
for (i=0;i<page;i++)
{
printf("\n\nEnter the Frame number where page %d must be placed: ",i);
scanf("%d",&frameno);
ftable[frameno] = i;
if(ptable[i].pbit == -1)
{
ptable[i].fno = frameno;
ptable[i].pbit = 1;
}
}
printf("\n\nPAGE TABLE\n\n");
printf("PageAddress FrameNo. PresenceBit\n\n");
for (i=0;i<page;i++)
printf("%d\t\t%d\t\t%d\n",i,ptable[i].fno,ptable[i].pbit);
printf("\n\n\n\tFRAME TABLE\n\n");
printf("FrameAddress PageNo\n\n");
for(i=0;i<frame;i++)
printf("%d\t\t%d\n",i,ftable[i]);
}
void cphyaddr()
{
int laddr,paddr,disp,phyaddr,baddr;
getch();
printf("\n\n\n\tProcess to create the Physical Address\n\n");
printf("\nEnter the Base Address: ");
scanf("%d",&baddr);
printf("\nEnter theLogical Address: ");
scanf("%d",&laddr);
paddr = laddr / psize;
disp = laddr % psize;
if(ptable[paddr].pbit == 1 )
phyaddr = baddr + (ptable[paddr].fno*psize) + disp;
printf("\nThe Physical Address where the instruction present: %d",phyaddr);
}
void main()
{
info();
assign();
cphyaddr();
}

OUTPUT
42
CS8461-Operating Systems Department of CSE 2018-2019

[user@sys108 ~]$ vi memoryman.c


[user@sys108 ~]$ cc memoryman.c
[user@sys108 ~]$ ./a.out

MEMORY MANAGEMENT USING PAGING


Enter the Size of Physical memory: 8
Enter the size of Logical memory: 6
Enter the partition size: 2
The physical memory is divided into 4 no.of frames
The Logical memory is divided into 2 no.of pages
Enter the Frame number where page 0 must be placed: 30
Enter the Frame number where page 1 must be placed: 40

PAGE TABLE
PageAddress FrameNo. PresenceBit
0 30 1
1 40 1

FRAME TABLE
FrameAddress PageNo
0 32555
1 32555
2 32555
3 0

Process to create the Physical Address


Enter the Base Address: 1000
Enter theLogical Address: 6
The Physical Address where the instruction present: 1012

RESULT
Thus the Memory management policy- Paging was executed successfully.

43
CS8461-Operating Systems Department of CSE 2018-2019

Ex. No: 13(a) FIFO PAGE REPLACEMENT ALGORITHM

AIM
To write a C program to implement FIFO page replacement algorithm

ALGORITHM
1. 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. Form a 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.

PROGRAM
#include<stdio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
void main()
{
printf("\n \t\t\t FIFO PAGE REPLACEMENT ALGORITHM");
printf("\n Enter no.of frames....");
scanf("%d",&nof);
printf("Enter number of reference string..\n");
scanf("%d",&nor);
printf("\n Enter the reference string..");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\nThe given reference string:");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=1;i<=nof;i++)
frm[i]=-1;
printf("\n");
for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference np%d->\t",ref[i]);
for(j=0;j<nof;j++)
{
44
CS8461-Operating Systems Department of CSE 2018-2019

if(frm[j]==ref[i])
{
flag=1;
break; }}
if(flag==0)
{
pf++;
victim++;
victim=victim%nof;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
} }
printf("\n\n\t\t No.of pages faults...%d",pf);
}

OUTPUT
[user@sys108 ~]$ vi fifo.c
[user@sys108 ~]$ cc fifo.c
[user@sys108 ~]$ ./a.out
FIFO PAGE REPLACEMENT ALGORITHM
Enter no.of frames....4
Enter number of reference string.. 6
Enter the reference string..
564123
The given reference string:
...................................... 5 6 4 1 2 3
Reference np5-> 5 -1 -1 -1
Reference np6-> 5 6 -1 -1
Reference np4-> 5 6 4 -1
Reference np1-> 5 6 4 1
Reference np2-> 2 6 4 1
Reference np3-> 2 3 4 1
No.of pages faults...6

RESULT
Thus the program for Page Replacement Algorithm using FIFO is written and executed
successfully.

45
CS8461-Operating Systems Department of CSE 2018-2019

Ex. No: 13(b) LRU PAGE REPLACEMENT ALGORITHM

AIM
To implement Least Recently Used Page Replacement algorithm in C.

ALGORITHM
Step 1: Create a queue to hold all pages in memory
Step 2: When the page is required replace the page at the head of the queue
Step 3: Now the new page is inserted at the tail of the queue
Step 4: Create a stack
Step 5: When the page fault occurs replace page present at the bottom of the stack

PROGRAM
#include<stdio.h>
int i,j,nof,nor,flag=0,ref[50],frm[50],pf=0,victim=-1;
int recent[10],lrucal[50],count=0;
int lruvictim();
void main()
{
printf("\n\t\t\t LRU PAGE REPLACEMENT ALGORITHM");
printf("\n Enter no.of Frames....");
scanf("%d",&nof);
printf(" Enter no.of reference string..");
scanf("%d",&nor);
printf("\n Enter reference string..");
for(i=0;i<nor;i++)
scanf("%d",&ref[i]);
printf("\n\n\t\t LRU PAGE REPLACEMENT ALGORITHM ");
printf("\n\t The given reference string:");
printf("\n………………………………..");
for(i=0;i<nor;i++)
printf("%4d",ref[i]);
for(i=1;i<=nof;i++)
{
frm[i]=-1;
lrucal[i]=0;
}

for(i=0;i<10;i++)
recent[i]=0;
printf("\n");
46
CS8461-Operating Systems Department of CSE 2018-2019

for(i=0;i<nor;i++)
{
flag=0;
printf("\n\t Reference NO %d->\t",ref[i]);
for(j=0;j<nof;j++)
{
if(frm[j]==ref[i])
{
flag=1;
break;
}
}
if(flag==0)
{
count++;
if(count<=nof)
victim++;
else
victim=lruvictim();
pf++;
frm[victim]=ref[i];
for(j=0;j<nof;j++)
printf("%4d",frm[j]);
}
recent[ref[i]]=i;
}
printf("\n\n\t No.of page faults...%d",pf);
getch();
}
int lruvictim()
{
int i,j,temp1,temp2;
for(i=0;i<nof;i++)
{
temp1=frm[i];
lrucal[i]=recent[temp1];
}
temp2=lrucal[0];
for(j=1;j<nof;j++)
{
if(temp2>lrucal[j])
temp2=lrucal[j];
}
47
CS8461-Operating Systems Department of CSE 2018-2019

for(i=0;i<nof;i++)
if(ref[temp2]==frm[i])
return i;
return 0;
}

OUTPUT
[user@sys108 ~]$ vi least.c
[user@sys108 ~]$ cc least.c
[user@sys108 ~]$ ./a.out
LRU PAGE REPLACEMENT ALGORITHM
Enter no.of Frames....3
Enter no.of reference string..6
Enter reference string..
654231
LRU PAGE REPLACEMENT ALGORITHM
The given reference string:
…………………. 6 5 4 2 3 1
Reference NO 6-> 6 -1 -1
Reference NO 5-> 6 5 -1
Reference NO 4-> 6 5 4
Reference NO 2-> 2 5 4
Reference NO 3-> 2 3 4
Reference NO 1-> 2 3 1
No.of page faults...6

RESULT
Thus the program for LRU Page Replacement Algorithm is written and executed
successfully.

48
CS8461-Operating Systems Department of CSE 2018-2019

Ex No: 13 (c) LFU PAGE REPLACEMENT ALGORITHM

AIM
To implement LFU page replacement technique.

ALGORITHM
1. Read Number Of Pages And Frames
2. Read Each Page Value
3. Search For Page In The Frames
4. If Not Available Allocate Free Frame
5. If No Frames Is Free Repalce The Page With The Page That Is Least frequently used.
6. Print Page Number Of Page Faults

PROGRAM
#include<stdio.h>
void main()
{
int q[20],p[50],c=0,c1,d,f,i,j,k=0,n,r,t,b[20],c2[20];
printf(“Enter no of pages:”);
scanf(“%d”,&n);
printf(“Enter the reference string:”);
for(i=0;i<n;i++)
scanf(“%d”,&p[i]);
printf(“Enter no of frames:”);
scanf(“%d”,&f);
q[k]=p[k];
printf(“\n\t%d\n”,q[k]);
c++;
k++;
for(i=1;i<n;i++)
{
c1=0;
for(j=0;j<f;j++)
{
if(p[i]!=q[j])
c1++;
}
if(c1==f)
{
c++;
if(k<f)
{
q[k]=p[i];
k++;
for(j=0;j<k;j++)
printf(“\t%d”,q[j]);
printf(“\n”);
}
else
{
for(r=0;r<f;r++)
{
49
CS8461-Operating Systems Department of CSE 2018-2019

c2[r]=0;
for(j=i-1;j<n;j–)
{
if(q[r]!=p[j])
c2[r]++;
else
break;
}
}
for(r=0;r<f;r++)
b[r]=c2[r];
for(r=0;r<f;r++)
{
for(j=r;j<f;j++)
{
if(b[r]<b[j])
{
t=b[r];
b[r]=b[j];
b[j]=t;
}
}
}
for(r=0;r<f;r++)
{
if(c2[r]==b[0])
q[r]=p[i];
printf(“\t%d”,q[r]);
}
printf(“\n”);
}
}
}
printf(“\nThe no of page faults is %d”,c);
}

OUTPUT
Enter no of pages:10
Enter the reference string:7 5 9 4 3 7 9 6 2 1
Enter no of frames:3
7
75
759
459
439
437
937
967
962
162

RESULT
Thus the program for LFU was executed successfully.
Ex No: 14 (a) SINGLE LEVEL DIRECTORY
50
CS8461-Operating Systems Department of CSE 2018-2019

AIM
To write a c program to simulate Single level directory structure.

ALGORITHM

Start the program.


Get the number of main directories to be created.
Get the name of the directory and size of the directory.
Simulate the directory level and display the structure.
Stop the program.

PROGRAM
#include<stdio.h>
main()
{
int master,s[20];
char f[20][20][20];
char d[20][20];
int i,j;
printf("Enter number of directorios:");
scanf("%d",&master);
printf("Enter names of directories:");
for(i=0;i<master;i++)
scanf("%s",&d[i]);
printf("Enter size of directories:");
for(i=0;i<master;i++)
scanf("%d",&s[i]);
printf("Enter the file names :");
for(i=0;i<master;i++)
for(j=0;j<s[i];j++)
scanf("%s",&f[i][j]);
printf("\n");
printf(" directory\tsize\tfilenames\n");
printf("*************************************************\n");
for(i=0;i<master;i++)
{
printf("%s\t\t%2d\t",d[i],s[i]);
for(j=0;j<s[i];j++)
printf("%s\n\t\t\t",f[i][j]);
printf("\n"); }
printf("\t\n");
}

OUTPUT

51
CS8461-Operating Systems Department of CSE 2018-2019

[user@sys108 ~]$ vi singlelevel.c


[user@sys108 ~]$ cc singlelevel.c
[user@sys108 ~]$ ./a.out
Enter number of directorios:2
Enter names of directories: hai hello
Enter size of directories:2 2
Enter the file names :sample test fibonacci fact
directory size filenames
*************************************************
hai 2 sample
test
hello 2 fibonacci
fact

RESULT
Thus the program to simulate Single level directory structure is executed successfully.

Ex.No: 14(b) TWO LEVEL DIRECTORY

52
CS8461-Operating Systems Department of CSE 2018-2019

AIM
To write a C program to simulate Two Level directory structures.

ALGORITHM

1. Start the program.


2. Get the number of main directories to be created, name of the directory and size of the
directory.
3. Get the number of sub directories to be created, name of the directory and size of the
directory.
4. Simulate the directory level and display the structure.
5. Stop the program.

PROGRAM
#include<stdio.h>
struct st
{
char dname[10];
char sdname[10][10];
char fname[10][10][10];
int ds,sds[10];
}dir[10];
void main()
{
int i,j,k,n;
printf("Enter number of directories:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter directory %d names:",i+1);
scanf("%s",&dir[i].dname);
printf("Enter size of directories:");
scanf("%d",&dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("Enter subdirectory name and size:");
scanf("%s",&dir[i].sdname[j]);
scanf("%d",&dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
{
printf("Enter file name:");
scanf("%s",&dir[i].fname[j][k]);
}
}
}
53
CS8461-Operating Systems Department of CSE 2018-2019

printf("\ndirname\t\tsize\tsubdirname\tsize\tfiles");
printf("\n******************************************************\n");
for(i=0;i<n;i++)
{
printf("%s\t\t%d",dir[i].dname,dir[i].ds);
for(j=0;j<dir[i].ds;j++)
{
printf("\t%s\t\t%d\t",dir[i].sdname[j],dir[i].sds[j]);
for(k=0;k<dir[i].sds[j];k++)
printf("%s\t",dir[i].fname[j][k]);
printf("\n\t\t");
}
printf("\n"); }
}

OUTPUT
[user@sys108 ~]$ vi twolevel.c
[user@sys108 ~]$ cc twolevel.c
[user@sys108 ~]$ ./a.out
Enter number of directories:2
Enter directory 1 names:colleges
Enter size of directories:1
Enter subdirectory name and size:deemed 1
Enter file name:stjosephs
Enter directory 2 names:companies
Enter size of directories:1
Enter subdirectory name and size:MNC 1
Enter file name:CTS
dirname size subdirname size files
******************************************************
colleges 1 affiliated 1 stjosephs

companies 1 MNC 1 CTS

RESULT
Thus the program to simulate Two level directory structure is executed successfully.

54
CS8461-Operating Systems Department of CSE 2018-2019

Ex.No:14(c) HIERARCHICAL & DAG

AIM
To write a C program to implement Hierarchical and DAG.

ALGORITHM
1. Start the program.
2. Get the number of main directories to be created, name of the directory and size of the
directory.
3. Get the number of sub directories to be created, name of the directory and size of the
directory.
4. Get the name of the file to be shared between directories.
5. Simulate the directed acyclic graph and display the structure.
6. Stop the program.

PROGRAM

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

#define MIN_PER_RANK 1

#define MAX_PER_RANK 5

#define MIN_RANKS 3

#define MAX_RANKS 5

#define PERCENT 30

int main (void)

int i, j, k,nodes = 0;

srand (time (NULL));

int ranks = MIN_RANKS

+ (rand () % (MAX_RANKS - MIN_RANKS + 1));

printf ("digraph {\n");


55
CS8461-Operating Systems Department of CSE 2018-2019

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

int new_nodes = MIN_PER_RANK

+ (rand () % (MAX_PER_RANK - MIN_PER_RANK + 1));

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

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

if ( (rand () % 100) < PERCENT)

printf (" %d -> %d;\n", j, k + nodes);

nodes += new_nodes;

printf ("}\n");

return 0;

OUTPUT

[user@sys108 ~]$ cc dgraph.c


[user@sys108 ~]$ ./a.out

digraph {

0 -> 5;

1 -> 6;

2 -> 5;

2 -> 8;

3 -> 5;

3 -> 8;

4 -> 6;

4 -> 7;

1 -> 9;
56
CS8461-Operating Systems Department of CSE 2018-2019

3 -> 9;

6 -> 9;

RESULT
Thus the program to simulate Directed Acyclic Graph and hierarchial structure is
executed successfully.

Ex.No:15(a) SEQUENTIAL FILE ALLOCATION

AIM
To write a c program to simulate Sequential File Allocation strategy.

ALGORITHM

1. Memory before allocation is displayed.


2. The file Id is entered by the user.
3. The number of blocks memory required and the starting address of the file is given by
the user.
4. If starting address and length of block is greater than 20 print error message.
5. Else the memory address is replaced by the id.
6. Display memory after allocation.

PROGRAM
#include<stdio.h>
#include<conio.h>
int a[20],num=0;
int fid[10],length[10],start[10];
void filedescriptor();
void display();
void filedescriptor()
{
int i;

57
CS8461-Operating Systems Department of CSE 2018-2019

printf("\n file id \t starting address \t length \n");


for(i=0;i<num;i++)
printf("%d\t\t\t %d\t\t%d\n",fid[i],start[i],length[i]);
}
void display()
{
int i;
for(i=0;i<20;i++)
printf("%2d",i);
printf("\n");
for(i=0;i<20;i++)
printf("%2d", a[i]);
}
void main()
{
int i,n,k,temp,st,l,id,flag=0,cho;
for(i=0;i<20;i++)
a[i]=0;
clrscr();
printf("\n Memory before allocation:\n");
display();
while(1) {
printf("\n Enter the file id:");
scanf("%d",&id);
printf("\n Enter the number of blocks the file occupies:");
scanf("%d", &l);
fid[num]=id;
length[num]=l;
printf("\n Enter the starting address:");
scanf("%d", &st);
flag=0;
if((st+l)>20)
{
printf("\n Sorry the given memory goes out of space:");
goto l; }
for(i=st;i<(st+l);i++) {
if(a[i]!=0) {
flag=1;
break;
}}
if(flag==0) {
start[num]=st;
for(i=st;i<(st+l);i++)
a[i]=id; }
else
{
printf("\n Sorry the given blocks are already occupied: Enter new starting address");
goto l; }
flag=0;
58
CS8461-Operating Systems Department of CSE 2018-2019

num++;
filedescriptor();
printf("\n Memory after allocation \n");
display();
printf("\n Want to continue? \n1.yes \n2.no");
scanf("%d",&cho);
if(cho==2)
exit(0);
}}

OUTPUT
[user@sys108 ~]$ vi sequential.c
[user@sys108 ~]$ cc sequential.c
[user@sys108 ~]$ ./a.out
Memory before allocation:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Enter the file id: 7
Enter the number of blocks the file occupies :4
Enter the starting address:2
File id starting address length
7 2 4
Memory after allocation:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
0 0 7 7 7 7 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Want to continue?
1.yes
2.no
2

RESULT
Thus a C program to simulate Sequential File allocation strategy is executed successfully.
59
CS8461-Operating Systems Department of CSE 2018-2019

Ex.No: 15(b) INDEXED FILE ALLOCATION

AIM
To write a C program to simulate Indexed File Allocation strategy.

ALGORITHM

1. Get the index block number and number of files in the index block as input from user.
2. Get the file numbers (i.e referred block numbers holding file) as input .
3. Check whether that the input block number is already allocated if so print block
allocated.
4. Else increase the count and allocate the file.
5. Continue the loop to enter another index block.

PROGRAM
#include<stdio.h>
void main()
{
int f[50],indblk,i,k,j,index[50],n,c,count=0;
for(i=0;i<50;i++)
f[i]=0;
X:printf("Enter index block");

60
CS8461-Operating Systems Department of CSE 2018-2019

scanf("%d",&indblk);
if(f[indblk]!=1)
{
f[indblk]=1;
printf("Enter number of files on index");
scanf("%d",&n);
}
y: for(i=0;i<n;i++)
{
scanf("%d",&index[i]);
if(f[index[i]]==0)
{
count++;
}
}
if(count==n)
{
for(j=0;j<n;j++)
f[index[j]]=1;
printf("\n Allocated");
printf("\n File indexed");
for(k=0;k<n;k++)
printf("\n%d->%d:%d",indblk,index[k],f[index[k]]);
}
else
{
printf("\n File in the index already allocation");
printf("\n Enter another file indexed");
goto y;
}
printf("\n Index is already allocated");
count=0;
printf("\n If you enter one more block(1/0)");
scanf("%d",&c);
if(c==1)
goto X;
}

OUTPUT
[user@sys108 ~]$ vi index.c
[user@sys108 ~]$ cc index.c
[user@sys108 ~]$ ./a.out
Enter index block 2
Enter no of files on index 4
5678
Allocated
File indexed
61
CS8461-Operating Systems Department of CSE 2018-2019

2->5:1
2->6:1
2->7:1
2->8:1
Index is already allocated
If you enter one more block(1/0)

RESULT
Thus a C program to simulate Indexed File allocation strategy is executed successfully.

62
CS8461-Operating Systems Department of CSE 2018-2019

Ex.No: 15(c) LINKED FILE ALLOCATION

AIM
To write a C program to simulate Linked File Allocation strategy

ALGORITHM

1. Get the number of blocks already allocated and its block numbers as input from user.
2. Add that block numbers to a list as allocated block number list and mark that block
numbers are allocated.
3. To perform allocation , get the starting block number and length of the input file.
4. From the starting block check whether each block is in allocated block number list.
5. If so print block is already allocated. Else allocate file to the block number.
6. Continue the loop if the processes want to be repeated.

PROGRAM
#include<stdio.h>
main()
{
int f[50],p,i,j,k,a,st,len,n,c;
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;
}
X:printf("Enter the starting 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++;
}
}
63
CS8461-Operating Systems Department of CSE 2018-2019

printf("\n If u want to enter one more file? (yes-1/no-0)");


scanf("%d",&c);
if(c==1)
goto X;
else
exit(0);
}

OUTPUT
[user@sys108 ~]$ vi linked.c
[user@sys108 ~]$ cc linked.c

[user@sys108 ~]$ ./a.out


Enter how many blocks that are already allocated 3
Enter the blocks no.s that are already allocated 4 7 9
Enter the starting block & length 3 7
3->1
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
If u want to enter one more file? (yes-1/no-0)

RESULT
Thus a C program to simulate Linked File allocation strategy is executed successfully.

64
CS8461-Operating Systems Department of CSE 2018-2019

Ex.No:16 SEGMENTATION TECHNIQUE OF MEMORY MANAGEMENT

AIM
To implement Segmentation Memory Management scheme using C

ALGORITHM
1. Get Segment number, base and limit address.
2. Define insert function to create segments and add segmentation details for each.
3. Define find function to search and get the segment details for the given segment number.
4. To display the segment details get segment number and offset.
5. Segment details are displayed when offset is less than limit of the given segment number
6. calculate physical memory address as phy addr=base+offset
7. Display the physical address in the segment of the given offset.

PROGRAM
#include<stdio.h>
struct list
{
int seg;
int base;
int limit;
struct list *next;
}*p;
void insert(struct list *q,int base,int limit,int seg)
{
if(p==NULL)
{
p=malloc(sizeof(struct list));
p->limit=limit;
p->base=base;
p->seg=seg;
p->next=NULL;
}
else
{
while(q->next!=NULL)
{
q=q->next;
printf("yes");
}
q->next=malloc(sizeof(struct list));
q->next->limit=limit;
q->next->base=base;
q->next->seg=seg;
q->next->next=NULL;
}
}
int find(struct list *q,int seg)
{
while(q->seg!=seg)
{
65
CS8461-Operating Systems Department of CSE 2018-2019

q=q->next;
}
return q->limit;
}
int search(struct list *q,int seg)
{
while(q->seg!=seg)
{
q=q->next;
}
return q->base;
}
main()
{
p=NULL;
int seg,offset,limit,base,c,s,physical;
printf("Enter segment table/n");
printf("Enter -1 as segment value for termination\n");
do
{
printf("Enter segment number");
scanf("%d",&seg);
if(seg!=-1)
{
printf("Enter base value:");
scanf("%d",&base);
printf("Enter value for limit:");
scanf("%d",&limit);
insert(p,base,limit,seg);
}
}while(seg!=-1);
printf("Enter offset:");
scanf("%d",&offset);
printf("Enter bsegmentation number:");
scanf("%d",&seg);
c=find(p,seg);
s=search(p,seg);
if(offset<c)
{
physical=s+offset;
printf("Address in physical memory %d\n",physical);
}
else
{
printf("error");
}
}

OUTPUT

66
CS8461-Operating Systems Department of CSE 2018-2019

[root@localhost root]# ./a.out


Enter segment table
Enter -1 as segment value for termination
Enter segment number1
Enter base value:2000
Enter value for limit:500
Enter segment number2
Enter base value:3000
Enter value for limit:600
Enter segment number-1
Enter offset:50
Enter bsegmentation number:2
Address in physical memory 3050

RESULT
Thus the program to simulate Segmentation Memory Management is executed
successfully.

67

You might also like