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

OS LAB

Uploaded by

Mrunni Mrinalini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

OS LAB

Uploaded by

Mrunni Mrinalini
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Andhra Loyola Institute of Engineering and Technology:

Vijayawada
LAB NAME: OPERATING SYTSEM
REG:R23 Ac.yr:2024-25
CLASS: II BTech Sem--2

1. Practicing of Basic UNIX Commands.


2. Write programs using the following UNIX operating system calls Fork, exec, getpid,
exit, wait, close, stat, opendir and readdir
3. Simulate UNIX commands like cp, ls, grep, etc.,
4. Simulate the following CPU scheduling algorithms a) Round Robin b) SJF c) FCFS d)
Priority
5. Implement a dynamic priority scheduling algorithm.
6. Assume that there are five jobs with different weights ranging from 1 to 5. Implement
round robin algorithm with time slice equivalent to weight.
7. Implement priority scheduling algorithm. While executing, no process should wait for
more than 10 seconds. If the waiting time is more than 10 seconds that process has to be
executed for at least 1 second before waiting again.
8. Control the number of ports opened by the operating system with a) Semaphore b)
Monitors.
9. Simulate how parent and child processes use shared memory and address space.
10. Simulate sleeping barber problem.
11. Simulate dining philosopher’s problem.
12. Simulate producer-consumer problem using threads.
13. Implement the following memory allocation methods for fixed partition a) First fit b)
Worst fit c) Best fit
14. Simulate the following page replacement algorithms a) FIFO b) LRU c) LFU etc.,
15. Simulate Paging Technique of memory management
16. Simulate Bankers Algorithm for Dead Lock avoidance and prevention
17. Simulate the following file allocation strategies a) Sequential b) Indexed c) Linked
18. Simulate all File Organization Techniques a) Single level directory b) Two level c)
Hierarchical d) DAG
UNIX SHELL:
A UNIX shell is a command-line interpreter that provides a user interface for the Unix operating
system . Users direct the operation of the computer by entering commands as text for a
command line interpreter to execute or by creating text scripts of one or more such commands.

1. Discuss about basic shell commands in Linux.


Logging In
login [name | option]
➢ Log in to the system. login asks for a username (name can be supplied on the command line)
and password (if appropriate).
➢ If successful, login updates accounting files, sets various environment variables, notifies
users if they have mail, and executes startup shell files.
Example: login: arun
Password: Make directory (mkdir)

This command is used to create a new directory.


Syntax: $mkdir dirname- The name of the directory that you wish to create.
Example: $ mkdir example - This would create a new directory called example.

Change directory (cd)


Changes the directory.
Syntax: $cd [directory] directory -Name of the directory user wishes to enter.
$cd.. Used to go back one directory on the majority of all Unix shells. It is important that the space
be between the cd and the..
$cd - When in a Korn shell to get back one directory used to go back one directory.
Example: $cd mydir- The above example would go into the mydir directory if it exists.
$cd ../home/users/computerhope
The above example would go back one directory and then go into the home/users/computerhope
directory. cd ../../ -Next, the abo ve example would go back two directories.

Cd - Finally, typing just cd alone will move you into the home directory.
Output: $ cd example [student@server example]$ View directory (ls)

List the content of a current directory.


Syntax: $ls [-options] name

Options, a - to list all directory entries


d - to list name of directories
l - to list files in long form
t - to list files sorted by name
Example: $ls –l - list each of the files in the current directory and the files
permissions, the size of the file, date of the last modification, and the file name or directory.
Output: [student@server example]$ls –l

Copy directory contents (cp)


