0% found this document useful (0 votes)
2 views

Operating Systems LAB programs

The document provides a comprehensive guide on basic UNIX commands, the vi editor, and various types of shells in the Unix/Linux operating system. It includes command syntax, descriptions, and examples for commands such as 'man', 'ls', 'cd', and 'chmod', as well as an overview of the Unix/Linux file system structure. Additionally, it covers the operation modes of the vi editor and outlines an experiment involving UNIX system calls.

Uploaded by

Tinotenda Mazura
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Operating Systems LAB programs

The document provides a comprehensive guide on basic UNIX commands, the vi editor, and various types of shells in the Unix/Linux operating system. It includes command syntax, descriptions, and examples for commands such as 'man', 'ls', 'cd', and 'chmod', as well as an overview of the Unix/Linux file system structure. Additionally, it covers the operation modes of the vi editor and outlines an experiment involving UNIX system calls.

Uploaded by

Tinotenda Mazura
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 80

1

Experiment-1

Practicing of Basic UNIX Commands.

1. man - view manual pages for UNIX commands


Syntax: man [-s section] item
$ man cat

2. who - displays the list of users logged presently


Syntax: who [option]… [file][arg1]
$ who

3. cat - concatenate files and show contents to the standard output


Syntax: cat [option]…[file]

$ cat > file1 hello

4. cd - change directory
Syntax: cd [option] directory

$ cd dir1

5. cp - copy files
Syntax: cp [option] source destination

$ cp file1 file2

6. ps - Reports process status


Syntax: Ps [options]

$ ps

7. ls - List files & directories


Syntax: ls [option] [file]

$ ls

8. mv - Rename or move files & directories to another location


Syntax: mv [option] source destination

$ mv file1 file2

9. rm - removes files & directories


Syntax: rm [option]…[file]

$ rm file1
2

10. mkdir - makes new directory


Syntax: mkdir [option] directory

$ mkdir dir1

11. rmdir - removes directory


Syntax: rmdir [option] directory

$ rmdir dir1

12. echo - displays a line of text to the standard output


Syntax: $ echo "Hello, World!"

$ echo $x

13. more - basic pagination when viewing text files or parsing UNIX commands output
Syntax: more [-options] [-num] [+/pattern] [+linenum] [file_name]

$ more +/reset sample.txt

$ more +30 sample.txt

14. date - Show current date & time


Syntax: date [+format]

$ date +%d/%m/%y

15. time - shows current time

$ time

16. kill - terminates a specified process


Syntax: Kill PID

$ kill 4901

17. history - displays history commands in the current


session
Syntax: history [options]

$ history

18. chmod - change file / directory access permissions


Symbolic mode

Syntax: chmod [ugoa][[+-=][mode]] file

 The first optional parameter indicates who – this can be (u)ser, (g)roup, (o)thers or (a)ll
 The second optional parameter indicates opcode – this can be for adding (+), removing (-) or
3

assigning (=) a permission.


 The third optional parameter indicates the mode – this can be (r)ead, (w)rite, or e(x)ecute.
$ chmod o-w file1

Numeric mode

Syntax: chmod [mode] file

 The mode is a combination of three digits – the first digit indicates the
permission for the user, the second digit for the group, and the third digit for
others.
 Each digit is computed by adding the associated permissions. Read
permission is ‘4’, write permission is ‘2’ and execute permission is ‘1’.
$ chmod 777 file1

19. chown - change file / directory ownership


Syntax: chown [owner] [file]

$ chown user2 file1

20. finger - displays user info if login is known


Syntax: finger username

21. pwd - confirm current directory


Syntax: pwd [option]

$ pwd

22. cal - displays calendar


Syntax: cal [[month] year]

$ cal 6 2019

23. logout - logs off UNIX


Syntax: Logout [options]

$ logout

24. shutdown - brings the system down in a secure way


Syntax: shutdown [options]

$ shutdown
4

Study of vi editor.
 Visual editor for editing programs.
 The vi editor is the most popular and classic text editor in the Linux family.
 This editor enables you to edit lines in context with other lines in the file.
 Below, are some reasons which make it a widely used editor?
 It is available in almost all Linux Distributions
 It works the same across different platforms and Distributions
 It requires very few resources.
 It is more user-friendly than other editors such as the ed or the ex.
 We can use the vi editor to edit an existing file or to create a new file from scratch.
 We can also use this editor to just read a text file.
 An improved version of the vi editor which is called the VIM has also been
made available now. Here, VIM stands for Vi IMproved.
Starting the vi Editor
To launch the vi Editor -Open the Terminal (CLI) and type
vi <filename_NEW> or <filename_EXISTING>
& if you specify an existing file, then the editor would open it for you to edit. Else, you
can create a new file.
The following table lists out the basic commands to use the vi editor –

S. No Command Description
1 vi filename Creates a new file if it already does not exist, otherwise opens
an existing file
2 vi –R filename Opens an existing file in the read-only mode.

Operation Modes

To work on vi editor, we need to understand its operation modes.

 Command mode − This mode enables you to perform administrative tasks such
as saving the files, executing the commands, moving the cursor, cutting (yanking)
and pasting the lines or words, as well as finding and replacing. In this mode,
whatever you type is interpreted as a command.

 Insert mode − This mode enables you to insert text into the file. Everything that's
typed in this mode is interpreted as input and placed in the file.

vi always starts in the command mode. To enter text, you must be in the insert mode for
which simply type i. To come out of the insert mode, press the Esc key, which will take
5

you back to the command mode.

vi Editing commands

Note: You should be in the "command mode" to execute these commands.

vi editor is case-sensitive so make sure to type the commands in the right letter-case,
otherwise you will end up making undesirable changes to the file.

Command Description
S. No
1 i Insert at cursor (goes into insert mode)
2 a Write after cursor (goes into insert mode)
3 A Write at the end of line (goes into insert mode)
4 ESC Terminate insert mode
5 u Undo last change
6 U Undo all changes to the entire line
7 o Open a new line (goes into insert mode)
8 dd Delete line
9 3dd Delete 3 lines.
10 D Delete contents of line after the cursor
11 C Delete contents of a line after the cursor and insert new text. Press ESC
key to end insertion.
12 dw Delete word
13 4dw Delete 4 words
14 cw Change word
15 x Delete character at the cursor
16 r Replace character
17 R Overwrite characters from cursor onward
18 s Substitute one character under cursor continue to insert
19 S Substitute entire line and begin to insert at the beginning of the line
20 ~ Change case of individual character

Moving within a file

Note: You need to be in the “command mode” to move within a file.

The default keys for navigation are mentioned below else; you can also use the arrow keys
on the keyboard.
S. Command Description
No
6

1 k Move cursor up
2 j Move cursor down
3 h Move cursor left
4 l Move cursor right

Saving and Closing the file

Note: You should be in the “command mode” to exit the editor and save changes to the file.

S. Command Description
No
1 Shift+zz Save the file and quit
2 :w Save the file but keep it open
3 :q Quit without saving
4 :wq Save the file and quit

