Operating Systems Lab Manual
Operating Systems Lab Manual
WEEK 1
AIM : Practice File handling utilities, Process utilities, Disk utilities, Networking commands, Filters, Text
processing utilities and Backup utilities.
To Append data into the file: To append data into the same file use append operator >> to write into thefile,
else the file will be overwritten (i.e., all of its contents will be erased).
cat >> file1.txt
To display a file: This command displays the data in the file.cat file1.txt
The above cat command will concatenate the two files (file1.txt and file2.txt) and it will display the output in
the screen. Some times the output may not fit the monitor screen. In such situation you canprint those files in
a new file or display the file using less command.
cat file1.txt file2.txt | less
This rm command recursively removes the contents of all subdirectories of the tmp directory,prompting you
regarding the removal of each file, and then removes the tmpdirectory itself.
To remove more files at once: rm command removes file1.txt and file2.txt files at the same time.rm file1.txt
file2.txt
Ex:
cd ..
This will change to the parent-directory from the current working directory/sub-directory.
cd ~
This command will move to the user's home directory which is "/home/username".
cp COMMAND:
cp command copy files from one location to another. If the destination is an existing file, then
the file is overwritten; if the destination is an existing directory, the file is copied into the directory (the
directory is not overwritten).
Copy two files:
cp file1.txt file2.txt
The above cp command copies the content of file1.txt to file2.txt
ls COMMAND:
ls command lists the files and directories under current working directory. Display root directory contents:
ls /
lists the contents of root directory.
Display hidden files and directories:
ls -a
lists all entries including hidden files and directories.
Display inode information:
ls –i
ln COMMAND:
ln command is used to create link to a file (or) directory. It helps to provide soft link for desired files.
Inode will be different for source and destination.
ln -s file1.txt file2.txt
Creates a symbolic link to 'file1.txt' with the name of 'file2.txt'. Here inode for 'file1.txt' and 'file2.txt'will be
different.
mkdir command: Use this command to create one or more new directories.
Include one or more instances of the “<DIRECTORY” variable (separating each with a whitespace), and set
each to the complete path to the new directory to be created.
rmdir command:
mv command:
diff command:
comm command:
wc command:
PROCESS UTILITIES:
ps Command:
ps command is used to report the process status. ps is the short name for Process Status.
1. ps: List the current running processes.
Output:
PID TTY TIME CMD
2540 pts/1 00:00:00 bash
2. ps –f : Displays full information about currently running processes.
Output:
UID PID PPID C STIME TTY TIME CMD
nirmala 2540 2536 0 15:31 pts/1 00:00:00 bash
3. kill COMMAND: kill command is used to kill the background process.
Step by Step process:
• Open a process music player or any file.xmms
press ctrl+z to stop the process.
• To know group id or job id of the background task.jobs -l
It will list the background jobs with its job id as,
• xmms 3956
• kmail 3467
To kill a job or process.
• kill 3956
kill command kills or terminates the background process xmms.
Disk utilities:
du (abbreviated from disk usage) is a standard Unix program used to estimate file spaceusage—space used
under a particular directory or files on a file system.
$du kt.txt pt.txt /* the first column displayed the file's disk usage */
8 kt.txt
4 pt.txt
Using -h option: As mentioned above, -h option is used to produce the output in humanreadable format.
$du -h kt.txt pt.txt
8.0K kt.txt4.0K pt.txt
/*now the output is in human readable format i.e in Kilobytes */
Using -a option
$du -a kartik
8 kartik/kt.txt 4 kartik/thakral.png
4 kartik/pt.txt 4 kartik/thakral
4 24 kartik
kartik/pranjal.
png
/*so with -a option used all the files (under directory kartik) disk usage info is displayed alongwith
the thakral sub-directory */
C:>telnet amrood.comTrying...
Connected to amrood.com.Escape character is '^]'. login: amrood
amrood's Password:
******************************************************WELCOME TO AMROOD.COM *
*****************************************************
$ logoutLINUX PROGRAMMING LAB021-2022
Connection closed.C:>
Finger:
The finger command displays information about users on a given host. The host can be either
local or remote.
Check all the logged-in users on the local machine −
$ finger
Login Name Tty Idle Login Time Office
amrood pts/0 Jun 25 08:03 (62.61.164.115)
Check all the logged-in users on the remote machine –
$ finger @avtar.com
Login Name Tty Idle Login Time Office amrood pts/0 Jun 25 08:03 (62.61.164.115)
Get the information about a specific user available on the remote machine −
$ finger [email protected]
Ifconfig: Ifconfig is used to configure the network interfaces.
FILTERS
more COMMAND:
more command is used to display text in the terminal screen. It allows only backwardmovement.
1. more -c index.txt
Clears the screen before printing the file .
2. more -3 index.txt
Prints first three lines of the given file. Press Enter to display the file line by line.
head COMMAND:
head command is used to display the first ten lines of a file, and also specifies how many linesto
display.
1. head index.php
This command prints the first 10 lines of 'index.php'.
2. head -5 index.php
The head command displays the first 5 lines of 'index.php'.
3. head -c 5 index.php
The above command displays the first 5 characters of 'index.php'.
tail COMMAND:
tail command is used to display the last or bottom part of the file. By default it displays last10
lines of a file.
1. tail index.php
It displays the last 10 lines of 'index.php'.
2. tail -2 index.php
It displays the last 2 lines of 'index.php'.
3. tail -n 5 index.php
Grep (Global Regular Expression Searching for a pattern), fgrep and egrep
$ grep ―s ales director‖ emp1 emp2
BACKUP UTILITIES
Linux backup and restore can be done using backup commands tar, cpio, dump and restore.
Backup Restore using tar command
tar: tape archive is used for single or multiple files backup and restore on/from a tape or file.
$tar cvf /dev/rmt/0 *
Options: c -> create ; v -> Verbose ; f->file or archive device ; * -> all files and directories .
$tar cvf /home/backup *
Create a tar called backup in home directory, from all file and directories s in the currentdirectory.
Viewing a tar backup on a tape or file
$tar tvf /dev/rmt/0 ## view files backed up on a tape device.
$tar tvf /home/backup ## view files backed up inside the backup
Note: t option is used to see the table of content in a tar file.
Extracting tar backup from the tape
$tar xvf /home/backup ## extract / restore files in to current directory.
Note : x option is used to extract the files from tar file. Restoration will go to present directoryor
original backup path depending on relative or absolute path names used for backup.
Backup restore using cpio command
Using cpio command to backup all the files in current directory to tape.
find . -depth -print | cpio -ovcB > /dev/rmt/0
cpio expects a list of files and find command provides the list, cpio has to put these file onsome
destination and a > sign redirect these files to tape. This can be a file as well .
WEEK 2
AIM : Write a shell script that receives any number of file names as arguments checks if every
argument supplied is a file or directory and reports accordingly. Whenever the argument is a file it
reports no of lines present in it.
ALGORITHM:
step 1: if arguments are less than 1 print Enter at least one input file name and goto step 9
Step 2: selects list a file from list of arguments provided in command line
Step 3: check for whether it is directory if yes print is directory and goto step 9
step 4: check for whether it is a regular file if yes goto step 5 else goto step 8
Step 5: print given name is regular file
step 6: print No of lines in file
step 7: goto step
step 8: print not a file or adirectory
step 9: stop
for x in $*
do
if [ -f $x ]
then
echo " $x is a file "
echo " no of lines in the file are "
wc -l $x
elif [ -d $x ]
then
echo " $x is a directory "
else
echo " enter valid filename or directory name "
fi
done
OUTPUT
WEEK 3
AIM : To write a C program to simulate the following non-preemptive CPU scheduling algorithms to
find turnaround time and waiting time for the following.
a) FCFS b) SJF c) Round Robin d) Priority
DESCRIPTION
Assume all the processes arrive at the same time.
PROGRAM
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);
getch();
}
NPUT
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
OUTPUT
PROCESS BURST TIME WAITING TIME RNAROUND TIME
P0 24 0 24
P1 3 24 27
P2 3 27 30
for(k=i+1;k<n;k++)
if(bt[i]>bt[k])
{
temp=bt[i]; bt[i]=bt[k]; bt[k]=temp;
}
np=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);getch();
}
INPUT
Enter the number of processes -- 4
Enter Burst Time for Process 0 -- 6
Enter Burst Time for Process 1 -- 8
Enter Burst Time for Process 2 -- 7
Enter Burst Time for Process 3 -- 3
OUTPUT
PROCESS BURST TIME WAITING TIME URNAROUND TIME
P3 3 0 3
P0 6 3 9
P2 7 9 16
P1 8 16 24
Average Waiting Time -- 7.000000
Average Turnaround Time -- 13.000000
for(i=0;i<n;i++)
{
printf("\nEnter Burst Time for process %d -- ", i+1); 11
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]);
getch();
}
INPUT
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
OUTPUT
The Average Turnaround time is – 15.666667
The Average Waiting time is -- 5.666667
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=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];
INPUT
Enter the number of processes --5
Enter the Burst Time & Priority of Process 0 --- 10
Enter the Burst Time & Priority of Process 1 --- 1
Enter the Burst Time & Priority of Process 2 --- 2
Enter the Burst Time & Priority of Process 3 --- 1
Enter the Burst Time & Priority of Process 4 --- 5
OUTPUT
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
WEEK 4
AIM: To Simulate Bankers Algorithm for Dead Lock Avoidance; Simulate Bankers Algorithm for Dead
Lock Prevention.
DESCRIPTION
In a multiprogramming environment, several processes may compete for a finite number of
resources. A processrequests resources; if the resources are not available at that time, the process
enters a waiting state. Sometimes, a waiting process is never again able to change state, because
the resources it has requested are held by other waiting processes. This situation is called a
deadlock. Deadlock avoidance is one of the techniques for handling deadlocks. This approach
requires that the operating system be given in advance additional information concerning which
resources a process will request and use during its lifetime. With this additional knowledge, it can
decide for each request whether or not the process should wait. To decide whether the current
request can be satisfied or must be delayed, the system must consider the resources currently
available, the resources currently allocated to each process, and the future requests and releases of
each process. Banker’s algorithm is a deadlock avoidance algorithm that is applicable to a system
with multiple instances of each resource type.
#include<stdio.h>
#include<conio.h>
int max[100][100];
int alloc[100][100];
int need[100][100];
int avail[100];
int n,r;
void input();
void show();
void cal();
int main()
{
int i,j;
printf("********** Banker's Algo ************\n");
input();
show();
cal();
getch();
return 0;
}
void input()
{
int i,j;
printf("Enter the no of Processes\t");
scanf("%d",&n);
printf("Enter the no of resources instances\t");
scanf("%d",&r);
printf("Enter the Max Matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&max[i][j]);
}
}
printf("Enter the Allocation Matrix\n");
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
scanf("%d",&alloc[i][j]);
}
}
printf("Enter the available Resources\n");
for(j=0;j<r;j++)
{
scanf("%d",&avail[j]);
}
}
void show()
{
int i,j;
printf("Process\t Allocation\t Max\t Available\t");
for(i=0;i<n;i++)
{
printf("\nP%d\t ",i+1);
for(j=0;j<r;j++)
{
printf("%d ",alloc[i][j]);
}
printf("\t");
for(j=0;j<r;j++)
{
printf("%d ",max[i][j]);
}
printf("\t");
if(i==0)
{
for(j=0;j<r;j++)
printf("%d ",avail[j]);
}
}
}
void cal()
{
int finish[100],temp,need[100][100],flag=1,k,c1=0;
int safe[100];
int i,j;
for(i=0;i<n;i++)
{
finish[i]=0;
}
//find need matrix
for(i=0;i<n;i++)
{
for(j=0;j<r;j++)
{
need[i][j]=max[i][j]-alloc[i][j];
}
}
printf("\n");
while(flag)
{
flag=0;
for(i=0;i<n;i++)
{
int c=0;
for(j=0;j<r;j++)
{
if((finish[i]==0)&&(need[i][j]<=avail[j]))
{
c++;
if(c==r)
{
for(k=0;k<r;k++)
{
avail[k]+=alloc[i][j];
finish[i]=1;
flag=1;
}
printf("P%d->",i);
if(finish[i]==1)
{
i=n;
}
}
}
}
}
}
for(i=0;i<n;i++)
{
if(finish[i]==1)
{
c1++;
}
else
{
printf("P%d->",i);
}
}
if(c1==n)
{
printf("\n The system is in safe state");
}
else
{
printf("\n Process are in dead lock");
printf("\n System is in unsafe state");
}
}
OUTPUT:
Enter the no of processes 5
Enter the no of resources instances 3
Enter the max matrix
75 3
32 2
90 2
22 2
43 3
Enter the allocation matrix
01 0
20 0
30 2
21 1
00 2
Enter available resources 3 2 2
P1->p3->p4->p2->p0->
The system is in safe state.
DESCRIPTION
The dining-philosophers problem is considered a classic synchronization problem because it is an
example of a large class of concurrency-control problems. It is a simple representation of the need
to allocate several resources among several processes in a deadlock-free and starvation-free
manner. Consider five philosophers who spend their lives thinking and eating. The philosophers
share a circular table surrounded by five chairs, eachbelonging to one philosopher. In the center of
the table is a bowl of rice, and the table is laid with five single chopsticks. When a philosopher
thinks, she does not interact with her colleagues. From time to time, a philosopher gets hungry
and tries to pick up the two chopsticks that are closest to her (the chopsticks that are between her
and her left and right neighbors). A philosopher may pick up only one chopstick at a time.
Obviously, she cam1ot pick up a chopstick that is already in the hand of a neighbor. When a
hungry philosopher has both her chopsticks at the same time, she eats without releasing her
chopsticks. When she is finished eating, she puts down both of her chopsticks and starts thinking
again. The dining-philosophers problem may lead to a deadlock situation and hence some rules
have to be framed to avoid the occurrence of deadlock.
PROGRAM
int tph, philname[20], status[20], howhung, hu[20], cho;
main()
{
int i; clrscr();
printf("\n\nDINING PHILOSOPHER PROBLEM");
printf("\nEnter the total no. of philosophers: ");
scanf("%d",&tph);
for(i=0;i<tph;i++)
{
philname[i] = (i+1);
status[i]=1;
}
printf("How many are hungry :
scanf("%d", &howhung);
if(howhung==tph)
{
printf("\nAll are hungry..\nDead lock stage will occur");
printf("\nExiting..");
}
else
{
for(i=0;i<howhung;i++)
{
INPUT
DINING PHILOSOPHER PROBLEM
Enter the total no. of philosophers: 5How many are hungry : 3
Enter philosopher 1 position: 2
Enter philosopher 2 position: 4
Enter philosopher 3 position: 5
OUTPUT
1. One can eat at a time 2.Two can eat at a time3.ExitEnter your choice: 1
combination 2
P 3 and P 0 are granted to eatP 5 is waiting
combination 3
P 5 and P 0 are granted to eatP 3 is waiting
1.One can eat at a time 2.Two can eat at a time 3.ExitEnter your choice: 3
DESCRIPTION
Producer-consumer problem, is a common paradigm for cooperating processes. A producer
process produces information that is consumed by a consumer process. One solution to the
producer-consumer problem uses shared memory. To allow producer and consumer processes
to run concurrently, there must be available a buffer of items that can be filled by the producer
and emptied by the consumer. This buffer will reside in a region of memory that is shared by the
producer and consumer processes. A producer can produce one item while the consumer is
consuming another item. The producer and consumer must be synchronized, so that the
consumer does not try to consume an item that has not yet been produced.
PROGRAM
#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
{
scanf(“%d”, &produce);
buffer[in] = produce;
in = (in+1)%bufsize;
}
Break;
case 2: if(in == out)
printf(“\nBuffer is Empty”);
Else
{
consume = buffer[out];
printf(“\nThe consumed value is %d”, consume);out = (out+1)%bufsize;
}
Break;
} } }
OUTPUT
1. Produce 2. Consume 3. ExitEnter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. ExitEnter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. ExitEnter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. ExitEnter your choice: 3
OUTPUT
2. Produce 2. Consume 3. ExitEnter your choice: 2
Buffer is Empty
1. Produce 2. Consume 3. ExitEnter your choice: 1
Enter the value: 100
1. Produce 2. Consume 3. ExitEnter your choice: 2
The consumed value is 100
1. Produce 2. Consume 3. ExitEnter your choice: 3
WEEK 6
if (pid == 0)
{ /* child */
signal(SIGHUP, sighup);
signal(SIGINT, sigint);
signal(SIGQUIT, sigquit);
for (;;)
; /* loop for ever */
}
else /* parent */
{ /* pid hold id of child */
printf("\nPARENT: sending SIGHUP\n\n");
kill(pid, SIGHUP);
}
}
// sighup() function definition
void sighup()
{
signal(SIGHUP, sighup); /* reset signal */
printf("CHILD: I have received a SIGHUP\n");
}
raise( ):
Program file name: raise.c#include <stdio.h> #include <stdlib.h> #include <signal.h>
return 0;
}
OUTPUT:
Registering the signal handlerRaising a SIGUSR1 signal Received a SIGUSR1 signal
void timestamp()
{
time_t t;
time(&t);
printf("the time is %s", ctime(&t));
}
main()
{
struct sigaction sigact;
sigemptyset(&sigact.sa_mask);
sigact.sa_flags = 0;
sigact.sa_handler = catcher;
sigaction(SIGALRM, &sigact, NULL);
alarm(10);
printf("before pause... ");timestamp();
pause();
printf("after pause... ");timestamp();
}
OUTPUT:
before pause... the time is Fri Jun 16 09:42:29 2001inside catcher...
int main(void)
{
abort();
printf("\"abort() called prior to printf()\"\n");
return 0;
}
AIM:- To write a C program that illustrate communication between two process usingunnamed pipes
Program file name: unnamed_pipe.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
void server(int,int);
void client(int,int);
int main()
{
int p1[2],p2[2],pid;
pipe(p1);
pipe(p2);
pid=fork();
if(pid==0)
{
close(p1[1]);
close(p2[0]);
server(p1[0],p2[1]);
return 0;
}
close(p1[0]);
close(p2[1]);
client(p1[1],p2[0]);
wait();
return 0;
}
WEEK 7
AIM :a) To Write a program that illustrates communication between two process using named pipes or FIFO.
Algorithm:
Create two processes, one is fifoserver_twoway and another one is fifoclient_twoway.
Programs:
/* Filename: fifoserver_twoway.c */
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
char end[10];
int to_end;
int read_bytes;
/* Filename: fifoclient_twoway.c */
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
while (1)
{
printf("Enter string: ");
fgets(readbuf, sizeof(readbuf), stdin);
stringlen = strlen(readbuf);
readbuf[stringlen - 1] = '\0';
end_process = strcmp(readbuf, end_str);
AIM : b) Write a C program that receives a message from message queue and display them.
ALGORITHM:
Step 1:Start
Step 2:Declare a message queue
typedef struct msgbuf
{
long mtype;
char mtext[MSGSZ];
}
message_buf;
Mtype =0 Retrieve the next message on the queue, regardless of its mtype.
PositiveGet the next message with an mtype equal to the specifiedmsgtyp.
Negative Retrieve the first message on the queue whose mtype fieldis less than or
equal to the absolute value of the msgtyp argument.
Usually mtype is set to1
mtext is the data this will be added to the queue.
Step 3:Get the message queue id for the "name" 1234, which was created by the serverkey = 1234
Step 4 : if ((msqid = msgget(key, 0666< 0) Then print error
The msgget() function shall return the message queue identifier associated with the argument key.
Step 5: Receive message from message queue by using msgrcv function
int msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg);
#include < sys/msg.h>
(msgrcv(msqid, &rbuf, MSGSZ, 1, 0)msqid: message queue id
&sbuf: pointer to user defined structure MSGSZ: message sizeMessage type: 1
Message flag:The msgflg argument is a bit mask constructed by ORing together zero or more of the
following flags: IPC_NOWAIT or MSG_EXCEPT or MSG_NOERROR
Step 6:if msgrcv <0 return error
Step 7:otherwise print message sent is sbuf.mextStep 8:stop
Program:
//IPC_msgq_send.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
main()
{
int msqid;
int msgflg = IPC_CREAT | 0666;
key_t key;
struct msgbuf sbuf;
size_t buflen;
key = 1234;
if ((msqid = msgget(key, msgflg )) < 0) //Getthe message queue ID for the given key
die("msgget");
//Message Typesbuf.mtype = 1;
buflen = strlen(sbuf.mtext) + 1 ;
else
printf("Message Sent\n");
exit(0);
}
Program:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 128
printf("%s\n", rcvbuffer.mtext);exit(0);
}
WEEK 8
AIM: To write a C program that illustrates two processes communicating using Shared memory.
Algorithm:-
the shared memory identifier associated with key Theargument key is equal to IPC_PRIVATE. so that
step1.Start
step 2.Include header files required for the program are#include <sys/types.h>
#include <sys/ipc.h>#include <sys/shm.h>#include <unistd.h> #include <string.h> #include <errno.h>
step 3.Declare the variable which are required aspid_t pid
int *shared /* pointer to the shm */int shmid
step 4.Use shmget function to create shared memory#include <sys/shm.h>
int shmget(key_t key, size_t size, int shmflg)
The shmget() function shall return the operating system selects the next availablekey for a newly created
shared block of memory.Size represents size of shared memory block Shmflg shared memory permissions
which are represented by octalinteger shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666);
print the shared memory idstep 5.if fork()==0 Then
begin
shared = shmat(shmid, (void *) 0, 0)
print the shared variable(shared) *shared=2print *shared sleep(2)
print *shared
end
step 6.else shared = shmat(shmid, (void *) 0, 0) print the shared variable(shared) print *shared
begin sleep(1) *shared=30
printf("Parent value=%d\n", *shared);sleep(5)
shmctl(shmid, IPC_RMID, 0)
end
step 7.stop.
Sha.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
OUTPUT:
$cc shared_mem.c
$ ./a.out
Shared Memory ID=65537
Child pointer 3086680064
Child value=1
Shared Memory ID=65537
Parent pointer 3086680064
Parent value=1
Parent value=42
Child value=42
WEEK 9
AIM: To Simulate all page replacement algorithms a) FIFO b) LRU c) OPTIMAL
DESCRIPTION
Page replacement is basic to demand paging. It completes the separation between logical memory
and physical memory. With this mechanism, an enormous virtual memory can be provided for
programmers on a smaller physical memory. There are many different page-replacement algorithms.
Every operating system probably has its own replacement scheme. A FIFO replacement algorithm
associates with each page the time when that page was brought into memory. When a page must be
replaced, the oldest page is chosen. If the recent past is used as an approximation of the near future,
then the page that has not been used for the longest period of time can be replaced. This approach is
the Least Recently Used (LRU) algorithm. LRU replacement associates with each page the time of that
page's last use. When a page must be replaced, LRU chooses the page that has not been used for the
longest period of time. Least frequently used (LFU) page-replacement algorithm requires that the
page with the smallest count be replaced. The reason for this selection is that an actively used page
should have a large reference count.
PROGRAM
INPUT
Enter the length of reference string – 20
Enter the reference string -- 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1
Enter no. of frames -- 3
OUTPUT
The Page Replacement Process is –
-1 -1 PF No. 1
0 -1 PF No. 2
0 1 PF No. 3
0 1 PF No. 4
0 1
3 1 PF No. 5
3 0 PF No. 6
3 0 PF No. 7
2 0 PF No. 8
2 3 PF No. 9
2 3 PF No. 10
2 3
2 3
1 3 PF No. 11
1 2 PF No. 12
1 2
1 2
1 2 PF No. 13
0 2 PF No. 14
0 1 PF No. 15
DESCRIPTION
Optimal page replacement algorithm has the lowest page-fault rate of all algorithms and will
never suffer from Belady's anomaly. The basic idea is to replace the page that will not be used
for the longest period of time. Use of this page-replacement algorithm guarantees the lowest
possible page fault rate for a fixed number of frames. Unfortunately, the optimal page-
replacement algorithm is difficult to implement, because it requires future knowledge of the
reference string.
PROGRAM
#include<stdio.h>int n;
main()
{
int seq[30],fr[5],pos[5],find,flag,max,i,j,m,k,t,s;int count=1,pf=0,p=0;
float pfr;clrscr();
printf("Enter maximum limit of the sequence: ");scanf("%d",&max);
printf("\nEnter the sequence: ");for(i=0;i<max;i++)
scanf("%d",&seq[i]); printf("\nEnter no. of frames: ");scanf("%d",&n);
fr[0]=seq[0];pf++;
printf("%d\t",fr[0]);i=1;
while(count<n)
{
flag=1;p++;
for(j=0;j<i;j++)
{
if(seq[i]==seq[j])flag=0;
}
if(flag!=0)
{
fr[count]=seq[i]; printf("%d\t",fr[count]);count++;
pf++;
} i++;
}
{
max=a[i];
k=i;
}
}
return k;
}
}
INPUT
Enter number of page references -- 10
Enter the reference string -- 12 3 4 52 5 25 1 4 3
Enter the available no. of frames --- 3
OUTPUT
The Page Replacement Process is –
1 -1 -1 PF No. 1
1 2 -1 PF No. 2
1 2 3 PF No. 3
4 2 3 PF No. 4
5 2 3 PF No. 5
5 2 3
5 2 3
5 2 1 PF No. 6
5 2 4 PF No. 7
5 2 3 PF No. 8
AIM: To write a C program that takes one or more file/directory names as command line input and reports
following information A) File Type B) Number Of Links C) Time of last Access D) Read, write and execute
permissions
Algorithm:
Step 1:start
Step 2:Declare struct stat a
Step 3:read arguments at command line
Step 4: set the status of the argument using stat(argv[i],&a);
Step 5:Check whether the given file is Directory file by using S_ISDIR(a.st_mode)if it is a directory file
print Directory file
Else
print is Regular fileStep6: print number of links
Step 7:print last time access
Step 8:Print Read,write and execute permissionsStep 9:stop
#include<stdio.h>
#include<sys/stat.h>
#include<time.h>
int main(int argc,char *argv[])
{
int i,j; struct stat a;
for (i=1;i<argc;i++)
{
printf("%s : ",argv[i]);
stat(argv[i],&a);
if(S_ISDIR(a.st_mode))
{
printf("is a Directory file\n");
}
else
{
printf("is Regular file\n");
}
printf("******File Properties********\n");
printf("Inode Number:%d\n",a.st_ino);
printf("UID:%o\n",a.st_uid);
printf("GID:%o\n",a.st_gid);
printf("No of Links:%d\n",a.st_nlink);
printf("Last Access time:%s",asctime(localtime(&a.st_atime)));
AIM: a)To Implement in c language the following UNIX commands using system calls i) cat ii) ls iii) Scanning
Directories (Ex: opendir(),readdir(),etc.)
DESCRIPTION:
(i) cat COMMAND: cat linux command concatenates files and print it on the standard
output. SYNTAX:
cat [OPTIONS] [FILE]...
OPTIONS:
-A Show all.
-b Omits line numbers for blank space in the output.
-e A $ character will be printed at the end of each line prior to a new line.
-E Displays a $ (dollar sign) at the end of each line.
-n Line numbers for all the output lines.
-s If the output has multiple empty lines it replaces it with one empty line.
-T Displays the tab characters in the output.
-v Non-printing characters (with the exception of tabs, new-lines & form-feeds) are printed visibly.
3. To display a file:
$cat file1.txt
This command displays the data in the file.
Algorithm:
Step 1:Start
Step 2:read arguments from keyboard at command line
Step 3:if no of arguments are less than two print ENTER CORRECT ARGUMENTSElse goto step 4
Step4:read the date from specified file and write it to destination fileStep 5 :stop
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
int main(int argc,char *argv[])
{
int fd,n;
char buff[512];
if(argc!=2)
printf("ENTER CORRECT ARGUMENTS :");
if((fd=open(argv[1],4))<0)
{
printf("ERROR");
return 0;
}
while(n=read(fd,buff,sizeof(buff))>0)write(1,buff,n);
}
(ii) ls
Description:
ls command is used to list the files present in a directory
Algorithm:
Step 1. Start.
Step 2. open directory using opendir( ) system call. Step 3. read the directory using readdir( ) system call.Step 4.
print dp.name and dp.inode .
Step 5. repeat above step until end of directory.Step 6: Stop.
Program name: 5b.c
#include<stdio.h> #include<dirent.h> void quit(char*,int);
int main(int argc,char **argv )
{
DIR *dirop;
struct dirent *dired;if(argc!=2)
{
printf("Invalid number of arguments\n");
#include <stdio.h>
#include <dirent.h>
int main(void)
{
struct dirent *de; // Pointer for directory entry
closedir(dr);
return 0;
OUTPUT
Output:
[root@dba ~]# cc -o 8
8a.c[root@dba ~]# ./8
the child process ID is
4485 the parent process
ID is 4484
WEEK 12
AIM: Write a C program to simulate disk scheduling algorithms. a) FCFS b) SCAN c) C-SCAN
DESCRIPTION
One of the responsibilities of the operating system is to use the hardware efficiently. For the disk
drives, meeting this responsibility entails having fast access time and large disk bandwidth. Both the
access time and the bandwidth can be improved by managing the order in which disk I/O requests are
serviced which is called as diskscheduling. The simplest form of disk scheduling is, of course, the first-
come, first-served (FCFS) algorithm. This algorithm is intrinsically fair, but it generally does not provide
the fastest service. In the SCAN algorithm, the diskarm starts at one end, and moves towards the other
end, servicing requests as it reaches each cylinder, until it gets to the other end of the disk. At the
other end, the direction of head movement is reversed, and servicing continues. The head
continuously scans back and forth across the disk. C-SCAN is a variant of SCAN designed to provide a
more uniform wait time. Like SCAN, C-SCAN moves the head from one end of the disk to the other,
servicing requests along the way. When the head reaches the other end, however, it immediately
returns to the beginning of the disk without servicing any requests on the return trip
PROGRAM
INPUT
Enter no.of tracks:9
Enter track position:55 58 60 70 18 90 150 160 184
OUTPUT
Tracks Difference between
traversed tracks
55 45
58 3
60 2
70 10
18 52
90 72
150 60
160 10
184 24
#include<conio.h>
#include<stdio.h>
int main()
{
int i,j,sum=0,n;
int d[20];
int disk; //loc of head
int temp,max;
int dloc; //loc of disk in arra
clrscr();
printf("enter number of loc ion\t");
scanf("%d",&n);
printf("enter position of he d\t");
scanf("%d",&disk);
printf("enter elements of disk
queue\n");
for(i=0;i<n;i++)
{
scanf("%d",&d[i]);
}
d[n]=disk;
n=n+1;
for(i=0;i<n;i++) // sorting d isk
locations
{
for(j=i;j<n;j++)
{
if(d[i]>d[j])
{
temp=d[i];
d[i]=d[j];
d[j]=temp;
}
max=d[n];
for(i=0;i<n;i++) // to find loc of disc in array
{
if(disk==d[i]) { dloc=i; break; }
}
for(i=dloc;i>=0;i--)
{
printf("%d -->",d[i]);
}
printf("0 -->");
for(i=dloc+1;i<n;i++)
{
printf("%d-->",d[i]);
}
sum=disk+max;
printf("\nmovement of total cylinders %d",sum);
getch();
return 0;
}
OUTPUT:
Enter no of location 8
Enter position of head 53
Enter elements of disk queue
98
183
37
122
14
124
65
67
53->37->14->0->65->67->98->122->124->183->
Movement of total cylinders 236.
#include<stdio.h>
int main()
{
int queue[20],n,head,i,j,k,seek=0,max,diff,temp,queue1[20],queue2[20],
temp1=0,temp2=0;
float avg;
printf("Enter the max range of disk\n");
scanf("%d",&max);
printf("Enter the initial head position\n");
scanf("%d",&head);
printf("Enter the size of queue request\n");
scanf("%d",&n);
printf("Enter the queue of disk positions to be read\n");
for(i=1;i<=n;i++)
{
scanf("%d",&temp);
if(temp>=head)
{
queue1[temp1]=temp;
temp1++;
}
else
{
queue2[temp2]=temp;
temp2++;
}
}
for(i=0;i<temp1-1;i++)
{
for(j=i+1;j<temp1;j++)
{
if(queue1[i]>queue1[j])
{
temp=queue1[i];
queue1[i]=queue1[j];
queue1[j]=temp;
}
}
}
for(i=0;i<temp2-1;i++)
{
for(j=i+1;j<temp2;j++)
{
if(queue2[i]>queue2[j])
{
temp=queue2[i];
queue2[i]=queue2[j];
queue2[j]=temp;
}
}
}
for(i=1,j=0;j<temp1;i++,j++)
queue[i]=queue1[j];
queue[i]=max;
queue[i+1]=0;
for(i=temp1+3,j=0;j<temp2;i++,j++)
queue[i]=queue2[j];
queue[0]=head;
for(j=0;j<=n+1;j++)
{
diff=abs(queue[j+1]-queue[j]);
seek+=diff;
printf("Disk head moves from %d to %d with
seek %d\n",queue[j],queue[j+1],diff);
}
printf("Total seek time is %d\n",seek);
avg=seek/(float)n;
printf("Average seek time is %f\n",avg);
return 0;
}
OUTPUT