Copying a file from one directory to another directory.
Syntax: $cp source directory destination directory
Example: [student@server ~]$ cp /home/student/example/Raj /home/student/example2 The
above command copy the contents from the directory Raj to example2
Rename the directory (rm)
This is used to rename a directory.
Syntax: $rm oldname newname
Example: $ rm example2 exapmle3
Remove directory (rmdir)
Deletes a directory.
Syntax: $rmdir [option]... directory...
Example: $rmdir example3 (For Empty Directory)
$rm -r example3 (For non-empty Directory)
Current directory (pwd)
This command displays full path of the current working directory.
Syntax: $pwd
Example: $pwd
/home/student/example
Create and view file (cat)
Allows look, modifying or combining a file.
Syntax: cat > filename */create file/*
cat filename */view file/*
Example: $cat > file1
Hai
How are you?
[1]+ Stopped cat >file1
$cat file1
Hai
How are you?
Copy file (cp)
Used to create duplicate copies of ordinary file.
Syntax: $cp source destination
Example: $cp file1 file2 (file1 contents were copied into file2)
Move a file (mv)
Used to rename a file.
Syntax: $mv oldname newnmae
Example: $mv file1 file2 (file1 has been renamed as file2)
Delete a file (rm)
Used to delete a file.
Syntax: $rm filename
Example: $rm file1(file1 has been removed)

Head
This command displays the initial part of the file. By default it displays first 10 lines of the file.
Syntax: $head filename
Example: $head file1 (It will show the top 10 lines of file1)
Tail
This command displays the later part of the file. By default it displays first 10 lines of the file.
Syntax: $tail filename
Example: $tail -4 file1 (It will show the last 4 lines of the file1)

Line, Word, character counting (wc)


This command is used to count the number of lines, words and characters of information contained
in a file.
Syntax: $wc [option] filename Options, l – to count the number of lines
c – to count the number of characters w – to count the number of words
Example: $wc file1
Sort a file or directory (sort)
Used to sort file or directory contents in ascending and descending order.
Syntax: $sort filename (ascending) $sort –r filename (descending)
Example: $sort file1 Data structures Fundamentals
Problem solving
$sort –r file1 Problem solving Fundamentals Data structures
Find file contents (grep)
This command is used to find particular information in a file
Syntax: $grep [pattern] filename
Example: $grep hai file1 hai

Set file permissions (chmod)


Chmod command is used to change the permission for the existing file. This command can be used in
two ways to change the permission. They are
Symbolic Mode:
Syntax: $chmod [who][opcode][mode] filename

Who OpcodeMode
u – User ‘+’ - add Permission r – read
g – Group ‘-‘ - Remove Permission w – Write
o – Other ‘=’ – Assign Absolute x - execute
a – All
Example: $chmod u+r file1 (read mode enabled to the users of the file1)
Absolute Mode:
Syntax: $chmod [octalnumber] filename
Example: $chmod 641 file1
Find file (or) directory (find)
Used to find a particular file or a directory
Syntax: $find filename
Example: $find file1 file1
ln(link)
Establish link between more than one file. The modification of one file reflects in others also.
Syntax: $ln filename1 filename2
Example: $ln raja surya
od(octaldump)
Used to display the ascii octal value of the file contents.
Syntax: od [option] filename
Options, c – to display content of the file in characters b – to display octal value of the content
of file
cd – to display octal value and its character of the file.
Example: od –c file1
Who
It displays user names who are all logging on a system

Syntax: $who
Example: student pts/1 Apr 20 14:40(192.17.6.2)
student2 pts/2 Apr 20 14:10(192.17.6.34)
student5 pts/5 Apr 20 14:16(192.17.6.5)
Who am i
This command tells the login details of a user.
Syntax: $who am i
Example: student pts/1 Apr 20 14:40(192.17.6.2)
Man
The man command displays the online manual pages.
Syntax: $man command name
Example: man ls
tty
Knowing the name of the terminal.
Syntax: $tty Output: /dev/tty 02
Echo
This command used to print
Example: $echo unix lab unix lab
Date
This command used to display system date information
Syntax: $date
Example: $date - To display the system date and time.
Mon Apr 20 15:41:50 EDT 2009
$date +%m - To display only the month number. 4
$date +%h - To display month in character. April
$date +”%h%m” - To display month in character and number April 4
Write
This write command used to send message when the user logging in.
Syntax: $write username message
Example: $write user01 hello
Mail
It allows to send message if the user doesn’t logging in.
Syntax: $mail username Subject:
//message// CC:
Example: $mail student Subject: hai
*****
*****
Pipe symbol
The pipe enables the user to take the output from command1 and feed it directly into the input of
command2.This is done the character “|”, which is placed between the two commands.
Syntax: $command1|command2|…|commandn
Example: $who|wc –l|temp
Combining commands
More than one command can be given in the same command line. Each command must be
separated by a semicolon (;). There are two types
Sequential commands
Give several commands on the same line by separating them with a semicolon (;)
Syntax: $command1; command2; commandn Example:: $chmod + rwx emp;ls – l emp
Command grouping
We can group commands using parentheses. Each command inside the parentheses must be
separated by semicolon. The grouped commands output will be sent to another file. We can see the
output by opening the file.
Syntax: $(commnad1;command2)>filename
Example: $(date;ls –l emp)>temp
Process management:
In Linux process management commands are used to the following purpose:
➢ Identifying process
➢ Monitoring and controlling the process
➢ Modifying and obtaining various information from process
➢ The most familiar process management commands are ps, top, pstree and kill, etc,
Ps:
This command is used to display the process status
Syntax: $ps Example: $ps Output:
PID Terminal Time Command
1096 pts/1 00.01.19 bash
1081 pts/1 00.05.23 man
Pgrep:
➢ It provides an interface, enabling to select processes using simple pattern matching
➢ It lists the process IDs (PIDs) of processes matching the specified pattern.
Syntax: $pgrep [option] [pattern]
Example: $pgrep bash
Pidof
It enables user to locate the Process ID (PID) of a process by name
Syntax: $pidof [option] process
Example: $pidof man
Pstree:
➢ Pstree displays all running process as a tree with init as root.
➢ It will display the parent – child relationship between processes in a clear manner.
Syntax: $pstree [options]
Top:
➢ Top command displays real time CPU and memory usage and current system uptime
information.
➢ It is tool in every system administrator toolbox.
Syntax: $top [options]
Tload:
The tload command display a real-time text mode graph of the system’s load average.
Syntax: $tload[options]
Terminating the process:
These terminating commands are used to stop the individual or all process.
Kill:
This is used to terminating the process. This is the /bin/kill command.
Syntax: $kill [option] IDs
Example: $kill 1029 Kill all:
Kill processes by command name. If more than one process is running the specified command, kill all
of them. Treat command names that contain a / as files; kill all processes that are executing that file.
Syntax: $killall [options] names

2A)PROGRAM FOR FORK() ,GETPID(), WAIT(),EXIT()


#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main( )
{
int pid;
pid=fork( );
if(pid<0)
{
printf(“error in executing fork”); exit(0);
}
else if(pid==0)
{
printf(“\n Child process is under execution”);
printf(“\n Process id of the child process is %d”, getpid());
printf(“\nProcess id of the parent process is %d”, getppid());
}
Else {
printf(“\n Parent process is under execution”); wait(Null);
printf(“\n Process id of the parent process is %d”, getpid());
printf(“\n Process id of the child process in parent is %d”, pid());
printf(“\n Process id of the parent of parent is %d”, getppid());
}
return(0); }

OUTPUT:

Child process under execution


Process id of the child process is: 134776 Process id of the parent process is: 13215 Parent process is
under execution
Process id of the child process in parent is: 13522 Process id of the parent of parent is: 13215

2b)PROGRAM FOR OPENDIR AND READDIR

#include<stdio.h>
#include<sys/types.h>
#include<sys/dir.h>
void main(int age,char *argv[])
{
DIR *dir;
struct dirent *rddir;
printf("\n Listing the directory content\n");
dir=opendir(argv[1]);
while((rddir=readdir(dir))!=NULL)
{
printf("%s\t\n",rddir->d_name);
}
closedir(dir);
}
OUTPUT:
RP
roshi.c first.c pk6.c f2 abc FILE1

OUTPUT:

Enter file name: file 5 Enter the pattern: roll no Roll no not found

3B)PROGRAM FOR CP

#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
main(int argc,char *argv[])
{
FILE *fp; char ch; int sc=0;
fp=fopen(argv[1],"r"); if(fp==NULL)
printf("unable to open a file",argv[1]);
else {
while(!feof(fp))
{
ch=fgetc(fp); if(ch==' ') sc++;
}
printf("no of spaces %d",sc); printf("\n");
fclose(fp);
}
}

OUTPUT:

File opened
No spaces found

3C)PROGRAM FOR LS

#include<stdio.h>
#include<dirent.h>
int main()
{
struct dirent **namelist;
int n,i;
char pathname[100];
scanf("%s",&pathname);
getcwd(pathname);
n=scandir(pathname,&namelist,0,alphasort);
if(n<0)
printf("Error"); else for(i=0;i<n;i++)
printf("%s\n",namelist[i]->d_name);
}

OUTPUT:

Enter the path : C:\Users\CPLAB> Desktop>ls Directory of C:\Users\CPLAB\Desktop

23-07-2022 10:30 <DIR> .


23-07-2022 10:30 <DIR> ..
22-07-2022 12:09 2,595 5A3.txt
01-10-2021 11:43 2,069 Anaconda Navigator (Anaconda3).lnk
01-10-2021 10:59 1,181 Android Studio.lnk
15-07-2022 14:43 16,269 BDA EXTERNAL.docx
22-07-2022 15:23 16,418 Best-Fit-Algorithm-in-C-and-C.webp
23-07-2022 09:57 751,256 CN-OS-LP LAB MANUAL K.ROSHAN.pdf
01-10-2021 10:42 2,789 IDLE (Python 3.9 64-bit).lnk
09-07-2022 14:04 45,451 IIcse A.xlsx
22-07-2022 16:05 23,888 Indexed-File-Allocation-Program-in-C-and-C-Output.webp
21-07-2022 15:06 15,446 IPC.docx
22-07-2022 10:31 19,951 JNTUA PRACTICAL END EXAM-2019 1.docx
22-07-2022 15:03 14,163 lfu.docx
21-07-2022 16:20 116,380 New Microsoft Word Document.docx
21-07-2022 16:21 116,367 os labmanual.docx
14-07-2022 12:46 13,553 paging tech.docx
23-07-2022 10:29 149,642 R 20 OS LAB MANUAL.docx
01-10-2021 15:55 2,117 SQL Plus.lnk
21-12-2021 11:32 515,132,968 VMware-workstation-full-10.0.3-1895310.exe
18 File(s) 516,442,503 bytes
2 Dir(s) 190,711,894,016 bytes free

4A)PROGRAM FOR ROUND ROBIN

#include<stdio.h> int main()


{
int i,j,n,bu[10],wa[10],tat[10],t,ct[10],max; float awt=0,att=0,temp=0;
printf("Enter the no of processes -- "); scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1); scanf("%d",&bu[i]);
ct[i]=bu[i];
}
printf("\nEnter the size of time slice -- "); scanf("%d",&t);
max=bu[0]; for(i=1;i<n;i++) if(max<bu[i]) max=bu[i]; for(j=0;j<(max/t)+1;j++) for(i=0;i<n;i++) if(bu[i]!
=0)
if(bu[i]<=t)
{
tat[i]=temp+bu[i]; temp=temp+bu[i]; bu[i]=0;
}
else
{
bu[i]=bu[i]-t; temp=temp+t;
}
for(i=0;i<n;i++)
{
wa[i]=tat[i]-ct[i]; att+=tat[i]; awt+=wa[i];}
printf("\nThe Average Turnaround time is -- %f",att/n); printf("\nThe Average Waiting time is -- %f
",awt/n);
printf("\n\tPROCESS\t BURST TIME \t WAITING TIME\tTURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\t%d \t %d \t\t %d \t\t %d \n",i+1,ct[i],wa[i],tat[i]);
}

OUTPUT:

Enter the no of processes -- 3

Enter Burst Time for process 1 -- 24 Enter Burst Time for process 2 -- 3 Enter Burst Time for process 3
-- 3 Enter the size of time slice -- 3
The Average Turnaround time is -- 15.000000 The Average Waiting time is -- 5.000000
PROCESS BURST TIME WAITING TIME TURNAROUND TIME
1 24 6 30
2 3 3 6
3 3 6 9

4B)PROGRAM FOR SJF:


#include<stdio.h> int main()
{
int p[20], bt[20], wt[20], tat[20], i, k, n, temp; float wtavg, tatavg;
printf("\nEnter the number of processes -- "); scanf("%d", &n);
for(i=0;i<n;i++)
{
p[i]=i;
printf("Enter Burst Time for Process %d -- ", i); scanf("%d", &bt[i]);

}
for(i=0;i<n;i++) for(k=i+1;k<n;k++) if(bt[i]>bt[k])
{
temp=bt[i]; bt[i]=bt[k]; bt[k]=temp; temp=p[i]; p[i]=p[k]; p[k]=temp;
}
wt[0] = wtavg = 0; tat[0] = tatavg = bt[0]; for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i]; wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\n\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", p[i], bt[i], wt[i], tat[i]); printf("\nAverage Waiting Time --
%f", wtavg/n); printf("\nAverage Turnaround Time -- %f", tatavg/n);
}

OUTPUT:

Enter the number of processes -- 4 Enter Burst Time for Process 0 -- 6 Enter Burst Time for Process 1
-- 7 Enter Burst Time for Process 2 -- 8 Enter Burst Time for Process 3 -- 3

PROCESS BURST TIME WAITING TIME TURNAROUND TIME

P3 3 0 3
P0 6 3 9
P1 7 9 16
P2 8 16 24
Average Waiting Time -- 7.000000 Average Turnaround Time -- 13.000000

4C)PROGRAM FOR FCFS

#include<stdio.h> int main()


{
int bt[20], wt[20], tat[20], i, n; float wtavg, tatavg;
printf("\nEnter the number of processes --"); scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for Process %d -- ", i); scanf("%d", &bt[i]);
}
wt[0] = wtavg = 0; tat[0] = tatavg = bt[0]; for(i=1;i<n;i++)
{
wt[i] = wt[i-1] +bt[i-1];
tat[i] = tat[i-1] +bt[i]; wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\t PROCESS \tBURST TIME \t WAITING TIME\t TURNAROUND TIME\n");
for(i=0;i<n;i++)
printf("\n\t P%d \t\t %d \t\t %d \t\t %d", i, bt[i], wt[i], tat[i]); printf("\nAverage Waiting Time -- %f",
wtavg/n); printf("\nAverage Turnaround Time -- %f", tatavg/n);
}

OUTPUT:

Enter the number of processes --3

Enter Burst Time for Process 0 -- 24


Enter Burst Time for Process 1 -- 3

Enter Burst Time for Process 2 -- 3


PROCESS BURST TIME WAITING TIME TURNAROUND TIME

P0 24 0 24
P1 3 24 27
P2 3 27 30
Average Waiting Time -- 17.000000 Average Turnaround Time -- 27.000000

4D)PROGRAM FOR PRIORITY

#include<stdio.h> int main()


{
int p[20],bt[20],pri[20], wt[20],tat[20],i, k, n, temp; float wtavg, tatavg;
printf("Enter the number of processes --- "); scanf("%d",&n);
for(i=0;i<n;i++)
{
p[i] = i;
printf("Enter the Burst Time & Priority of Process %d --- ",i); scanf("%d %d",&bt[i], &pri[i]);
}
for(i=0;i<n;i++) for(k=i+1;k<n;k++) if(pri[i] > pri[k])
{
temp=p[i]; p[i]=p[k]; p[k]=temp; temp=bt[i]; bt[i]=bt[k]; bt[k]=temp; temp=pri[i]; pri[i]=pri[k];
pri[k]=temp;
}
wtavg = wt[0] = 0; tatavg = tat[0] = bt[0]; for(i=1;i<n;i++)
{
wt[i] = wt[i-1] + bt[i-1];
tat[i] = tat[i-1] + bt[i];
wtavg = wtavg + wt[i]; tatavg = tatavg + tat[i];
}
printf("\nPROCESS\t\tPRIORITY\tBURST TIME\tWAITING TIME\tTURNAROUND TIME");
for(i=0;i<n;i++)
printf("\n%d \t\t %d \t\t %d \t\t %d \t\t %d ",p[i],pri[i],bt[i],wt[i],tat[i]); printf("\nAverage Waiting
Time is --- %f",wtavg/n);
printf("\nAverage Turnaround Time is --- %f",tatavg/n);
}

OUTPUT:

Enter the number of processes --- 5


Enter the Burst Time & Priority of Process 0 --- 10 3
Enter the Burst Time & Priority of Process 1 --- 1 1
Enter the Burst Time & Priority of Process 2 --- 2 4
Enter the Burst Time & Priority of Process 3 --- 1 5
Enter the Burst Time & Priority of Process 4 --- 5 2

PROCESS PRIORITY BURST TIME WAITING TIME TURNAROUND TIME


1 1 1 0 1
4 2 5 1 6
0 3 10 6 16
2 4 2 16 18
3 5 1 18 19
Average Waiting Time is --- 8.200000 Average Turnaround Time is --- 12.000000

7) Program for Semaphore


#include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h>

sem_t mutex;

void* thread(void* arg)


{
//wait sem_wait(&mutex); printf("\nEntered..\n");

//critical section sleep(4);

//signal
printf("\nJust Exiting...\n"); sem_post(&mutex);
}

int main()
{
sem_init(&mutex, 0, 1); pthread_t t1,t2;
pthread_create(&t1,NULL,thread,NULL); sleep(2); pthread_create(&t2,NULL,thread,NULL);
pthread_join(t1,NULL); pthread_join(t2,NULL); sem_destroy(&mutex);
return 0;
}

OUTPUT:

Entered..

Just Exiting...

Entered..

Just Exiting...
8) PROGRAM FOR SHARED MEMORY [IPC]:

#include<sys/shm.h> #include<string.h> int main()


{
int i;
void *shared_memory; char buff[100];
int shmid;
shmid=shmget((key_t)2345, 1024, 0666|IPC_CREAT); printf("Key of shared memory is %d\n",shmid);
shared_memory=shmat(shmid,NULL,0);
//process attached to shared memory segment printf("Process attached at %p\n",shared_memory);
printf("Enter some data to write to shared memory\n"); read(0,buff,100); //get some input from user
strcpy(shared_memory,buff); //data written to shared memory printf("You wrote : %s\n",(char
*)shared_memory);
}

OUTPUT:
Key of shared memory is 0
Process attached at 0x7feaa4dea000
Enter some data to write to shared memory kuppam engineering college
You wrote : kuppam engineering college

9) PROGRAM FOR SLEEPING BARBER PROBLEM:

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


<semaphore.h> #include <time.h> #include <sys/types.h> #include <sys/time.h>

void *barber_function(void *idp); void *customer_function(void *idp); void serve_customer();


void *make_customer_function();
/* Mutex */ pthread_mutex_t srvCust;