Study of Bash shell, Bourne shell and C shell in Unix/Linux operating system. What Is a
Shell?
A shell is a program that provides an interface between a user and an operating system
(OS) kernel.
An OS starts a shell for each user when the user logs in or opens a terminal or console
window. A kernel is a program that:
 Controls all computer operations.
 Coordinates all executing utilities
 Ensures that executing utilities do not interfere with each other or consume all
system resources.
 Schedules and manages all system processes.
By interfacing with a kernel, a shell provides a way for a user to execute utilities and
programs.

Types of Shell

1. Bourne Shell (sh)


 The Bourne shell is one of the original shells, developed for UNIX
computers by Stephen Bourne at AT&T Bell Labs in 1977.
 It offers features such as input and output redirection, shell scripting with
string and integer variables, and condition testing and looping.
 Command full-path name is /bin/sh and /sbin/sh.
 Default prompt for a non-root user is $.
7

 Default prompt for a root user is #.


2. C Shell (csh)
 The C shell was designed to allow users to write shell script
programs using syntax very similar to that of the C programming
language.
 The C shell is a UNIX shell created by Bill Joy.
 The C shell is a command processor typically run in a text window,
allowing the user to type commands.
 Command full-path name is /bin/csh.
 Default prompt for a non-root user is hostname %.
 Default prompt for a root user is hostname #.
3. Bourne Again Shell (bash)
 The default Linux shell.
 Backward-compatible with the original sh UNIX shell.
 Bash is largely compatible with sh and incorporates useful features from
the Korn shell ksh and the C shell csh.
 Command full-path name is /bin/bash.
 Default prompt for a non-root user is bash-x.xx$. (Where x.xx indicates
the shell version number. For example, bash-3.50$)

Root user default prompt is bash-x.xx#. (Where x.xx indicates the shell
version number. For example, bash-3.50$#)
Study of Unix/Linux files system (tree structure).
Unix/Linux files system (tree structure)
 UNIX file system is a logical method of organizing and storing large
amounts of information in a way that makes it easy to manage.
 A file is a smallest unit in which the information is stored.
 Files in Unix System are organized into multi-level hierarchy structure known as
a directory tree. At the very top of the file system is a directory called “root”
which is represented by a “/”. All other files are “descendants” of root.

1. / – Root

 Every single file and directory starts from the root directory.

 Only root user has write privilege under this directory.

 Please note that /root is root user’s home directory, which is not same as /.
8

2. /bin – User Binaries

 Contains binary executables.

 Common linux commands you need to use in single-user modes are located
under this directory.

 Commands used by all the users of the system are located here.

 For example: ps, ls, ping, grep, cp.

3. /sbin – System Binaries

 Just like /bin, /sbin also contains binary executables.

 But, the linux commands located under this directory are used typically by
system aministrator, for system maintenance purpose.

 For example: iptables, reboot, fdisk, ifconfig, swapon

4. /etc – Configuration Files

 Contains configuration files required by all programs.

 This also contains startup and shutdown shell scripts used to start/stop
individual programs.

 For example: /etc/resolv.conf, /etc/logrotate.conf

5. /dev – Device Files

 Contains device files.

 These include terminal devices, usb, or any device attached to the system.

 For example: /dev/tty1, /dev/usbmon0

6. /proc – Process Information

 Contains information about system process.

 This is a pseudo filesystem contains information about running process. For


example:
/proc/{pid} directory contains information about the process with that particular pid.

 This is a virtual filesystem with text information about system resources. For
example:
/proc/uptime

7. /var – Variable Files


9

 var stands for variable files.

 Content of the files that are expected to grow can be found under this directory.

 This includes — system log files (/var/log); packages and database files (/var/lib);
emails (/var/mail); print queues (/var/spool); lock files (/var/lock); temp files
needed across reboots (/var/tmp);

8. /tmp – Temporary Files

 Directory that contains temporary files created by system and users.

 Files under this directory are deleted when system is rebooted.

9. /usr – User Programs

 Contains binaries, libraries, documentation, and source-code for second level


programs.

 /usr/bin contains binary files for user programs. If you can’t find a user binary
under /bin, look under /usr/bin. For example: at, awk, cc, less, scp

 /usr/sbin contains binary files for system administrators. If you can’t find a system
binary under /sbin, look under /usr/sbin. For example: atd, cron, sshd, useradd,
userdel

 /usr/lib contains libraries for /usr/bin and /usr/sbin

 /usr/local contains users programs that you install from source. For example,
when you install apache from source, it goes under /usr/local/apache2

10. /home – Home Directories

 Home directories for all users to store their personal files.

 For example: /home/john, /home/nikita

11. /boot – Boot Loader Files

 Contains boot loader related files.

 Kernel initrd, vmlinux, grub files are located under /boot

 For example: initrd.img-2.6.32-24-generic, vmlinuz-2.6.32-24-generic

12. /lib – System Libraries

 Contains library files that supports the binaries located under /bin and /sbin

 Library filenames are either ld* or lib*.so.*


10

 For example: ld-2.11.1.so, libncurses.so.5.7

13. /opt – Optional add-on Applications

 opt stands for optional.

 Contains add-on applications from individual vendors.

 Add-on applications should be installed under either /opt/ or /opt/ sub-directory.

14. /mnt – Mount Directory

 Temporary mount directory where sysadmins can mount filesystems.

15. /media – Removable Media Devices

 Temporary mount directory for removable devices.

 For examples, /media/cdrom for CD-ROM; /media/floppy for floppy


drives;
/media/cdrecorder for CD writer

16. /srv – Service Data

 srv stands for service.

 Contains server specific services related data.

 For example, /srv/cvs contains CVS related data.

Experiment-2
11

Write programs using the following UNIX operating system calls fork, exec, getpid,
exit, wait, close, stat, opendir and readdir

AIM: To write a ‘C’ Program using system calls opendir, readdir, and closedir.

#include<stdio.h>

#include<dirent.h>

struct dirent *dptr;

int main(int argc, char *argv[])


{
char buff[100];
DIR *dirp;
printf("\n\n ENTER DIRECTORY NAME");
scanf("%s", buff);
if((dirp=opendir(buff))==NULL)
{
printf("The given directory does not exist.");
exit(1);
}
while(dptr=readdir(dirp))
{
printf("%s\n",dptr->d_name);
}
closedir(dirp);
}
OUTPUT :
ENTER DIRECTORY NAMEcse1
.
hai.c
..
a.out
12

hi
13

AIM: To write a ‘C’ Program using stat system call

#include<stdio.h>

#include<unistd.h>;

#include<fcntl.h>;

#include<sys/stat.h>;

main(int argc,char *argv[])

struct stat buf;

int fd,n,i=1;

while(i<argc)

fd=open(argv[i],O_RDONLY);

fd=fstat(fd,&buf);

printf("The information of the file is:%s\n",argv[i]);

if(S_ISREG(buf.st_mode))

printf("File is regular\n");

else if(S_ISDIR(buf.st_mode))

printf("It is a directory\n");

else

printf("Not a specific file type\n");

printf("Number of links:%d\n",buf.st_nlink);

