Os Lab Manual 1 To 8
Os Lab Manual 1 To 8
LAB MANUAL
SCHOOL OF COMPUTING
SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
(Deemed University u/s 3 of UGC Act 1956)
Kattankulathur, Chengalpattu District, 603 202.
© SRMIST
21CSC202J-Operating Systems
LIST OF EXPERIMENTS
Exp. CO
Title of the experiment
No. Mapped
a. Operating system Installation
1 CO-1
b. Booting Process of Linux
a. Basic Linux Commands CO-1
2
b. Filters and Admin Commands CO-5
5 Multithreading CO-2
© SRMIST
21CSC202J-Operating Systems
Aim:
Procedure:
© SRMIST
21CSC202J-Operating Systems
Aim:
To understand the booting process of LINUX
Procedure:
Press the power button on your system, and after few moments you see the Linux login prompt. From the
time you press the power button until the Linux login prompt appears, the following sequence occurs. The
following are the 6 high level stages of a typical Linux boot process.
Step 1.BIOS
BIOS stands for Basic Input/Output System
Performs some system integrity checks
Searches, loads, and executes the boot loader program.
It looks for boot loader in floppy, CD-ROMs, or hard drive. You can press a key (typically F12 or
F2, but it depends on your system) during the BIOS startup to change the boot sequence.
Once the boot loader program is detected and loaded into the memory, BIOS gives the control to
it.
So, in simple terms BIOS loads and executes the MBR boot loader.
Step 2. MBR
MBR stands for Master Boot Record.
It is located in the 1st sector of the bootable disk. Typically /dev/hda, or /dev/sda
MBR is less than 512 bytes in size. This has three components 1) primary boot loader info in 1st
446 bytes 2) partition table info in next 64 bytes 3) mbr validation check in last 2 bytes.
© SRMIST
21CSC202J-Operating Systems
Step 3. GRUB
GRUB stands for Grand Unified Bootloader.
If you have multiple kernel images installed on your system, you can choose which one to be
executed.
GRUB displays a splash screen, waits for few seconds, if you don’t enter anything, it loads the
default kernel image as specified in the grub configuration file.
GRUB has the knowledge of the filesystem (the older Linux loader LILO didn’t understand
filesystem).
Grub configuration file is /boot/grub/grub.conf (/etc/grub.conf is a link to this). The following is
sample grub.conf of CentOS.
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/boot/grub/splash.xpm.gz
hiddenmenu
title CentOS(2.6.18-194.el5PAE)
root(hd0,0)
kernel/boot/vmlinuz-2.6.18-194.el5PAE ro root=LABEL=/
initrd /boot/initrd-2.6.18-194.el5PAE.img
As you notice from the above info, it contains kernel and initrd image.
So, in simple terms GRUB just loads and executes Kernel and initrd images.
Step 4. Kernel
Mounts the root file system as specified in the “root=” in grub.conf
Kernel executes the /sbin/init program
Since init was the 1st program to be executed by Linux Kernel, it has the process id (PID) of 1.
Do a ‘ps -ef | grep init’ and check the pid.
initrd stands for Initial RAM Disk.
initrd is used by kernel as temporary root file system until kernel is booted and the real root file
system is mounted. It also contains necessary drivers compiled inside, which helps it to access the
hard drive partitions, and other hardware.
Step 5. Init
Looks at the /etc/inittab file to decide the Linux run level.
Following are the available run levels
o 0 – halt
o 1 – Single user mode
o 2 – Multiuser, without NFS
o 3 – Full multiuser mode
o 4 – unused
o 5 – X11
o 6 – reboot
Init identifies the default initlevel from /etc/inittab and uses that to load all appropriate program.
Execute ‘grep initdefault /etc/inittab’ on your system to identify the default run level
© SRMIST
21CSC202J-Operating Systems
If you want to get into trouble, you can set the default run level to 0 or 6. Since you know what 0
and 6 means, probably you might not do that.
Typically you would set the default run level to either 3 or 5.
Login Process
1. Users enter their username and password
2. The operating system confirms your name and password.
3. A "shell" is created for you based on your entry in the "/etc/passwd" file
4. You are "placed" in your "home"directory.
1. Start-up information is read from the file named "/etc/profile". This file is known as the system
login file. When every user logs in, they read the information in this file.
2. Additional information is read from the file named ".profile" that is located in your "home"
directory. This file is known as your personal login file.
© SRMIST
21CSC202J-Operating Systems
Aim:
To execute basic linux commands
Procedure:
a) Basics
1. echo SRM ➔ to display the string SRM
2. clear ➔ to clear the screen
3. date ➔ to display the current date and time
4. cal 2003 ➔ to display the calendar for the year 2003
5. cal 6 2003 ➔ to display the calendar for the June-2003
6. passwd ➔ to change password
© SRMIST
21CSC202J-Operating Systems
e) I/O Redirection
Input redirection
wc –l < ex1 ➔ To find the number of lines of the file ‘ex1’
Output redirection
who > f2 ➔ the output of ‘who’ will be redirected to file f2
cat >> f1 ➔ to append more into the file f1
f) Piping
Syntax :
Command1 | command2
Example.
cat f1 | more list the contents of file f1 screen by screen
head –6 f1 |tail –2 prints the 5th & 6th lines of the file f1.
g) Environment variables
1. echo $HOME ➔ display the path of the home directory
2. echo $PS1 ➔ display the prompt string $
3. echo $PS2 ➔ display the second prompt string ( > symbol by
default )
4. echo $LOGNAME ➔ login name
5. echo $PATH ➔ list of pathname where the OS searches for an
executable file
h) File Permission
-- chmod command is used to change the access permission of a file.
© SRMIST
21CSC202J-Operating Systems
Method-1:
Syntax :
u : user, g : group, o : others, + : Add permission - : Remove the permission r : read, w : write,
x :execute, a : all permissions
Example:
chmod ug+rw f1
Adding ‘read & write’ permissions of file f1 to both user and group members.
Method-2
Syntax :
Example:
chmod 754 f1
Aim:
To execute filters and admin commands.
© SRMIST
21CSC202J-Operating Systems
Procedure:
A. FILTERS
1. cut
Used to cut characters or fileds from a file/input
Syntax :
Example:
cut –c 5 file.txt
By default, tab is the filed separator(delimiter). If the fileds of the files are separated by any other
character, we need to specify explicitly by –d option
2. grep
Used to search one or more files for a particular pattern.
Syntax :
3. sort
Used to sort the file in order
Syntax :
sort filename
© SRMIST
21CSC202J-Operating Systems
4. uniq
Displays unique lines of a sorted file
Syntax :
uniq filename
5. diff
Used to differentiate two files
Syntax :
diff f1 f2
compare two files f1 & f2 and prints all the lines that are differed between f1 & f2.
Questions:
Q1. Write a command to cut 5 to 8 characters of the file f1.
$
Q2. Write a command to display user-id of all the users in your system.
$
Q3. Write a command to check whether the user judith is available in your system or not. (use grep)
$
Q4. Write a command to display the lines of the file f1 starts with SRM.
$
© SRMIST
21CSC202J-Operating Systems
Q6. Write a command to display the unique lines of the sorted file f21. Also display the number of
occurrences of each line.
$
Q7. Write a command to display the lines that are common to the files f1 and f2.
$
INSTALLING SOFTWARE
3. Install a package/software
© SRMIST
21CSC202J-Operating Systems
5. Reinstall a package
sudo apt-get install <package-name> --reinstall
MANAGING USERS
Managing users is a critical aspect of server management.
In Ubuntu, the root user is disabled for safety.
Root access can be completed by using the sudo command by a user who is in the “admin” group.
When you create a user during installation, that user is added automatically to the admin group.
6. Add a user
sudo adduser username
7. Disable a user
sudo passwd -l username
8. Enable a user
sudo passwd -u username
9. Delete a user
sudo userdel –r username
© SRMIST
21CSC202J-Operating Systems
If you do not want to run the commands in terminal to manage users and groups, then you can
install a GUI add-on .
sudo apt install gnome-system-tools
Q11. Create a user ‘elias’. Login to the newly created user and exit.
$
Q12. Disable the user ‘elias’, try to login and enable again.
$
Aim:
To execute shell programs in linux environment
Procedure:
© SRMIST
21CSC202J-Operating Systems
Important Hints
No space before and after the assignment operator Ex. sum=0
Single quote ignores all special characters. Dollar sign, Back quote and Back slash are not
ignored inside Double quote. Back quote is used as command substitution. Back slash is used to
remove the special meaning of a character.
Arithmetic expression can be written as follows : i=$((i+1) or i=$(expr$i + 1)
Command line arguments are referred inside the programme as $1, $2, ..and so on
$* represents all arguments, $# specifies the number of arguments
read statement is used to get input from input device. Ex. read a b
Synatax-01:
if [ condition ]
then
#commands to execute if condition is true
fi
Example:
if [ $age -ge 18 ]
then
echo "You are eligible to vote."
fi
Syntax-02:
if [ condition ]
then
# commands if condition is true
else
# commands if condition is false
fi
Example:
if [ $num -eq 0 ]
© SRMIST
21CSC202J-Operating Systems
then
echo "Zero"
else
echo "Non-zero"
fi
Syntax-03:
if [ condition1 ]
then
# commands for condition1
elif [ condition2 ]
then
# commands for condition2
else
# commands if no conditions are true
fi
Example:
if [ $marks -ge 90 ]
then
echo "Grade A"
elif [ $marks -ge 75 ]
then
echo "Grade B"
else
echo "Grade C"
fi
case expression in
pattern1)
# commands to execute if expression matches pattern1
;;
pattern2)
# commands to execute if expression matches pattern2
;;
*)
# default commands (if no pattern matches)
;;
esac
Example:
case $num in
1)
© SRMIST
21CSC202J-Operating Systems
Example:
for color in red green blue
do
echo "Color is $color"
done
while [ condition ]
do
# commands to execute while condition is true
done
Example:
count=1
while [ $count -le 5 ]
do
echo "Count is $count"
count=$((count + 1))
done
© SRMIST
21CSC202J-Operating Systems
Q1. Given the following values, num=10, x=*, y=`date` a="Hello, 'he said'”. Execute and write the
output of the following commands:
echo num
echo $num
echo $x
echo ‘$x’
echo “$x”
echo $y
echo $(date)
echo $a
echo \$num
echo \$$num
Output :
Q3. Write a program to check whether the file has execute permission or not. If not, add the
permission.
© SRMIST
21CSC202J-Operating Systems
Q4. Write a shell script to list only the name of sub directories in the present working directory
Q5. Write a program to check all the files in the present working directory for a pattern (passed
through command line) and display the name of the file followed by a message stating that the
pattern is available or not available.
Aim:
To create a process using fork() and understand the usage of getpid(), getppid(), wait() functions
Procedure:
Compilation of C Program
Step 1 : Open the terminal and edit your program and save with extension “.c”
Example: nano test.c
© SRMIST
21CSC202J-Operating Systems
Virtual fork
vfork() is similar to fork but both processes shares the same address space.
#include <stdio.h>
#include<unistd.h>
int main()
{
int a=5,b=10,pid;
printf("Before fork a=%d b=%d \n",a,b);
pid=fork();
if(pid==0)
{
a=a+1; b=b+1;
printf("In child a=%d b=%d \n",a,b);
}
else
{
sleep(1);
a=a-1; b=b-1;
printf("In Parent a=%d b=%d \n",a,b);
}
return 0;
}
Output:
Q2. Rewrite the program in Q1 using vfork() and write the output
© SRMIST
21CSC202J-Operating Systems
Output:
#include <stdio.h>
#include<unistd.h>
int main()
{
int pid,n,oddsum=0,evensum=0;
printf("Enter the value of n :”);
scanf(“%d”,&n);
pid=fork();
// Complete the program
return 0;
}
© SRMIST
21CSC202J-Operating Systems
Sample Output :
Enter the value of n 10
Sum of odd numbers 25
Sum of even numbers : 30
Q5. How many child processes are created for the following code? Hint : Check with small values of
‘n’.
#include <stdio.h>
#include<unistd.h>
int main()
{
for (i=0; i<n; i++)
fork();
return 0;
}
Output:
Q6. Write a program to print the Child process ID and Parent process ID in both Child and Parent
processes
#include <stdio.h>
#include<unistd.h>
int main()
{
return 0;
}
Sample Output:
In Child Process
Parent Process ID : 18
Child Process ID : 20
In Parent Process
Parent Process ID : 18
Child Process ID : 20
© SRMIST
21CSC202J-Operating Systems
Q7. How many child processes are created for the following code?
#include <stdio.h>
#include<unistd.h>
int main()
{
fork();
fork()&&fork()||fork();
fork();
printf(“Yes ”);
return 0;
}
Output :
Aim:
To write a C program to demonstrate various thread related concepts.
Procedure:
int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void
*arg);
Parameters:
thread: pointer to an unsigned integer value that returns the thread id of the thread created.
attr: pointer to a structure that is used to define thread attributes like detached state, scheduling
policy, stack address, etc. Set to NULL for default thread attributes.
© SRMIST
21CSC202J-Operating Systems
start_routine: pointer to a subroutine that is executed by the thread. The return type and parameter
type of the subroutine must be of type void *. The function has a single attribute but if multiple
values need to be passed to the function, a struct must be used.
arg: pointer to void that contains the arguments to the function defined in the earlier argument
B. Terminate a thread
Parameters:
Retval: the pointer to an integer that stores the return status of the thread terminated.
Parameter:
th: thread id of the thread for which the current thread waits.
thread_return: pointer to the location where the exit status of the thread mentioned in th is stored.
pthread_t pthread_self(void);
It compares whether two threads are the same or not. If the two threads are equal, the function returns a
non-zero value otherwise zero.
Parameters:
t1: the thread id of the first thread
t2: the thread id of the second thread
Q1. Create 3 threads, first one to find the sum of odd numbers; second one to find the sum of even
numbers; third one to find the sum of natural numbers; This program also displays the list of odd/even
numbers.
Complete the code snippet wherever applicable in the below program highlighted in red colour
font.
© SRMIST
21CSC202J-Operating Systems
© SRMIST
21CSC202J-Operating Systems
Output:
Result:
Thus, the program has been executed successfully by creating three threads.
Aim:
To demonstrate Mutual Exclusion-Semaphore and Reader Writer Solution
Description:
Semaphore: Semaphore is used to implement process synchronization. This is to protect critical region
shared among multiples processes.
© SRMIST
21CSC202J-Operating Systems
key ➔ semaphore id
nsems ➔ no. of semaphores in the semaphore array
semflg ➔ IPC_CREATE|0664 : to create a new semaphore
IPC_EXCL|IPC_CREAT|0664 : to create new semaphore and the call fails if the semaphore
already exists
Step 3: To perform operations on the semaphore sets viz., allocating resources, waiting for the resources
or freeing the resources, define the following functions
struct sembuf
{
unsigned short sem_num; /* Semaphore set num */
short sem_op; /* Semaphore operation */
short sem_flg; /*Operation flags, IPC_NOWAIT, SEM_UNDO */
};
Q1. Execute and write the output of the following program for mutual exclusion using System V
semaphore
#include<sys/ipc.h>
#include<sys/sem.h>
int main()
{
int pid,semid,val;
struct sembuf sop;
semid=semget((key_t)6,1,IPC_CREAT|0666);
pid=fork();
sop.sem_num=0;
sop.sem_op=0;
sop.sem_flg=0;
if (pid!=0)
{
© SRMIST
21CSC202J-Operating Systems
sleep(1);
printf("The Parent waits for WAIT signal\n");
semop(semid,&sop,1);
printf("The Parent WAKED UP & doing her job\n");
sleep(10);
printf("Parent Over\n");
}
else
{
printf("The Child sets WAIT signal & doing her job\n");
semctl(semid,0,SETVAL,1);
sleep(10);
printf("The Child sets WAKE signal & finished her job\n");
semctl(semid,0,SETVAL,0);
printf("Child Over\n");
}
return 0;
}
Output :
2. POSIX Semaphore
The POSIX system in Linux presents its own built-in semaphore library. To use it, we have to include
semaphore.h and compile the code by linking with -lpthread - lrt
© SRMIST
21CSC202J-Operating Systems
Q2. Program creates two threads: one to increment the value of a shared variable and second to
decrement the value of the shared variable. Both the threads make use of semaphore variable so
that only one of the threads is executing in its critical section. Execute and write the output.
#include<pthread.h>
#include<stdio.h>
#include<semaphore.h>
#include<unistd.h>
void *fun1();
void *fun2();
int shared=1; //shared variable
sem_t s; //semaphore variable
int main()
{
sem_init(&s,0,1); //initialize semaphore variable - 1st argument is
//address of variable, 2nd is number of processes sharing semaphore,
//3rd argument is the initial value of semaphore variable
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, fun1, NULL);
sleep(1);
pthread_create(&thread2, NULL, fun2, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2,NULL);
printf("Final value of shared is %d\n",shared); //prints the last
//updated value of shared variable
}
void *fun1()
{
int x;
sem_wait(&s); //executes wait operation on s
x=shared;//thread1 reads value of shared variable
printf("Thread1 reads the value as %d\n",x);
x++; //thread1 increments its value
printf("Local updation by Thread1: %d\n",x);
sleep(1); //thread1 is preempted by thread 2
shared=x; //thread one updates the value of shared variable
printf("Value of shared variable updated by Thread1 is: %d\n",shared);
sem_post(&s);
}
void *fun2()
{
int y;
sem_wait(&s);
y=shared;//thread2 reads value of shared variable
printf("Thread2 reads the value as %d\n",y);
y--; //thread2 increments its value
printf("Local updation by Thread2: %d\n",y);
© SRMIST
21CSC202J-Operating Systems
The final value of the variable shared will be 1. When any one of the threads executes the wait operation
the value of “s” becomes zero. Hence the other thread (even if it preempts the running thread) is not able
to successfully execute the wait operation on “s“. Thus, not able to read the inconsistent value of the
shared variable. This ensures that only one of the threads is running in its critical section at any given
time.
Output:
In a reader-writer problem, multiple readers can read data from a shared resource, while only one writer
can write data to the resource.
Q3: The challenge is to ensure that the readers do not read data while the writer is writing, and the
writer does not write data while the readers are reading. For example, consider a scenario where a
database is being accessed by multiple users. The users can read data from the database, but only
one user can write data to the database at a time. The challenge is to ensure that the users do not
read data while the database is being written to, and the writer does not write data while the users
are reading.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
/*
This program provides a possible solution for first readers writers problem using mutex and semaphore.
It has used 10 readers and 5 producers to demonstrate the solution.
*/
sem_t wrt;
pthread_mutex_t mutex;
© SRMIST
21CSC202J-Operating Systems
int cnt = 1;
int numreader = 0;
void *writer(void *wno)
{
sem_wait(&wrt);
cnt = cnt*2;
printf("Writer %d modified cnt to %d\n",(*((int *)wno)),cnt);
sem_post(&wrt);
}
void *reader(void *rno)
{
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
numreader++;
if(numreader == 1)
{
sem_wait(&wrt); // If this id the first reader, then it will block the writer
}
pthread_mutex_unlock(&mutex);
// Reading Section
printf("Reader %d: read cnt as %d\n",*((int *)rno),cnt);
// Reader acquire the lock before modifying numreader
pthread_mutex_lock(&mutex);
}
int main()
{
pthread_t read[10],write[5];
pthread_mutex_init(&mutex, NULL);
sem_init(&wrt,0,1);
int a[10] = {1,2,3,4,5,6,7,8,9,10}; //Just used for numbering the producer and consumer
for(int i = 0; i < 10; i++)
{
pthread_create(&read[i], NULL, (void *)reader, (void *)&a[i]);
}
for(int i = 0; i < 5; i++)
{
pthread_create(&write[i], NULL, (void *)writer, (void *)&a[i]);
}
for(int i = 0; i < 10; i++)
{
pthread_join(read[i], NULL);
}
for(int i = 0; i < 5; i++)
{
pthread_join(write[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&wrt);
return 0;
}
© SRMIST
21CSC202J-Operating Systems
Output:
AIM:
To write C programs to simulate solutions to Dining Philosophers Problem.
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.
o The philosophers share a circular table surrounded by five chairs, each belonging to one
philosopher.
o In the center of the table is a bowl of rice, and the table is laid with five single chopsticks.
o When a philosopher thinks, she does not interact with her colleagues.
o 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 neighbours).
© SRMIST
21CSC202J-Operating Systems
o A philosopher may pick up only one chopstick at a time. Obviously, she cannot pick up a
chopstick that is already in the hand of a neighbour.
o When a hungry philosopher has both her chopsticks at the same time, she eats without
releasing her chopsticks.
o 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.
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
sem_t room;
sem_t chopstick[5];
void * philosopher(void * num)
{
//Write coding for Main Philosopher thread
}
void eat(int phil)
{
printf("\nPhilosopher %d is eating",phil);
}
int main()
{
int i,a[5]; pthread_t tid[5];
sem_init(&room,0,4);
for(i=0;i<5;i++)
sem_init(&chopstick[i],0,1);
for(i=0;i<5;i++)
{
a[i]=i;
pthread_create(&tid[i],NULL,philosopher,(void *)&a[i]);
}
for(i=0;i<5;i++)
pthread_join(tid[i],NULL);
}
© SRMIST
21CSC202J-Operating Systems
Output:
Aim:
To demonstrate the FCFS and SJF CPU scheduling algorithms
Description:
© SRMIST
21CSC202J-Operating Systems
Algorithm:
Step 1: Input the processes along with their burst time (bt).
Step 2: Find waiting time (wt) for all processes.
Step 3: As first process that comes need not to wait so waiting time for process 1 will be 0 i.e. wt[0] = 0.
Step 4: Find waiting time for all other processes i.e. for process i -> wt[i] = bt[i-1] + wt[i-1]
Step 5: Find turnaround time = waiting_time + burst_time for all processes.
Step 6: Find average waiting time = total_waiting_time / no_of_processes
Step 7: Similarly, find average turnaround time = total_turn_around_time / no_of_processes.
Output : Process-wise burst-time, waiting-time and turnaround-time. Also display Average-waiting time
and Average-turnaround-time
Description:
To calculate the average waiting time in the shortest job first algorithm the sorting of the process based on
their burst time in ascending order then calculate the waiting time of each process as the sum of the
bursting times of all the process previous or before to that process.
Algorithm:
Step 1: Start the process
Step 2: Accept the number of processes in the ready Queue
Step 3: For each process in the ready Q, assign the process id and accept the CPU burst time
Step 4: Start the Ready Q according the shortest Burst time by sorting according to lowest to highest burst
time.
Step 5: Set the waiting time of the first process as ‗0‘ and its turnaround time as its burst time.
Step 6: Sort the processes names based on their Burt time
Step 7: For each process in the ready queue, calculate
© SRMIST
21CSC202J-Operating Systems
© SRMIST