/* Semaphores */ sem_t barber_ready; sem_t customer_ready; sem_t modifySeats;

/* Inputs */ int chair_cnt; int total_custs;

int available_seats;
int no_served_custs = 0; time_t waiting_time_sum;

void *barber_function(void *idp)


{
int counter = 0;
while (1)
{
/* Lock semaphore "customer_ready" - try to get a customer or sleep if there is none */
sem_wait(&customer_ready);
/* Lock semaphore "modifySeats" - try to get access to seats */ sem_wait(&modifySeats);
/* Increment by 1 the available seats */ available_seats++;
/* Unlock semaphore "modifySeats" */ sem_post(&modifySeats);

/* Unlock semap sem_post(&barbe


/* Lock mutex "srvCust" - protect service by the same barber from other threads */
pthread_mutex_lock(&srvCust);

/* Serve customer */ serve_customer();

/* Unlock mutex "srvCust" - finished service */ pthread_mutex_unlock(&srvCust);


printf("Customer was served.\n"); counter++;
if (counter == (total_custs - no_served_custs)) break;
}
pthread_exit(NULL);
}

void *customer_function(void *idp)


{
struct timeval start, stop;
/* Lock semaphore "modifySeats" */ sem_wait(&modifySeats);

/* If there is available seat */ if (available_seats >= 1)


{
/* Occupy a seat */ available_seats--;

printf("Customer[pid = %lu] is waiting.\n", pthread_self()); printf("Available seats: %d\n",


available_seats);
/* Start waiting-time counter */ gettimeofday(&start, NULL);
/* Unlock semaphore "customer_ready" - set the customer ready to be served */
sem_post(&customer_ready);

/* Unlock semaphore "modifySeats" */ sem_post(&modifySeats);

/* Lock semaphore "barber_ready" - wait for barber to get ready */ sem_wait(&barber_ready);

/* Stop waiting-time counter */ gettimeofday(&stop, NULL);


double sec = (double)(stop.tv_usec - start.tv_usec) / 1000000 + (double)(stop.tv_sec - start.tv_sec);
/* Assign the time spent to global variable (ms) */ waiting_time_sum += 1000 * sec;
printf("Customer[pid = %lu] is being served. \n", pthread_self());
}

else
{
/* Unlock semaphore "modifySeats" */ sem_post(&modifySeats); no_served_custs++;
printf("A Customer left.\n");
}
pthread_exit(NULL);
}