printf("Type and permission:%o\n",buf.st_mode);

printf("Time of last access:%s\n",ctime(&buf.st_mtime));

i++;

}
14

OUTPUT :

./a.out cse1

The information of the file is:cse1

It is a directory

Number of links:2

Type and permission:40775

Time of last access:Wed Mar 26 16:13:38 2025


15

AIM: To write programs using the following UNIX operating system calls fork, exec,
getpid, exit, wait

#include<stdio.h>

#include<unistd.h>

main(int argc,char *ar[])

int pid,pid1,pid2;

pid=fork();

if(pid==-1)

printf("ERROR IN PROCESS CREATION \n");

exit(1);

else if(pid==0)

printf("\n the child process ID is %d\n", pid2);

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

else

wait(NULL);

pid1=getpid();

printf("\n the parent process ID is %d\n", pid1);

printf("Child completed");

exit(0);

}
16

OUTPUT:

the child process ID is 134514075

2a.c 2b.c 2c.c a.out cse1 cse2

the parent process ID is 29602

Child completed
17

Experiment-3

Simulate UNIX commands like cp, ls, grep, etc.,

a) AIM: To write a ‘C’ Program to simulate cp command

#include<fcntl.h>

#include<stdio.h>

#include<unistd.h>

#include<sys/stat.h>

int main(int argc, char *argv[])

int fd1,fd2;

int n;

char buf;

fd1=open(argv[1],O_RDONLY);

fd2=creat(argv[2],S_IWUSR|S_IRUSR);

while((n=read(fd1,&buf,1))>0)

write(fd2,&buf,1);

return (0);

cat>hai

hai everyone

how are u?

Helo cse

^Z

[3]+ Stopped cat > hai


18

[suryavinti@localhost ~]$ cc 3a.c

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

[suryavinti@localhost ~]$ ./a.out hai hello

[suryavinti@localhost ~]$ cat hello

hai everyone

how are u?

Helo cse
19

AIM: To write a ‘C’ Program to simulate ls command.

#include<stdio.h>

#include<dirent.h>

main(int argc, char **argv)

DIR *dp;

struct dirent *link;

dp=opendir(argv[1]);

printf("\n contents of the directory %s are \n", argv[1]);

while((link=readdir(dp))!=0)

printf("%s",link->d_name);

closedir(dp);

OUTPUT :

./a.out cse1

contents of the directory cse1 are

.hai.c. .a.out hi
20

b) AIM: To write a ‘C’ Program to simulate grep command.

void usage()

printf("usage:\t./a.out filename word \n ");

int main(int argc, char *argv[])

FILE *fp;

char fline[max];

char *newline;

int count=0;

int occurrences=0;

if(argc!=3)

usage();

exit(1);

if(!(fp=fopen(argv[1],"r")))

printf("grep: couldnot open file : %s \n",argv[1]);

exit(1);

while(fgets(fline,max,fp)!=NULL)

count++;

if(newline=strchr(fline, '\n'))
21

*newline='\0';

if(strstr(fline,argv[2])!=NULL)

printf("%s: %d %s \n", argv[1],count, fline);

occurrences++;

OUTPUT:

./a.out hai h

hai: 1 hai everyone

hai: 2 how are u?


22

Experiment-4

Simulate the following CPU scheduling algorithms

a) FCFS b) SJF c) Priority d) Round Robin

a) AIM: To write a ‘C’ Program to simulate First Come First Served CPU Scheduling
(FCFS) Algorithm.
main()
{
int n,i,twt,ttt;
char p[20][20];
int b[20],w[20],tt[20];
float awt,att;
printf("Enter no.of process:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter process:");
scanf("%s",p[i]);
printf("Enter burst time:");
scanf("%d",&b[i]);
}
w[1]=0;
tt[1]=w[1]+b[1];
twt=0;
ttt=tt[1];
for(i=2;i<=n;i++)
{
w[i]=w[i-1]+b[i-1];
tt[i]=w[i]+b[i];
twt=w[i]+twt;
23

ttt=tt[i]+ttt;
}
printf("sno\tprocess name \tburst time \twaiting time \tturn around time\n");
for(i=1;i<=n;i++)
{
printf("%d\t%s\t\t%d\t\t%d\t\t%d\t\n",i,p[i],b[i],w[i],tt[i]);
}
printf("Total waiting time: %d\n",twt);
printf("Total turn around time: %d\n",ttt);
printf("Avg waiting time: %f\n",(float)twt/n);
printf("Avg turn around time: %f\n",(float)ttt/n);
}
Output :
Enter no.of process:4
Enter process:1
Enter burst time:4
Enter process:2
Enter burst time:3
Enter process:3
Enter burst time:2
Enter process:4
Enter burst time:8
sno process name burst time waiting time turn around time
1 1 4 0 4
2 2 3 4 7
3 3 2 7 9
4 4 8 9 17
Total waiting time: 20
Total turn around time: 37
Avg waiting time: 5.000000
Avg turn around time: 9.250000
24

b) AIM: To write a ‘C’ Program to simulate Shortest Job First CPU scheduling (SJF)
Algorithm.
main()
{
int n,i,twt,ttt,k,j,temp;
char p[20][20],c[20];
int b[20],w[20],tat[20];
float awt,att;
printf("Enter no.of process:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter process:");
scanf("%s",p[i]);
printf("Enter burst time:");
scanf("%d",&b[i]);
}
for(k=1;k<=n-1;k++)
{
for(j=1;j<=n-k;j++)
{
if(b[j]>b[j+1])
{
temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
strcpy(c,p[j]);
strcpy(p[j],p[j+1]);
strcpy(p[j+1],c);
25

}
}
}
w[1]=0;
tat[1]=w[1]+b[1];
twt=0;
ttt=tat[1];
for(i=2;i<=n;i++)
{
w[i]=w[i-1]+b[i-1];
tat[i]=w[i]+b[i];
twt=w[i]+twt;
ttt=tat[i]+ttt;
}
printf("s.no\tprocessname\tburst\ttwait\ttturn around\n");
for(i=1;i<=n;i++)
{
printf("%d\t%s\t\t%d\t%d\t%d\t\n",i,p[i],b[i],w[i],tat[i]);
}
printf("Total waiting time: %d\n",twt);
printf("Total turn around time: %d\n",ttt);
printf("Avg waiting time: %f\n",(float)twt/n);
printf("Avg turn around time: %f\n",(float)ttt/n);
}
OUTPUT:
Enter no.of process:4
Enter process:1
Enter burst time:5
Enter process:2
26

Enter burst time:3


Enter process:3
Enter burst time:1
Enter process:4
Enter burst time:4
s.no processname burst twait tturn around
1 3 1 0 1
2 2 3 1 4
3 4 4 4 8
4 1 5 8 13
Total waiting time: 13
Total turn around time: 26
Avg waiting time: 3.250000
Avg turn around time: 6.500000
27

c) AIM: To write a ‘C’ Program to simulate Priority CPU scheduling Algorithm.