void serve_customer() {
/* Random number between 0 and 400 (miliseconds) */ int s = rand() % 401;
/* Convert miliseconds to microseconds */ s = s * 1000;
usleep(s);
}

void *make_customer_function() { int tmp;


int counter = 0;

while (counter < total_custs)


{
/* Declare and create a customer thread */ pthread_t customer_thread;
tmp = pthread_create(&customer_thread, NULL, (void *)customer_function, NULL); if (tmp)
printf("Failed to create thread.");
/* Increment the counter */ counter++;
/* Sleep for 100ms before creating another customer */ usleep(100000);
}
}

int main() {
/* Initialization, should only be called once */ srand(time(NULL));

/* Barber 1 thread */ pthread_t barber_1;


/* Thread that creates customers */ pthread_t customer_maker;
int tmp;
/* Initialize mutex */ pthread_mutex_init(&srvCust, NULL);

/* Initialize semaphores */ sem_init(&customer_ready, 0, 0);


sem_init(&barber_ready, 0, 0);
sem_init(&modifySeats, 0, 1);
printf("Please enter the number of seats: \n"); scanf("%d", &chair_cnt);
printf("Please enter the total customers: \n"); scanf("%d", &total_custs);
available_seats = chair_cnt;
/* Create barber thread */
tmp = pthread_create(&barber_1, NULL, (void *)barber_function, NULL);
if (tmp)
printf("Failed to create thread.");
/* Create customer_maker thread */
tmp = pthread_create(&customer_maker, NULL, (void *)make_customer_function, NULL);
if (tmp)
printf("Failed to create thread.");
/* Wait for threads to finish */ pthread_join(barber_1, NULL); pthread_join(customer_maker, NULL);
printf("\n \n");
printf("Average customers' waiting time: %f ms.\n", (waiting_time_sum / (double) (total_custs -
no_served_custs)));
printf("Number of customers that were forced to leave: %d\n", no_served_custs);
}
OUTPUT:

Please enter the number of seats:


1
Please enter the total customers:
5
Customer[pid = 140506826811136] is waiting. Available seats: 0
Customer[pid = 140506826811136] is being served. Customer[pid = 140506818307840] is waiting.
Available seats: 0 Customer was served.
Customer[pid = 140506818307840] is being served. Customer[pid = 140506809915136] is waiting.
Available seats: 0 A Customer left.
Customer was served.
Customer[pid = 140506809915136] is being served. Customer[pid = 140506793129728] is waiting.
Available seats: 0 Customer was served.
Customer[pid = 140506793129728] is being served. Customer was served.

Average customers' waiting time: 122.500000 ms. Number of customers that were forced to leave: 1
10) PROGRAM FOR DINING PHILOSOPHER’S PROBLEM:

#include<stdio.h> #define n 4
int compltedPhilo = 0,i; struct fork{
int taken;
}ForkAvil[n];

struct philosp{ int left;


int right;
}Philostatus[n];

void goForDinner(int philID){ //same like threads concept here cases implemented
if(Philostatus[philID].left==10 && Philostatus[philID].right==10)
printf("Philosopher %d completed his dinner\n",philID+1);
//if already completed dinner
else if(Philostatus[philID].left==1 && Philostatus[philID].right==1){
//if just taken two forks
printf("Philosopher %d completed his dinner\n",philID+1);

Philostatus[philID].left = Philostatus[philID].right = 10; //remembering that he completed dinner by


assigning value 10
int otherFork = philID-1;

if(otherFork== -1) otherFork=(n-1);

ForkAvil[philID].taken = ForkAvil[otherFork].taken = 0; //releasing forks printf("Philosopher %d


released fork %d and fork %d\n",philID+1,philID+1,otherFork+1); compltedPhilo++;
}
else if(Philostatus[philID].left==1 && Philostatus[philID].right==0){ //left already taken, trying for
right fork
if(philID==(n-1)){
if(ForkAvil[philID].taken==0){ //KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN
reverse DIRECTION
ForkAvil[philID].taken = Philostatus[philID].right = 1; printf("Fork %d taken by philosopher %d\
n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,philID+1);
}
}else{ //except last philosopher case int dupphilID = philID;
philID-=1;

if(philID== -1) philID=(n-1);

if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[dupphilID].right = 1; printf("Fork %d taken by Philosopher %d\
n",philID+1,dupphilID+1);
}else{
printf("Philosopher %d is waiting for Fork %d\n",dupphilID+1,philID+1);
}
}
}
else if(Philostatus[philID].left==0){ //nothing taken yet if(philID==(n-1)){
if(ForkAvil[philID-1].taken==0){ //KEY POINT OF THIS PROBLEM, THAT LAST PHILOSOPHER TRYING IN
reverse DIRECTION
ForkAvil[philID-1].taken = Philostatus[philID].left = 1; printf("Fork %d taken by philosopher %d\
n",philID,philID+1);
}else{
printf("Philosopher %d is waiting for fork %d\n",philID+1,philID);
}
}else{ //except last philosopher case if(ForkAvil[philID].taken == 0){
ForkAvil[philID].taken = Philostatus[philID].left = 1; printf("Fork %d taken by Philosopher %d\
n",philID+1,philID+1);
}else{
printf("Philosopher %d is waiting for Fork %d\n",philID+1,philID+1);
}
}
}else{}
}

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


ForkAvil[i].taken=Philostatus[i].left=Philostatus[i].right=0;

while(compltedPhilo<n){
/* Observe here carefully, while loop will run until all philosophers complete dinner Actually problem
of deadlock occur only thy try to take at same time
This for loop will say that they are trying at same time. And remaining status will print by go for
dinner function
*/ for(i=0;i<n;i++)
goForDinner(i);
printf("\nTill now num of philosophers completed dinner are %d\n\n",compltedPhilo);
}

return 0;}

OUTPUT:

Fork 1 taken by Philosopher 1


Fork 2 taken by Philosopher 2
Fork 3 taken by Philosopher 3 Philosopher 4 is waiting for fork 3
Till now num of philosophers completed dinner are 0 Fork 4 taken by Philosopher 1
Philosopher 2 is waiting for Fork 1
Philosopher 3 is waiting for Fork 2 Philosopher 4 is waiting for fork 3
Till now num of philosophers completed dinner are 0 Philosopher 1 completed his dinner
Philosopher 1 released fork 1 and fork 4
Fork 1 taken by Philosopher 2 Philosopher 3 is waiting for Fork 2 Philosopher 4 is waiting for fork 3
Till now num of philosophers completed dinner are 1 Philosopher 1 completed his dinner
Philosopher 2 completed his dinner
Philosopher 2 released fork 2 and fork 1
Fork 2 taken by Philosopher 3 Philosopher 4 is waiting for fork 3
Till now num of philosophers completed dinner are 2 Philosopher 1 completed his dinner
Philosopher 2 completed his dinner
Philosopher 3 completed his dinner Philosopher 3 released fork 3 and fork 2
Fork 3 taken by philosopher 4
Till now num of philosophers completed dinner are 3 Philosopher 1 completed his dinner
Philosopher 2 completed his dinner Philosopher 3 completed his dinner Fork 4 taken by philosopher
4
Till now num of philosophers completed dinner are 3

Philosopher 1 completed his dinner Philosopher 2 completed his dinner Philosopher 3 completed his
dinner Philosopher 4 completed his dinner

Philosopher 4 released fork 4 and fork 3

Till now num of philosophers completed dinner are 4


10)PROGRAM FOR

#include<stdio.h> void main()


{
int buffer[10], bufsize, in, out, produce, consume, choice=0; in = 0;
out = 0;
bufsize = 10;
while(choice !=3)
{
printf(“\n1. Produce \t 2. Consume \t3. Exit”); printf(“\nEnter your choice: ”); scanf(“%d”,&choice);
switch(choice) {
case 1: if((in+1)%bufsize==out) printf(“\nBuffer is Full”);
else
{

}
break;;;
printf(“\nEnter the value: “); scanf(“%d”, &produce); buffer[in] = produce;
in = (in+1)%bufsize; case 2: if(in == out)
printf(“\nBuffer is Empty”); else
{
consume = buffer[out];
printf(“\nThe consumed value is %d”, consume); out = (out+1)%bufsize;
}
break;

}}}
OUTPUT:

1. Produce 2. Consume 3. Exit Enter your choice: 2


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

11A)PROGRAM FOR FIRST FIT


#include<stdio.h>

void main()
{
int bsize[10], psize[10], bno, pno, flags[10], allocation[10], i, j;

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


{
flags[i] = 0;
allocation[i] = -1;
}
printf("Enter no. of blocks: "); scanf("%d", &bno);
printf("\nEnter size of each block: "); for(i = 0; i < bno; i++)
scanf("%d", &bsize[i]);

printf("\nEnter no. of processes: "); scanf("%d", &pno);


printf("\nEnter size of each process: "); for(i = 0; i < pno; i++)
scanf("%d", &psize[i]);
for(i = 0; i < pno; i++) //allocation as per first fit for(j = 0; j < bno; j++)
if(flags[j] == 0 && bsize[j] >= psize[i])
{
allocation[j] = i; flags[j] = 1; break;
}
//display allocation details
printf("\nBlock no.\tsize\t\tprocess no.\t\tsize"); for(i = 0; i < bno; i++)
{
printf("\n%d\t\t%d\t\t", i+1, bsize[i]); if(flags[i] == 1)
printf("%d\t\t\t%d",allocation[i]+1,psize[allocation[i]]); else
printf("Not allocated");
}
}
OUTPUT:

Enter no. of blocks: 3


Enter size of each block: 5 2 7 Enter no. of processes: 2 Enter size of each process: 1 4
Block no. size process no. size
1 5 1 1
2 2 Not allocated
3 7 2 4

11B)PROGRAM FOR BEST FIT:

#include<stdio.h> void main()


{
int fragment[20],b[20],p[20],i,j,nb,np,temp,lowest=9999; static int barray[20],parray[20];
printf("\n\t\t\tMemory Management Scheme - Best Fit"); printf("\nEnter the number of blocks:");
scanf("%d",&nb);
printf("Enter the number of processes:"); scanf("%d",&np);
printf("\nEnter the size of the blocks:-\n"); for(i=1;i<=nb;i++)
{
printf("Block no.%d:",i);
scanf("%d",&b[i]);
}
printf("\nEnter the size of the processes :-\n"); for(i=1;i<=np;i++)
{
printf("Process no.%d:",i);
scanf("%d",&p[i]);
}
for(i=1;i<=np;i++)
{
for(j=1;j<=nb;j++)
{
if(barray[j]!=1)
{

temp=b[j]-p[i]; if(temp>=0) if(lowest>temp)


{
parray[i]=j; lowest=temp;
}
}
}
fragment[i]=lowest; barray[parray[i]]=1; lowest=10000;
}
printf("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment"); for(i=1;i<=np && parray[i]!
=0;i++) printf("\n%d\t\t%d\t\t%d\t\t%d\t\t%d",i,p[i],parray[i],b[parray[i]],fragment[i]);
}

OUTPUT
Memory Management Scheme - Best Fit Enter the number of blocks:3
Enter the number of processes:3

Enter the size of the blocks:- Block no.1:10


Block no.2:20 Block no.3:30

Enter the size of the processes :- Process no.1: 25


Process no.2:15 Process no.3:10

Process_no Process_size Block_no Block_size Fragment

1 25 3 30 5
2 15 2 20 5
3 10 1 10 0

11C)PROGRAM FOR WORST FIT:

#include<stdio.h> #include<conio.h> #define max 25 void main()


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

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

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

12A)PROGRAM FOR FIFO:

#include <stdio.h> int main()


{
int referenceString[10], pageFaults = 0, m, n, s, pages, frames; printf("\nEnter the number of Pages:\
t");
scanf("%d", &pages);
printf("\nEnter reference string values:\n"); for( m = 0; m < pages; m++)
{
printf("Value No. [%d]:\t", m + 1); scanf("%d", &referenceString[m]);
}
printf("\n What are the total number of frames:\t");
{
scanf("%d", &frames);
}
int temp[frames];
for(m = 0; m < frames; m++)
{
temp[m] = -1;
}
for(m = 0; m < pages; m++)
{
s = 0;
for(n = 0; n < frames; n++)
{
if(referenceString[m] == temp[n])
{
s++;

pageFaults--;
}
}
pageFaults++;
if((pageFaults <= frames) && (s == 0))
{
temp[m] = referenceString[m];
}
else if(s == 0)
{
temp[(pageFaults - 1) % frames] = referenceString[m];
}
printf("\n");
for(n = 0; n < frames; n++)
{
printf("%d\t", temp[n]);
}
}
printf("\nTotal Page Faults:\t%d\n", pageFaults); return 0;
}
OUTPUT:

Enter the number of Pages: 5

Enter reference string values: Value No. [1]: 2


Value No. [2]: 5
Value No. [3]: 4
Value No. [4]: 8
Value No. [5]: 1

What are the total number of frames: 4

2 -1 -1 -1
2 5 -1 -1
2 5 4 -1
2 5 4 8
1 5 4 8
Total Page Faults: 5
12B)PROGRAM FOR LRU:

#include<stdio.h>
int findLRU(int time[], int n){
int i, minimum = time[0], pos = 0; for(i = 1; i < n; ++i){
if(time[i] < minimum){ minimum = time[i]; pos = i;
}
}
return pos;
}
int main()
{
int no_of_frames, no_of_pages, frames[10], pages[30], counter = 0, time[10], flag1, flag2, i, j, pos,
faults = 0;
printf("Enter number of frames: "); scanf("%d", &no_of_frames); printf("Enter number of pages: ");
scanf("%d", &no_of_pages); printf("Enter reference string: ");
for(i = 0; i < no_of_pages; ++i){ scanf("%d", &pages[i]);
}

for(i = 0; i < no_of_frames; ++i){ frames[i] = -1;


}

for(i = 0; i < no_of_pages; ++i){ flag1 = flag2 = 0;

for(j = 0; j < no_of_frames; ++j){ if(frames[j] == pages[i]){ counter++;


time[j] = counter; flag1 = flag2 = 1; break;
}
}

if(flag1 == 0){
for(j = 0; j < no_of_frames; ++j){ if(frames[j] == -1){ counter++;
faults++;
frames[j] = pages[i]; time[j] = counter; flag2 = 1;

break;
}
}
}

if(flag2 == 0){
pos = findLRU(time, no_of_frames); counter++;
faults++;
frames[pos] = pages[i]; time[pos] = counter;
}

printf("\n");
for(j = 0; j < no_of_frames; ++j){ printf("%d\t", frames[j]);
}
}
printf("\n\nTotal Page Faults = %d", faults);

return 0;
}

12C) PROGRAM FOR LFU:

#include<stdio.h> #include<conio.h> void main()


{
int rs[50], i, j, k, m, f, cntr[20], a[20], min, pf=0; clrscr();
printf("\nEnter number of page references -- "); scanf("%d",&m);
printf("\nEnter the reference string -- "); for(i=0;i<m;i++)
scanf("%d",&rs[i]);
printf("\nEnter the available no. of frames -- "); scanf("%d",&f);
for(i=0;i<f;i++)
{
cntr[i]=0; a[i]=-1;
}
printf("\nThe Page Replacement Process is \n"); for(i=0;i<m;i++)
{
for(j=0;j<f;j++) if(rs[i]==a[j])
{
cntr[j]++; break;
}
if(j==f)
{
min = 0; for(k=1;k<f;k++) if(cntr[k]<cntr[min]) min=k;
a[min]=rs[i]; cntr[min]=1; pf++;
}
printf("\n"); for(j=0;j<f;j++) printf("\t%d",a[j]); if(j==f)
printf("\tPF No. %d",pf);
}
printf("\n\n Total number of page faults -- %d",pf); getch();
}

OUTPUT:

Enter number of page references -- 4

Enter the reference string -- 4 5 8 9

Enter the available no. of frames -- 2

The Page Replacement Process is

4 -1 PF No. 1
4 5 PF No. 2
8 5 PF No. 3
9 5 PF No. 4

Total number of page faults -- 4


13PROGRAM FOR PAGE REPLACEMENT

#include<stdio.h> #define MAX 50

int main()
{
int page[MAX],i,n,f,ps,off,pno; int choice=0;
printf("\nEnter the no of peges in memory: "); scanf("%d",&n);
printf("\nEnter page size: "); scanf("%d",&ps); printf("\nEnter no of frames: "); scanf("%d",&f);
for(i=0;i<n;i++)
page[i]=-1;
printf("\nEnter the page table\n");
printf("(Enter frame no as -1 if that page is not present in any frame)\n\n"); printf("\npageno\
tframeno\n-------\t ");
for(i=0;i<n;i++)
{
printf("\n\n%d\t\t",i); scanf("%d",&page[i]);
}
do
{
printf("\n\nEnter the logical address(i.e,page no & offset):"); scanf("%d%d",&pno,&off);
if(page[pno]==-1)
printf("\n\nThe required page is not available in any of frames"); else
printf("\n\nPhysical address(i.e,frame no & offset):%d,%d",page[pno],off); printf("\nDo you want to
continue(1/0)?:");
scanf("%d",&choice);
}while(choice==1); return 1;
}
OUTPUT:

Enter the no of peges in memory: 4

Enter page size: 10 Enter no of frames: 10


Enter the page table
(Enter frame no as -1 if that page is not present in any frame)

pageno frameno

0
-1

1
8

2
-1

3
6

Enter the logical address(i.e,page no & offset):200 2

Physical address(i.e,frame no & offset):14,2 Do you want to continue(1/0)?:

14)PROGRAM FOR DEAD LOCK

#include<stdio.h>

#include<conio.h> void main()