#include<stdio.h>
#include<string.h>
void main()
{
int n,i,twt,ttt,k,j,temp;
char p[20][20],c[20];
int b[20],w[20],tat[20],pr[20];
float awt,att;
printf("Enter no.of process:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("Enter process:");
scanf("%s",p[i]);
printf("Enter burst time:");
scanf("%d",&b[i]);
printf("Enter priority:");
scanf("%d",&pr[i]);
}
for(k=1;k<=n-1;k++)
{
for(j=1;j<=n-k;j++)
{
if(pr[j]>pr[j+1])
{
temp=pr[j];
pr[j]=pr[j+1];
pr[j+1]=temp;
28

temp=b[j];
b[j]=b[j+1];
b[j+1]=temp;
strcpy(c,p[j]);
strcpy(p[j],p[j+1]);
strcpy(p[j+1],c);
}
}}
w[1]=0;
tat[1]=w[1]+b[1];
twt=0;
ttt=tat[1];
for(i=2;i<=n;i++)
{
w[i]=w[i-1]+b[i-1];
tat[i]=w[i]+b[i];
twt=w[i]+twt;
ttt=tat[i]+ttt;
}
printf("s.no\tpname\tburst\tpriority\ttwait\ttturn around\n");
for(i=1;i<=n;i++)
{
printf("%d\t%s\t%d\t\t%d\t%d\t%d\n",i,p[i],b[i],pr[i],w[i],tat[i]);
}
printf("Total waiting time: %d\n",twt);
printf("Total turn around time: %d\n",ttt);
printf("Avg waiting time: %f\n",(float)twt/n);
printf("Avg turn around time: %f\n",(float)ttt/n);
}
29

OUTPUT:
Enter no.of process:4
Enter process:1
Enter burst time:4
Enter priority:2
Enter process:2
Enter burst time:2
Enter priority:3
Enter process:3
Enter burst time:6
Enter priority:4
Enter process:4
Enter burst time:1
Enter priority:1
s.no pname burst priority twait tturn around
1 4 1 1 0 1
2 1 4 2 1 5
3 2 2 3 5 7
4 3 6 4 7 13
Total waiting time: 13
Total turn around time: 26
Avg waiting time: 3.250000
Avg turn around time: 6.500000
30

d) AIM: To write a ‘C’ Program to simulate Round-Robin (RR) CPU scheduling


Algorithm.

#include<stdio.h>

#include<string.h>

int main()

char p[10][5];

int et[10],wt[10],timer,count,pt[25],rt,i,j,totwt=0,n,found=0,m,tat[10],ttt=0;

float avgwt;

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

scanf("%d",&n);

printf("Enter time slice:\n");

scanf("%d",&timer);

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

printf("Enter the process name:\n");

scanf("%s",&p[i]);

printf("Enter the process time:\n");

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

m=n;

wt[0]=0;

i=0;

do

if(pt[i]>timer)

{
31

rt=pt[i]-timer;

strcpy(p[n],p[i]);

pt[n]=rt;

et[i]=timer;

n++;

else

et[i]=pt[i];

i++;

wt[i]=wt[i-1]+et[i-1];

while(i<n);

count=0;

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

for(j=i+1;j<=n;j++)

if(strcmp(p[i],p[j])==0)

count++;

found=j;

if(found!=0)

{
32

wt[i]=wt[found]-(count*timer);

count=0;

found=0;

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

totwt+=wt[i];

tat[i]=wt[i]+pt[i];

ttt=ttt+tat[i];

avgwt=(float)totwt/m;

printf("pname \t ptime \t wtime \tturnaroundtime\n");

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

printf("\n %s \t %d \t %d \t\t %d",p[i],pt[i],wt[i],tat[i]);

printf("\n Total waiting time: %d \n",totwt);

printf("\n Avg wating time: %f",avgwt);

printf("\n Total turnaroundtime: %d",ttt);

printf("\n Avg turnaround time: %f",(float)ttt/m);

OUTPUT:

Enter the no of process:

4
33

Enter time slice:

Enter the process name:

Enter the process time:

Enter the process name:

Enter the process time:

Enter the process name:

Enter the process time:

Enter the process name:

Enter the process time:

pname ptime wtime turnaroundtime

1 4 5 9

2 3 7 10

3 1 4 5

4 5 10 15

Total waiting time: 26 Avg wating time: 6.500000

Total turnaroundtime: 39 Avg turnaround time: 9.750000


34

Experiment-5

Control the number of ports opened by the operating system with


a) Semaphore b) Monitors.
a) AIM: Write a C program to control the number of ports opened by the operating system
with Semaphore.

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#include <semaphore.h>

#define MAX_PORTS 5 // Maximum number of ports allowed

// Semaphore to control the number of available ports

sem_t port_semaphore;

// Function to simulate opening a port

void* open_port(void* arg)

// Wait for an available port

if (sem_wait(&port_semaphore) == 0)

int thread_id = *((int*)arg);

printf("Thread %d: Port is open.\n", thread_id);

// Simulating some port usage time

sleep(2); // Simulate port usage for 2 seconds

printf("Thread %d: Port is closed.\n", thread_id);

// Signal that the port is now available

sem_post(&port_semaphore);

}
35

else

printf("Thread %d: Could not open a port, semaphore wait failed.\n", *((int*)arg));

return NULL;

int main()

pthread_t threads[10];

int thread_ids[10],i;

// Initialize the semaphore with MAX_PORTS value

if (sem_init(&port_semaphore, 0, MAX_PORTS) != 0)

perror("Semaphore initialization failed");

return -1;

// Array of thread ids

// Create threads (simulating different processes trying to use the ports)

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

thread_ids[i] = i + 1; // Assign thread ids starting from 1

if (pthread_create(&threads[i], NULL, open_port, &thread_ids[i]) != 0)

perror("Thread creation failed");

return -1;
36

// Wait for all threads to complete

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

pthread_join(threads[i], NULL);

// Destroy the semaphore

sem_destroy(&port_semaphore);

return 0;

Output:

Thread 1: Port is open.

Thread 2: Port is open.

Thread 4: Port is open.

Thread 5: Port is open.

Thread 3: Port is open.

Thread 3: Port is closed.

Thread 5: Port is closed.

Thread 4: Port is closed.

Thread 2: Port is closed.

Thread 9: Port is open.

Thread 6: Port is open.

Thread 7: Port is open.

Thread 8: Port is open.

Thread 1: Port is closed.


37

Thread 10: Port is open.

Thread 8: Port is closed.

Thread 7: Port is closed.

Thread 9: Port is closed.

Thread 6: Port is closed.

Thread 10: Port is closed.


38