{
int n,r,i,j,k,p,u=0,s=0,m;
int block[10],run[10],active[10],newreq[10];
int max[10][10],resalloc[10][10],resreq[10][10]; int totalloc[10],totext[10],simalloc[10];
//clrscr();
printf("Enter the no of processes:"); scanf("%d",&n);
printf("Enter the no ofresource classes:"); scanf("%d",&r);
printf("Enter the total existed resource in each class:"); for(k=1; k<=r; k++)
scanf("%d",&totext[k]);
printf("Enter the allocated resources:"); for(i=1; i<=n; i++)
for(k=1; k<=r; k++) scanf("%d",&resalloc);
printf("Enter the process making the new request:"); scanf("%d",&p);
printf("Enter the requested resource:"); for(k=1; k<=r; k++) scanf("%d",&newreq[k]);
printf("Enter the process which are n blocked or running:"); for(i=1; i<=n; i++)
{
if(i!=p)
{
printf("process %d:\n",i+1); scanf("%d%d",&block[i],&run[i]);
}
}
block[p]=0; run[p]=0;
for(k=1; k<=r; k++)
{

j=0;
for(i=1; i<=n; i++)
{
totalloc[k]=j+resalloc[i][k]; j=totalloc[k];
}
}
for(i=1; i<=n; i++)
{
if(block[i]==1||run[i]==1) active[i]=1;
else active[i]=0;
}
for(k=1; k<=r; k++)
{
resalloc[p][k]+=newreq[k];

totalloc[k]+=newreq[k];
}
for(k=1; k<=r; k++)
{
if(totext[k]-totalloc[k]<0)
{ u=1;
break;
}
}
if(u==0)
{
for(k=1; k<=r; k++) simalloc[k]=totalloc[k]; for(s=1; s<=n; s++) for(i=1; i<=n; i++)
{
if(active[i]==1)
{ j=0;
for(k=1; k<=r; k++)
{
if((totext[k]-simalloc[k])<(max[i][k]-resalloc[i][k]))
{ j=1;
break;
}
}
}
if(j==0)

{
active[i]=0; for(k=1; k<=r; k++)
simalloc[k]=resalloc[i][k];
}
} m=0;
for(k=1; k<=r; k++) resreq[p][k]=newreq[k]; printf("Deadlock willn't occur");
}
else
{
for(k=1; k<=r; k++)
{
resalloc[p][k]=newreq[k]; totalloc[k]=newreq[k];
}
printf("Deadlock will occur");
}
getch();
}
OUTPUT:
15A)PROGRAM FOR SEQUENTIAL FILE ALLOCATION
#include <stdio.h> #include <conio.h> #include <stdlib.h>

void recurse(int files[]){


int flag = 0, startBlock, len, j, k, ch;
printf("Enter the starting block and the length of the files: "); scanf("%d%d", &startBlock, &len);
for (j=startBlock; j<(startBlock+len); j++){ if (files[j] == 0)
flag++;
}
if(len == flag){
for (int k=startBlock; k<(startBlock+len); k++){ if (files[k] == 0){
files[k] = 1; printf("%d\t%d\n", k, files[k]);
}
}
if (k != (startBlock+len-1))
printf("The file is allocated to the disk\n");
}
else
printf("The file is not allocated to the disk\n"); printf("Do you want to enter more files?\n");
printf("Press 1 for YES, 0 for NO: "); scanf("%d", &ch);
if (ch == 1) recurse(files); else
exit(0); return;
}
int main()
{
int files[50];
for(int i=0;i<50;i++) files[i]=0;
printf("Files Allocated are :\n"); recurse(files);
getch(); return 0;}
OUPUT:
Enter the starting block and the length of the files: 14 3

14 1
15 1
16 1
The file is allocated to the disk Do you want to enter more files? Press 1 for YES, 0 for NO: 1
Enter the starting block and the length of the files: 14 1 The file is not allocated to the disk
Do you want to enter more files? Press 1 for YES, 0 for NO: 1
Enter the starting block and the length of the files: 14 2 The file is not allocated to the disk
Do you want to enter more files? Press 1 for YES, 0 for NO: 0
15B)PROGRAM FOR INDEXED FILE ALLOCATION

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


int files[50], indexBlock[50], indBlock, n; void recurse1();
void recurse2(); void recurse1(){
printf("Enter the index block: "); scanf("%d", &indBlock);
if (files[indBlock] != 1){
printf("Enter the number of blocks and the number of files needed for the index %d on the disk: ",
indBlock);
scanf("%d", &n);
}
else{
printf("%d is already allocated\n", indBlock); recurse1();
}
recurse2();
}
void recurse2(){ int ch;
int flag = 0;
for (int i=0; i<n; i++){ scanf("%d", &indexBlock[i]); if (files[indexBlock[i]] == 0) flag++;
}
if (flag == n){
for (int j=0; j<n; j++){ files[indexBlock[j]] = 1;
}
printf("Allocated\n"); printf("File Indexed\n"); for (int k=0; k<n; k++){
printf("%d > %d : %d\n", indBlock, indexBlock[k], files[indexBlock[k]]);
}
}
else{
printf("File in the index is already allocated\n"); printf("Enter another indexed file\n"); recurse2();
}
printf("Do you want to enter more files?\n"); printf("Enter 1 for Yes, Enter 0 for No: "); scanf("%d",
&ch);

if (ch == 1) recurse1(); else exit(0); return;


}
int main()
{
for(int i=0;i<50;i++) files[i]=0; recurse1();
return 0;
}
OUTPUT:
Enter the index block: 5

Enter the number of blocks and the number of files needed for the index 5 on the disk: 4 1 2 3 4
Allocated File Indexed 5 > 1 : 1
5 >2:1
5 >3:1
5 >4:1
Do you want to enter more files? Enter 1 for Yes, Enter 0 for No:
15C)PROGRAM FOR LINKED FILE ALLOCATION
#include <stdio.h> #include <conio.h> #include <stdlib.h>
void recursivePart(int pages[]){

int st, len, k, c, j;


printf("Enter the index of the starting block and its length: "); scanf("%d%d", &st, &len);
k = len;
if (pages[st] == 0){
for (j = st; j < (st + k); j++){
if (pages[j] == 0){ pages[j] = 1;
printf("%d >%d\n", j, pages[j]);
}
else {
printf("The block %d is already allocated \n", j); k++;
}
}
}
else
printf("The block %d is already allocated \n", st); printf("Do you want to enter more files? \n");
printf("Enter 1 for Yes, Enter 0 for No: "); scanf("%d", &c);
if (c==1) recursivePart(pages);
else
exit(0); return;
}
int main(){
int pages[50], p, a;
for (int i = 0; i < 50; i++) pages[i] = 0;
printf("Enter the number of blocks already allocated: "); scanf("%d", &p);
printf("Enter the blocks already allocated: "); for (int i = 0; i < p; i++){
scanf("%d", &a); pages[a] = 1;
}
recursivePart(pages); getch();
return 0;
}
OUTPUT:

Enter the number of blocks already allocated: 3 Enter the blocks already allocated: 1 3 5
Enter the index of the starting block and its length: 2 2 1

2 >1
The block 3 is already allocated 4 >1
Do you want to enter more files?
Enter 1 for Yes, Enter 0 for No: Enter the index of the starting block and its length:

16 PROGRAM FOR SINGLE LEVEL DIRECTORY

#include<stdio.h> #include<conio.h> #include<string.h> void main()


{
int nf=0,i=0,j=0,ch;

char mdname[10],fname[10][10],name[10]; clrscr();


printf("Enter the directory name:"); scanf("%s",mdname);
printf("Enter the number of files:"); scanf("%d",&nf);
do
{
printf("Enter file name to be created:"); scanf("%s",name);
for(i=0;i<nf;i++)
{
if(!strcmp(name,fname[i])) break;
}
if(i==nf)
{
strcpy(fname[j++],name); nf++;
}
else
printf("There is already %s\n",name);
printf("Do you want to enter another file(yes - 1 or no - 0):"); scanf("%d",&ch);
}
while(ch==1);
printf("Directory name is:%s\n",mdname); printf("Files names are:");
for(i=0;i<j;i++) printf("\n%s",fname[i]); getch();
}

OUTPUT:

Enter the directory name:sss Enter the number of files:3

Enter file name to be created:aaa


Do you want to enter another file(yes - 1 or no - 0):1 Enter file name to be created:bbb
Do you want to enter another file(yes - 1 or no - 0):1 Enter file name to be created:ccc
Do you want to enter another file(yes - 1 or no - 0):0 Directory name is:sss
Files names are:
aaa bbb ccc
17) PROGRAM FOR TWO LEVEL DIRECTORY