b) AIM: Write a C program to control the number of ports opened by the operating system
with Monitor.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define MAX_PORTS 5 // Maximum number of ports allowed
// Monitor structure for managing ports
typedef struct {
int available_ports; // Number of available ports
pthread_mutex_t mutex; // Mutex for critical section
pthread_cond_t cond_var; // Condition variable for waiting
} PortMonitor;
// Initialize the port monitor
void init_monitor(PortMonitor* monitor) {
monitor->available_ports = MAX_PORTS;
pthread_mutex_init(&monitor->mutex, NULL);
pthread_cond_init(&monitor->cond_var, NULL);
}
// Acquire a port from the monitor
void acquire_port(PortMonitor* monitor) {
pthread_mutex_lock(&monitor->mutex);
// Wait if no ports are available
while (monitor->available_ports == 0) {
printf("No available ports. Waiting...\n");
pthread_cond_wait(&monitor->cond_var, &monitor->mutex);
}
// Allocate a port (decrease available ports)
monitor->available_ports--;
printf("Port acquired. Available ports: %d\n", monitor->available_ports);

pthread_mutex_unlock(&monitor->mutex);
}
39

// Release a port back to the monitor


void release_port(PortMonitor* monitor) {
pthread_mutex_lock(&monitor->mutex);
// Release the port (increase available ports)
monitor->available_ports++;
printf("Port released. Available ports: %d\n", monitor->available_ports);
// Signal that a port has been released
pthread_cond_signal(&monitor->cond_var);
pthread_mutex_unlock(&monitor->mutex);
}
// Function to simulate opening a port
void* open_port(void* arg) {
PortMonitor* monitor = (PortMonitor*)arg;
// Acquire a port
acquire_port(monitor);
// Simulate using the port for a short time
sleep(2); // Simulate port usage for 2 seconds
// Release the port after usage
release_port(monitor);
return NULL;
}
int main() {
PortMonitor monitor;
init_monitor(&monitor);
// Array of threads to simulate different processes
pthread_t threads[10];
// Create threads (simulating processes trying to use ports)
for (int i = 0; i < 10; i++) {
if (pthread_create(&threads[i], NULL, open_port, &monitor) != 0) {
perror("Thread creation failed");
return -1;
}
}
40

// Wait for all threads to complete


for (int i = 0; i < 10; i++) {
pthread_join(threads[i], NULL);
}
// Cleanup the mutex and condition variable
pthread_mutex_destroy(&monitor.mutex);
pthread_cond_destroy(&monitor.cond_var);
return 0;
}
Output:

Port acquired. Available ports: 4

Port acquired. Available ports: 3

Port acquired. Available ports: 2

Port acquired. Available ports: 1

Port acquired. Available ports: 0

No available ports. Waiting...

No available ports. Waiting...

No available ports. Waiting...

No available ports. Waiting...

No available ports. Waiting...

Port released. Available ports: 1

Port released. Available ports: 2

Port released. Available ports: 3

Port released. Available ports: 4

Port released. Available ports: 5

Port acquired. Available ports: 4

Port acquired. Available ports: 3

Port acquired. Available ports: 2


41

Port acquired. Available ports: 1

Port acquired. Available ports: 0

Port released. Available ports: 1

Port released. Available ports: 2

Port released. Available ports: 3

Port released. Available ports: 4

Port released. Available ports: 5


42

Experiment-6

Write a program to illustrate concurrent execution of threads using pthreads library.


a) AIM: To write a program to illustrate concurrent execution of threads using pthreads
library.
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
void *mythread1(void *vargp)
{
int i;
printf("thread1\n");
for(i=1;i<=10;i++)
printf("i=%d\n",i);
printf("exit from thread1\n");
return NULL;
}
void *mythread2(void *vargp)
{
int j;
printf("thread2 \n");
for(j=1;j<=10;j++)
printf("j=%d\n",j);
printf("Exit from thread2\n");
return NULL;
}
int main()
{
pthread_t tid;
printf("before thread\n");
pthread_create(&tid,NULL,mythread1,NULL);
pthread_create(&tid,NULL,mythread2,NULL);
pthread_join(tid,NULL);
pthread_join(tid,NULL);
43

exit(0);
}
Output:
before thread
thread1
thread2
j=1
j=2
j=3
j=4
j=5
j=6
j=7
j=8
j=9
j=10
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
exit from thread1
Exit from thread2
44

Experiment-7

Write a program to solve producer-consumer problem using Semaphores.


a) AIM: To write a program to solve producer-consumer problem using Semaphores.
PROGRAM :

#include <stdio.h>

#include <stdlib.h>

int mutex = 1;

int full = 0;

int size = 10, data = 0;

void producer()

--mutex;

++full;

--size;

data++;

printf("\nProducer produces item number: %d\n", data);

++mutex;

void consumer()

--mutex;

--full;

++size;

printf("\nConsumer consumes item number: %d.\n", data);

data--;

++mutex;
45

int main()

int n, i;

printf("\n1. Enter 1 for Producer\n2. Enter 2 for Consumer\n3. Enter 3 to Exit");

while(1)

printf("\nEnter your choice: ");

scanf("%d", &n);

switch (n)

case 1:

if ((mutex == 1) && (size!= 0))

producer();

else

printf("The Buffer is full. New data cannot be produced!");

break;

case 2:

if ((mutex == 1) && (full != 0))

consumer();
46

else

printf("The Buffer is empty! New data cannot be consumed!");

break;

case 3:

exit(0);

break;

}}}

Output:

1. Enter 1 for Producer

2. Enter 2 for Consumer

3. Enter 3 to Exit

Enter your choice: 1

Producer produces item number: 1

Enter your choice: 1

Producer produces item number: 2

Enter your choice: 2

Consumer consumes item number: 2.

Enter your choice: 2

Consumer consumes item number: 1

Enter your choice: 2

The Buffer is empty! New data cannot be consumed!

Enter your choice: 3

--------------------------------
47

Experiment-8
Implement the following memory allocation methods for fixed partition
a) First fit b) Worst fit c) Best fit
AIM: To write a C program to implement first fit memory allocation method for fixed
partition

PROGRAM

#include<stdio.h>

void main()

int bsize[10], psize[10], b, p, flags[10], allocation[10], i, j;

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

flags[i] = 0;

allocation[i] = -1; // Initially, no process is allocated

printf("Enter the number of blocks: ");

scanf("%d", &b);

printf("Enter the size of each block:\n");

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

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

printf("Enter the number of processes: ");

scanf("%d", &p);

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

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

{
48

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

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

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

if(bsize[j] >= psize[i])

allocation[i] = j;

bsize[j] -= psize[i];

break;

printf("\nProcess No\tProcess Size\tBlock Number\n");

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

printf("%d\t\t%d\t\t", i+1, psize[i]);

if(allocation[i] != -1)

printf("%d\n", allocation[i] + 1);

else

printf("Not Allocated\n");

Output:

Enter the number of blocks: 4


49

Enter the size of each block:

100

200

300

400

Enter the number of processes: 5

Enter the size of each process:

150

100

250

380

450

Process No Process Size Block Number

1 150 2

2 100 1

3 250 3

4 380 4

5 450 Not Allocated


50

b) Worst fit

#include <stdio.h>

#define MAX 25

void main() {

int frag[MAX], blockSize[MAX], fileSize[MAX], i, j, numBlocks, numFiles, temp, highest;

int blockAllocated[MAX] = {0}, fileAllocated[MAX];

printf("\nMemory Management Scheme - Worst Fit");

printf("\nEnter the number of blocks: ");

scanf("%d", &numBlocks);

printf("Enter the number of files: ");

scanf("%d", &numFiles);

printf("\nEnter the size of the blocks:\n");

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

printf("Block %d: ", i + 1);

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

printf("\nEnter the size of the files:\n");

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

printf("File %d: ", i + 1);

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

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

highest = -1;

fileAllocated[i] = -1;

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

if (!blockAllocated[j]) {
51

temp = blockSize[j] - fileSize[i];

if (temp >= 0 && (highest == -1 || temp > highest)) {

fileAllocated[i] = j;

highest = temp;

if (fileAllocated[i] != -1) {

frag[i] = highest;

blockAllocated[fileAllocated[i]] = 1;

} else {

frag[i] = -1;

printf("\nFile_no\tFile_size\tBlock_no\tBlock_size\tFragment");

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

if (fileAllocated[i] != -1) {

printf("\n%d\t%d\t\t%d\t\t%d\t\t%d", i + 1, fileSize[i], fileAllocated[i] + 1,


blockSize[fileAllocated[i]], frag[i]);

} else {

printf("\n%d\t%d\t\tNot Allocated", i + 1, fileSize[i]);

Output:

Memory Management Scheme - Worst Fit


52

Enter the number of blocks: 5

Enter the number of files: 4

Enter the size of the blocks:

Block 1: 100

Block 2: 500

Block 3: 200

Block 4: 300

Block 5: 600

Enter the size of the files:

File 1: 212

File 2: 417

File 3: 112

File 4: 426

File_no File_size Block_no Block_size Fragment

1 212 5 600 388

2 417 2 500 83

3 112 4 300 188

4 426 Not Allocated


53

c) Best fit

#include <stdio.h>

#define MAX 25

void main() {

int frag[MAX], blockSize[MAX], fileSize[MAX], i, j, numBlocks, numFiles, temp, lowest;

int blockAllocated[MAX] = {0}, fileAllocated[MAX];

printf("\nMemory Management Scheme - Best Fit");

printf("\nEnter the number of blocks: ");

scanf("%d", &numBlocks);

printf("Enter the number of files: ");

scanf("%d", &numFiles);

printf("\nEnter the size of the blocks:\n");

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

printf("Block %d: ", i + 1);

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

printf("\nEnter the size of the files:\n");

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

printf("File %d: ", i + 1);

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

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

lowest = -1;

fileAllocated[i] = -1;
54

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

if (!blockAllocated[j]) {

temp = blockSize[j] - fileSize[i];

if (temp >= 0 && (lowest == -1 || temp < lowest)) {

fileAllocated[i] = j;

lowest = temp;

if (fileAllocated[i] != -1) {

frag[i] = lowest;

blockAllocated[fileAllocated[i]] = 1;

} else {

frag[i] = -1;

printf("\nFile No\tFile Size\tBlock No\tBlock Size\tFragment");

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

if (fileAllocated[i] != -1) {

printf("\n%d\t%d\t\t%d\t\t%d\t\t%d", i + 1, fileSize[i], fileAllocated[i] + 1,


blockSize[fileAllocated[i]], frag[i]);

} else {

printf("\n%d\t%d\t\tNot Allocated", i + 1, fileSize[i]);

}
55

Output:

Memory Management Scheme - Best Fit

Enter the number of blocks: 4

Enter the number of files: 5

Enter the size of the blocks:

Block 1: 100

Block 2: 200

Block 3: 300

Block 4: 400

Enter the size of the files:

File 1: 55

File 2: 130

File 3: 250

File 4: 190

File 5: 380

File No File Size Block No Block Size Fragment

1 55 1 100 45

2 130 2 200 70

3 250 3 300 50

4 190 4 400 210

5 380 Not Allocated

--------------------------------
56

Experiment-9

9. Simulate the following page replacement algorithms a) FIFO b) LRU c) LFU

a) FIFO

PROGRAM:

#include <stdio.h>

int main() {

int pages[20], frames[10], nop, ps, npf = 0, i, j, q = 0, found;

printf("Enter number of pages: ");

scanf("%d", &nop);

printf("Enter page sequence: ");

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

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

printf("Enter number of frames: ");

scanf("%d", &ps);

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

frames[i] = -1;

printf("\nFIFO Page Replacement Process:\n");

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

found = 0;

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

if (frames[j] == pages[i]) {
57

found = 1;

break;

printf("Page %d -> ", pages[i]);

if (found == 0) {

frames[q++] = pages[i];

if (q == ps) q = 0;

npf++;

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

if (frames[j] != -1)

printf("%d ", frames[j]);

else

printf("- ");

if (!found)

printf(" --> Page Fault");

printf("\n");

printf("Total Page Faults: %d\n", npf);


58

return 0;

Output:

Enter number of pages: 14

Enter page sequence: 7 0 1 2 0 3 0 4 2 3 0 3 2 3

Enter number of frames: 4

FIFO Page Replacement Process:

Page 7 -> 7 - - - --> Page Fault

Page 0 -> 7 0 - - --> Page Fault

Page 1 -> 7 0 1 - --> Page Fault

Page 2 -> 7 0 1 2 --> Page Fault

Page 0 -> 7 0 1 2

Page 3 -> 3 0 1 2 --> Page Fault

Page 0 -> 3 0 1 2

Page 4 -> 3 4 1 2 --> Page Fault

Page 2 -> 3 4 1 2

Page 3 -> 3 4 1 2

Page 0 -> 3 4 0 2 --> Page Fault

Page 3 -> 3 4 0 2

Page 2 -> 3 4 0 2

Page 3 -> 3 4 0 2

Total Page Faults: 7


59

b) LRU

#include<stdio.h>

void main ( )

int a[50],c[10],i,j,k,ps,nop,npf=0,nps=0;

printf("\n\t Enter no of pages :");

scanf("%d",&nop);

printf("\n\tEnter pages :");

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

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

printf("\n\tEnter no of page frames : ");

scanf ("%d",&ps);

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

for(k=0;c[k]!=a[i]&&k<nps;k++);

if(k==nps)

npf++;

if(nps==ps)

for(k=0;k<nps-1;k++)

c[k]=c[k+1];

c[k]=a[i];

if(nps<ps)

nps++;
60

else

for (j=k;j<nps-1;j++)

c[j]=c[j+1];

c[j]=a[i];

printf("\n") ;

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

printf("%d" ,c[k]) ;

printf (" \n\tNo of page faults occurred are %d",npf);

Output:

Enter no of pages :12

Enter pages :2 3 2 1 5 2 4 5 3 2 5 2

Enter no of page frames : 4

23

32

321

3215
61

3152

1524

1245

2453

4532

4325

4352

No of page faults occurred are 6


62

LFU
#include<stdio.h>

int main()

int f,p;

int pages[50],frame[10],hit=0,count[50],time[50];

int i,j,page,flag,least,minTime,temp;

printf("Enter no of frames : ");

scanf("%d",&f);

printf("Enter no of pages : ");

scanf("%d",&p);

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

frame[i]=-1;

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

count[i]=0;

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

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

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

printf("\n");

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

{
63

count[pages[i]]++;

time[pages[i]]=i;

flag=1;

least=frame[0];

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

if(frame[j]==-1 || frame[j]==pages[i])

if(frame[j]!=-1)

hit++; }

flag=0;

frame[j]=pages[i];

break; }

if(count[least]>count[frame[j]])

least=frame[j];

}}

if(flag)

minTime=50;

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

if(count[frame[j]]==count[least] && time[frame[j]]<minTime) {

temp=j;

minTime=time[frame[j]]; }}

count[frame[temp]]=0;
64

frame[temp]=pages[i]; }

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

printf("%d ",frame[j]); }