#include<string.h>

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


{
char dname[10],fname[10][10]; int fcnt;
}dir[10]; void main()
{
int i,ch,dcnt,k; char f[30], d[30]; dcnt=0;
while(1)
{
printf("\n\n1. Create Directory\t2. Create File\t3. Delete File"); printf("\n4. Search File\t\t5. Display\
t6. Exit\tEnter your choice -- "); scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter name of directory -- "); scanf("%s", dir[dcnt].dname); dir[dcnt].fcnt=0;
dcnt++;
printf("Directory created"); break;
case 2: printf("\nEnter name of the directory -- "); scanf("%s",d);
for(i=0;i<dcnt;i++) if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- "); scanf("%s",dir[i].fname[dir[i].fcnt]); printf("File created");
break;
}
if(i==dcnt)
printf("Directory %s not found",d); break;
case 3: printf("\nEnter name of the directory -- "); scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter name of the file -- "); scanf("%s",f); for(k=0;k<dir[i].fcnt;k++)
{

if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is deleted ",f); dir[i].fcnt--;
strcpy(dir[i].fname[k],dir[i].fname[dir[i].fcnt]); goto jmp;
}
}
printf("File %s not found",f); goto jmp;
}
}
printf("Directory %s not found",d); jmp : break;
case 4: printf("\nEnter name of the directory -- "); scanf("%s",d);
for(i=0;i<dcnt;i++)
{
if(strcmp(d,dir[i].dname)==0)
{
printf("Enter the name of the file -- "); scanf("%s",f); for(k=0;k<dir[i].fcnt;k++)
{
if(strcmp(f, dir[i].fname[k])==0)
{
printf("File %s is found ",f); goto jmp1;
}
}
printf("File %s not found",f); goto jmp1;
}
}
printf("Directory %s not found",d); jmp1: break;
case 5: if(dcnt==0) printf("\nNo Directory's "); else
{
printf("\nDirectory\tFiles"); for(i=0;i<dcnt;i++)
{
printf("\n%s\t\t",dir[i].dname); for(k=0;k<dir[i].fcnt;k++) printf("\t%s",dir[i].fname[k]);
}
}

break; default:exit(0);
}
}
}
OUTPUT:

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 1

Enter name of directory -- DIR1 Directory created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 1

Enter name of directory -- DIR2 Directory created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 2

Enter name of the directory -- DIR1 Enter name of the file -- aaa
File created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 2

Enter name of the directory -- DIR1 Enter name of the file -- bbb
File created

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 5

Directory Files DIR1


DIR2

1. Create Directory 2. Create File 3. Delete File


4. Search File 5. Display 6. Exit Enter your choice -- 6

18) PROGRAM FOR DAG

#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 void main()
{
int i,j,k,nodes=0; srand(time(NULL));
int ranks=MIN_RANKS+(rand()%(MAX_RANKS-MIN_RANKS+1)); printf("DIRECTED ACYCLIC GRAPH\
n");
for(i=1;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;
}
}

OUTPUT

DIRECTED ACYCLIC GRAPH 0->7;


1->6;
1->7;

2->7
19) PROGRAM FOR Hierarchical directory File organization technique

#include<stdio.h> #include<graphics.h> #include<string.h> struct tree_element


{
char name[20];
int x, y, ftype, lx, rx, nc, level; struct tree_element *link[5];
};
typedef struct tree_element node; void main()
{
int gd=DETECT,gm; node *root; root=NULL;
create(&root,0,"root",0,639,320); clrscr(); initgraph(&gd,&gm,"c:\tc\BGI"); display(root);
closegraph();

}
create(node **root,int lev,char *dname,int lx,int rx,int x)
{
int i, gap; if(*root==NULL)
{
(*root)=(node *)malloc(sizeof(node)); printf("Enter name of dir/file(under %s) : ",dname);
fflush(stdin);
gets((*root)->name);
printf("enter 1 for Dir/2 for file :"); scanf("%d",&(*root)->ftype); (*root)->level=lev;
(*root)->y=50+lev*50; (*root)->x=x;
(*root)->lx=lx; (*root)->rx=rx; for(i=0;i<5;i++)
(*root)->link[i]=NULL; if((*root)->ftype==1)
{
printf("No of sub directories/files(for %s):",(*root)->name); scanf("%d",&(*root)>nc); if((*root)-
>nc==0)
gap=rx-lx; else
gap=(rx-lx)/(*root)->nc; for(i=0;i<(*root)->nc;i++)
create(&((*root)>link[i]),lev+1,(*root)>name,lx+gap*i,lx+gap*i+gap, lx+gap*i+gap/2);
}
else
(*root)->nc=0;
}
}
display(node *root)
{
int i; settextstyle(2,0,4); settextjustify(1,1); setfillstyle(1,BLUE); setcolor(14);
if(root !=NULL)
{
for(i=0;i<root->nc;i++)
line(root->x,root->y,root->link[i]->x,root->link[i]->y); if(root->ftype==1)
bar3d(root->x-20,root->y-10,root->x+20,root>y+10,0,0); else
fillellipse(root->x,root->y,20,20); outtextxy(root->x,root->y,root->name);

for(i=0;i<root->nc;i++) display(root->link[i]);
}
}

OUTPUT

Enter Name of dir/file (under root): ROOT Enter 1 for Dir / 2 For File : 1
No of subdirectories / files (for ROOT) :2 Enter Name of dir/file (under ROOT): USER 1 Enter 1 for
Dir /2 for file:1
No of subdirectories /files (for USER 1): 1 Enter Name of dir/file (under USER 1):SUBDIR Enter 1 for
Dir /2 for file:1
No of subdirectories /files (for SUBDIR):
1 Enter Name of dir/file (under USER 1):JAVA Enter 1 for Dir /2 for file:1
No of subdirectories /files (for JAVA): 0 Enter Name of
dir/file (under SUBDIR):VB Enter 1 for Dir /2 for file:1
No of subdirectories /files (for VB): 0 Enter Name of dir/file (under ROOT):USER2 Enter 1 for Dir /2
for file:1
No of subdirectories /files (for USER2): 2 Enter Name of dir/file (under ROOT):A Enter 1 for Dir /2 for
file:2
Enter Name of dir/file (under USER2):SUBDIR 2 Enter 1 for Dir /2 for file:1
No of subdirectories /files (for SUBDIR 2):
2 Enter Name of dir/file (under SUBDIR2):PPL Enter 1 for Dir /2 for file:1 No of
subdire

2 Enter Name of dir/file (under PPL):B Enter 1 for Dir /2 for file:2
Enter Name of dir/file (under PPL):C Enter 1 for Dir /2 for file:2

CONTENT BEYOND THE SYLLABUS

PROGRAM TO ADD TWO NUMBERS IN SHELL SCRIPT

function add()
{
sum=$(($1 + $2)) echo "Sum = $sum"
}

a=10 b=20
#call the add function and pass the values add $a $b

OUTPUT
Sum = 30

PROGRAM TO PRINT NUMBERS USING FOR LOOP


for i in {0..10..2} do
echo "Welcome $i times" done

OUTPUT

Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times
PROGRAM TO FIND LESSER NUMBER
echo "Enter a number" read n
if [ $n -lt 100 ]; then
printf "$n is less than 100\n" fi

OUTPUT
Enter a number 87
87 is lesser than 100

You might also like