printf("\n");

printf("Page hit = %d",hit);

return 0;

Output:

Enter no of frames : 3

Enter no of pages : 7

Enter page no :

1234215

1 -1 -1

1 2 -1

123

423

423

421

521

Page hit = 1

Experiment-10
65

Simulate Paging Technique of memory management.

AIM: To write a program to Simulate Paging Technique of memory management.

Program:

#include <stdio.h>

#define MAX_PAGES 100 // Maximum number of pages

int pageTable[MAX_PAGES]; // Page table to store frame mappings

// Function to simulate paging

void simulatePaging(int numPages, int numFrames)

int i;

printf("\nPage Table Mapping:\n");

printf("Page No. -> Frame No.\n");

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

pageTable[i] = i % numFrames; // Simple mapping: Page i ? Frame (i % numFrames)

printf(" %d -> %d\n", i, pageTable[i]);

// Function to convert logical address to physical address

void logicalToPhysical(int pageNum, int offset, int pageSize) {

if (pageNum >= MAX_PAGES || pageTable[pageNum] == -1) {

printf("\nError: Invalid page number!\n");

return;

int frameNum = pageTable[pageNum];

int physicalAddress = (frameNum * pageSize) + offset;

printf("\nLogical Address: (Page %d, Offset %d) ? Physical Address: %d\n", pageNum, offset,
physicalAddress);
66

int main() {

int numPages, numFrames, pageSize,i;

printf("Enter total number of pages: ");

scanf("%d", &numPages);

printf("Enter total number of frames: ");

scanf("%d", &numFrames);

printf("Enter page size (in bytes): ");

scanf("%d", &pageSize);

if (numPages > MAX_PAGES) {

printf("\nError: Maximum pages exceeded!\n");

return 1;

// Initialize page table

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

pageTable[i] = -1; // Initialize page table with -1 (not mapped)

// Simulate paging

simulatePaging(numPages, numFrames);

// Convert logical address to physical address

int choice;

do {

int pageNum, offset;

printf("\nEnter logical address (Page Number & Offset): ");

scanf("%d %d", &pageNum, &offset);


67

if (offset >= pageSize) {

printf("\nError: Offset exceeds page size!\n");

} else {

logicalToPhysical(pageNum, offset, pageSize);

printf("\nDo you want to convert another address? (1-Yes, 0-No): ");

scanf("%d", &choice);

} while (choice == 1);

return 0;

Output:

Enter total number of pages: 5

Enter total number of frames: 3

Enter page size (in bytes): 1024

Page Table Mapping:

Page No. -> Frame No.

0 -> 0

1 -> 1

2 -> 2

3 -> 0

4 -> 1

Enter logical address (Page Number & Offset): 2 500

Logical Address: (Page 2, Offset 500) ? Physical Address: 2548

Do you want to convert another address? (1-Yes, 0-No): 1

Enter logical address (Page Number & Offset): 3 300


68

Logical Address: (Page 3, Offset 300) ? Physical Address: 300

Do you want to convert another address? (1-Yes, 0-No): 1

Enter logical address (Page Number & Offset): 0

4 700

Logical Address: (Page 0, Offset 4) ? Physical Address: 4

Do you want to convert another address? (1-Yes, 0-No):

Experiment-11
69

Implement Bankers Algorithm for Dead Lock avoidance and prevention

AIM: To write a C program to implement Bankers Algorithm for Dead Lock Avoidance
and prevention

#include <stdio.h>

void main() {

int n, m, i, j, k, y, ind = 0;

// Taking input for number of processes and resources

printf("Enter the number of processes: ");

scanf("%d", &n);

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

scanf("%d", &m);

int alloc[n][m], max[n][m], avail[m], work[m], need[n][m];

int finish[n], safesequence[n];

// Taking input for allocation matrix

printf("Enter the allocation matrix:\n");

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

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

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

// Taking input for max matrix


70

printf("Enter the max matrix:\n");

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

for (j = 0; j < m; j++) { // Fixed loop condition j<m instead of j<n

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

// Taking input for available resources

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

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

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

// Copy available resources to work array

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

work[i] = avail[i];

// Calculating need matrix

printf("Need Matrix is:\n");

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

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

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

printf("%d ", need[i][j]); // Print need matrix

printf("\n");
71

// Initializing finish array to 0

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

finish[i] = 0;

// Safety algorithm

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

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

if (finish[i] == 0) { // If process is not finished

int flag = 0;

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

if (need[i][j] > work[j]) { // If need is more than available

flag = 1;

break;

if (flag == 0) { // If process can be executed

safesequence[ind++] = i; // Store in safe sequence

for (y = 0; y < m; y++) {

work[y] += alloc[i][y]; // Free allocated resources

finish[i] = 1;

}
72

// Checking if all processes are finished

int safe = 1;

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

if (finish[i] == 0) {

safe = 0;

break;

// Printing Safe Sequence if found

if (safe) {

printf("\nFollowing is the Safe Sequence:\n");

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

printf("P%d ", safesequence[i]);

} else {

printf("\nSystem is in an Unsafe State!\n");

Output:

Enter the number of processes: 5

Enter the number of resources: 3

Enter the allocation matrix:


73

010

200

302

211

002

Enter the max matrix:

753

322

902

422

533

Enter the available resources:

332

Need Matrix is:

743

122

600

211

531

Following is the Safe Sequence:

P1 P3 P4 P0 P2

Experiment-12
74

Simulate the following file allocation strategies


i) Sequential b) Indexed c) Linked

i) AIM: To write a ‘C’ Program to simulate Sequenced File Allocation strategy.

i) Sequential

#include<stdio.h>

void main()

int n,i,j,b[20],sb[20],t[20],x,c[20][20];

printf("Enter no.of files:");

scanf("%d",&n);

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

printf("Enter no. of blocks occupied by file%d:",i+1);

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

printf("Enter the starting block of file%d:",i+1);

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

t[i]=sb[i];

for(j=0;j<b[i];j++)

c[i][j]=sb[i]++;

printf("Filename\tStart block\tlength\n");

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

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

printf("Enter file name:");

scanf("%d",&x);

printf("\nFile name is:%d",x);

printf("\nlength is:%d",b[x-1]);
75

printf("\nblocks occupied:");

for(i=0;i<b[x-1];i++)

printf("%4d\t",c[x-1][i]);

Output:

Enter no.of files:3

Enter no. of blocks occupied by file1:4

Enter the starting block of file1:5

Enter no. of blocks occupied by file2:3

Enter the starting block of file2:10

Enter no. of blocks occupied by file3:2

Enter the starting block of file3:15

Filename Start block length

1 5 4

2 10 3

3 15 2

Enter file name:2

File name is:2

length is:3

blocks occupied: 10 11 12
76

b) Linked
#include<stdio.h>

struct file

char fname[10];

int start,size,block[10];

}f[10];

main()

int i,j,n;

printf("\nEnter no. of files:");

scanf("%d",&n);

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

printf("\nEnter file name:");

scanf("%s",&f[i].fname);

printf("\nEnter starting block:");

scanf("%d",&f[i].start);

f[i].block[0]=f[i].start;

printf("\nEnter no.of blocks:");

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

printf("\nEnter block numbers:");

for(j=1;j<=f[i].size;j++)

scanf("%d",&f[i].block[j]);

}
77

printf("File\tstart\tsize\tblock\n");

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

printf("%s\t%d\t%d\t",f[i].fname,f[i].start,f[i].size);

for(j=1;j<=f[i].size-1;j++)

printf("%d--->",f[i].block[j]);

printf("%d",f[i].block[j]);

printf("\n");

Output:

Enter no. of files:2

Enter file name:file1

Enter starting block:5

Enter no.of blocks:3

Enter block numbers:6 7 8

Enter file name:file2

Enter starting block:10

Enter no.of blocks:4

Enter block numbers:11 12 13 14

File start size block

file1 5 3 6--->7--->8

file2 10 4 11--->12--->13--->14

EXPERIMENT 13:
Download and install nachos operating system and experiment with it

Setting Up Your Account


78

The Nachos software is built using the GNU make program. You will need to modify
your PATH environment variable so that when you run make, GNU make, and not some
other make, will be executed. Your PATH should also include /u/cs350/bin, since there are a
number of useful Nachos-related programs there.

Your PATH is normally set by a command in your .cshrc file, in your home directory, each time
you log in. (If you are using some shell other than csh, it should have its own startup file, which
you can modify.) In the CSCF standard .cshrc file, you can do this by changing the line

setenv PATH `/bin/showpath standard`


to
setenv PATH `/bin/showpath gnu /u/cs350/bin standard`
Note the backquotes that are used in the above commands. They are important, and they must be
backquotes and not regular forward quotes. Note also that the gnu argument must come
before standard in order for GNU make to become the default.

This change will take effect the next time you log in. If you would like the change to take effect
immediately, you need to get your shell to re-load the initialization file you just changed.
Assuming you are using csh, you can do that by typing source ~/.cshrc.

Installing Nachos

Create a directory that will contain the nachos installation (ie ~/cs350).

To install Nachos, use the script /u/cs350/bin/install_nachos. This script takes one parameter,
which is the name of the directory into which Nachos should be installed. Assuming that
your PATH has been set up as described above, you should be able to type

install_nachos cs350
where cs350 is the name of the directory.

Building Nachos

Once Nachos is installed, you should try compiling it. There are actually three separate chunks of
code that get installed in your account when you run install_nachos. One is the code for
the nachos program itself. This program is written in C++ and implements the machine
simulation and the operating system for the simulated machine. The second is a set of test
programs. These programs are written in C. They run on the simulated machine, and are used to
test its operating system. The third is the coff2noff program for converning a COFF (Common
Object File Format) file to a NOFF file (Nachos Object File Format). The first chunk is by far
the largest of the three.

These three chunks of code must be built separately. First build the coff2noff program in the
directory coff2noff . (All relative pathnames are assumed to be relative to the main Nachos
79

directory, which is cs350_XX/nachos if you installed nachos in cs350_XX.) To build coff2noff,


change into the coff2noff directory and type

make

The test programs live in, and are built in, the directory code/test. (They require the use of
coff2noff, so you must compile coff2noff first.) In the directory code/test , you will find a
Makefile, which can be used to build the test programs. The Makefile contains instructions on
how to do the build.

The source code for the nachos program itself lives in several directories: code/lib,
code/machine, code/threads, code/filesys, code/userprog, and code/network. The program is built
using the Makefile in one of the "build" directories. You need to choose a build directory
depending on the type of machine you are currently logged in to. As of January 2003, all of the
CPU servers in the CSCF undergraduate environment are running Solaris, so you should work in
the build.solaris directory.

Once you are in the appropriate build directory, read the Makefile carefully, and follow the
instructions in it. It explains how to build the nachos program.

Running Nachos

Once you have built nachos, you should be able to run it by simply typing
./nachos
in the build directory. The command line argument -u will give you a list of the available
command line options. Using these options, you can control what nachos does when it runs. For
starters, you may wish to try the -K and -C flags, which run some simple self-tests. You can also
try asking Nachos to run a very simple test program called halt, which is found in
the code/test directory. To try this, type
./nachos -d ca -x ../test/halt
The -d ca turns on the address space (a) and system call (c) related debugging output.
The halt program simply makes the "Halt" system call, which causes the machine simulator to
halt and print out some statistics. Have a look at the halt program. It is in code/test/halt.c.

For more details, you can look in the file code/threads/main.cc. In fact, this is the best place to
start reading the Nachos code, since this is where it all begins.

Nachos Directory Structure

The main nachos directory contains three sub-directories:


coff2noff/
The source code and Makefiles for coff2noff, which is a program for converting COFF
(Common Object File Format) files to NOFF (Nachos Object File Format) files. Note
that noff.h in this directory is a link to the file noff.h in userprog.
80

c++-example/
The Nachos operating system is written in a subset of C++. This directory contains an
excellent primer on C++. This primer is good reading for those who need a refresher, and
even for those of you who are experienced C++ programmers. In particular, it explains
why some of the "features" of C++ are not used at all in Nachos.
code/
All of the source code for the Nachos operating system, the machine simulation, and the
test programs can be found here. This code is organized into several sub-directories:
lib
utilities used by the rest of the Nachos code
machine/
The machine simulation. Except as noted in machine.h, you may not modify the code in
this directory.
threads/
Nachos is a multi-threaded program. Thread support is found here. This directory also
contains the main() routine of the nachos program, in main.cc.
userprog/
Nachos operating system code to support the creation of address spaces, loading of user
(test) programs, and execution of test programs on the simulated machine. The exception
handling code is here, in exception.cc.
filesys/
Two different file system implementations are here. The "real" file system uses the
simulated workstation's simulated disk to hold files. A "stub" file system translates
Nachos file system calls into UNIX file system calls. This is useful initially, so that files
can be used (e.g., to hold user programs) before you have had a chance to fix up the
"real" file system. By default, the "stub" file system is build into the nachos program and
the "real" file system is not. This can be changed by setting a flag in the Nachos makefile.
network/
Nachos operating system support for networking, which implements a simple "post
office" facility. Several independent simulated Nachos machines can talk to each other
through a simulated network. Unix sockets are used to simulate network connections
among the machines.
test/
User test programs to run on the simulated machine. As indicated earlier, these are
separate from the source for the Nachos operating system and workstation simulation.
This directory contains its own Makefile. The test programs are very simple and are
written in C rather than C++.

You might also like