LabManual CSE32509 01 2024 02 37 12 1054599822
LabManual CSE32509 01 2024 02 37 12 1054599822
LabManual CSE32509 01 2024 02 37 12 1054599822
1
Contents
1 Experiment 1: Introduction to Linux Commands 8
1.1 Objective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2 Reference Material[1][3][2] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.1 Important Linux Commands for File and Directory Management . . . . . . . 8
1.2.2 Shell Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.2.3 Types of Shell Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.4 Linux File System Hierarchy[2][3] . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.5 Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2.6 Linux File Permission Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 Lab Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.4 Sample Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5 Evaluation Parameters and Rating Scale . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.1 Student’s Self Rating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.5.2 Teacher’s Rating Student Performance . . . . . . . . . . . . . . . . . . . . . . 12
2
3.5.1 Student’s Self Rating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.5.2 Teacher’s Rating Student Performance . . . . . . . . . . . . . . . . . . . . . . 34
3
7.3 Sample Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
7.4 Lab Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.5 Sample Viva Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
7.6 Evaluation Parameters and Rating Scale . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.6.1 Student’s Self Rating . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
7.6.2 Teacher’s Rating Student Performance . . . . . . . . . . . . . . . . . . . . . . 70
4
Expression of Gratitude
I extend my deepest gratitude to both of you for your invaluable support and guidance through-
out the creation of the CSE325: Operating Systems Laboratory manual. Your unwavering
encouragement, expertise, and mentorship have been pivotal in crafting a comprehensive resource
for our students.
Your commitment to academic excellence and dedication to our learning community have been
inspirational. Your visionary leadership and continuous support have significantly enriched our
educational experiences and have empowered us to produce this manual that will serve as a valuable
asset for our students’ education.
I am profoundly grateful for the opportunities you have provided us and the trust you have
placed in our abilities. Your impactful contributions continue to shape the School of Computer
Science at Lovely Professional University and nurture an environment of growth and learning.
Once again, thank you for your profound guidance and belief in our endeavors. Your support
has been instrumental, and I am honored to have had the privilege of working under your guidance.
5
General Guidelines for Students
• Completion of Lab Manual Exercises: The completion of lab manual exercises con-
tributes to the Continuous Assessment (CA) marks.
• Assigned System Usage: Sit according to your roll number and use the designated system
consistently throughout the semester.
• Reporting System Issues: It is the student’s responsibility to report any issues related to
the designated system to the teacher promptly.
• Use of Electronic Devices: Use electronic devices in a professional manner, adhering to
academic norms.
• System Settings: Avoid changing system settings without prior approval from the teacher.
• Assist with Technical Issues: Aid students in troubleshooting technical issues they might
encounter during the experiments.
• Evaluate and Provide Feedback: Evaluate students’ work based on predefined parameters
and provide constructive feedback to enhance their learning experience.
• Coordinate with Support Staff: Collaborate with the IT support team to swiftly resolve
technical difficulties beyond your expertise.
6
• Encourage Exploration and Understanding: Promote a deeper understanding of oper-
ating systems by encouraging students to explore beyond the prescribed experiments.
• Maintain a Positive Learning Atmosphere: Create a positive and supportive learning
environment that encourages students to engage actively in their learning process.
– ”J/E grading will be based on the student’s performance during the CAP day, marked
out of 50.”
– ”LM assessment will be out of 50, determined by the teacher’s average overall rating
from the evaluation of the previous two experiments in the lab manual. The average
overall rating will be multiplied by 5.”
• There will be total 4 continuous assessment practical (CAP) conducted during the semester
(100 marks each).
• Best 3 out of 4 will be considered in grade calculation by the end of the semester.
7
Lab Experiments
1 Experiment 1: Introduction to Linux Commands
1.1 Objective
The objective of this lab experiment is to introduce students to fundamental Linux commands
used for navigating the file system, managing files and directories, and performing basic system
operations. By the end of this experiment, students should be familiar with commonly used com-
mands such as ls, cd, mkdir, rm, cp, and mv, gaining a foundational understanding of the Linux
command-line interface.
8
1.2.3 Types of Shell Commands
• Internal Commands: These commands are built into the shell itself. They are part of the
shell’s functionalities and do not exist as separate executable files. Examples include cd, echo,
exit, alias, export, etc.
• External Commands: These commands are separate executable files located in directories
listed in the system’s PATH variable. When a user inputs an external command, the shell
searches for the command’s executable file in these directories and executes it if found.
1.2.5 Paths
Paths refer to the location or address of a file or directory in the file system.
Types of paths
(i) Absolute Path: An absolute path defines the complete location of a file or directory starting
from the root directory (/). It includes the entire directory hierarchy from the root directory
to the specific file or directory. For instance, /home/user/documents/file.txt is an absolute
9
path where the file.txt is located in the ’documents’ directory inside the ’user’ directory within
the ’home’ directory, starting from the root (/) directory.
(ii) Relative Path: A relative path defines the location of a file or directory with respect to the cur-
rent working directory. It doesn’t start from the root directory but refers to a location relative
to the current directory. For example, if the current directory is /home/user/, a file located
in the ’documents’ directory can be referenced using a relative path like documents/file.txt.
- r w x r - x r - x
| | | | | | |
| | | | | | +---- Others (permissions for users not covered by owner or group)
| | | | +---------- Group (permissions for users in the file’s group)
| | +------------------ Owner (permissions for the file or directory owner)
| +-------------------- Type of the file (e.g., - for a regular file, d for a directory)
+------------------------ Special permission bits (e.g., s, t, etc.)
Each group of permissions (Owner, Group, Others) consists of three characters representing
read (r), write (w), and execute (x) permissions. If a permission is allowed, the respective character
is displayed, and if it’s denied, a hyphen (-) is shown.
For example:
In this example: - The first character (-) indicates that it’s a regular file. - The next three
characters (rw-) represent the owner’s permissions (read and write, but not execute). - The following
three characters (r–) represent the group’s permissions (read-only). - The last three characters (r–)
represent permissions for others (read-only).
These permissions can be changed using commands like chmod in Linux to alter the read, write,
and execute permissions for the owner, group, and others.
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
10
References
[1] Greg Gagne Abraham Silberschatz, Peter B. Galvin. Operating System Concepts. Wiley, 10
edition, 2018.
[2] Sumitabha Das. Unix Concepts And Applications. Wiley, 4 edition, 2006.
[3] Richard Stones Neil Matthew. Beginning Linux Programming. Wiley, 4 edition, 2007.
11
1.5 Evaluation Parameters and Rating Scale
1.5.1 Student’s Self Rating
Evaluation Parameters Rating (Out of 10)
Understanding of Required Concepts 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
Practical Implementation 1 2 3 4 5 6 7 8 9 10
Lab-manual Readiness 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
12
Intentionally left blank for writing solutions to the provided lab exercises.
13
Intentionally left blank for writing solutions to the provided lab exercises.
14
2 Experiment 2: Basics of Shell Scripting
2.1 Objective
The primary objectives include creating simple yet functional scripts, grasping scripting syntax
elements such as variables, loops, and control structures, and executing these scripts effectively.
Moreover, this experiment will emphasize the real-world utility of shell scripting in automating
routine tasks, performing file manipulations, and simplifying system administration processes.
(i) Environment Variables: These are variables that contain information about the environment
in which the shell operates, such as user settings, system paths, or configuration preferences.
(ii) User-Defined Variables: These are variables created by users to store custom data or infor-
mation required for specific tasks or scripts.
15
2.2.5 Important Environment Variables
• PATH: Specifies directories where executable programs are located.
• HOME: Represents the current user’s home directory.
• Standard Input Redirection (<): Changes the command’s input source to a file.
• Standard Output Redirection (>): Redirects command output to a file (overwrites ex-
isting content).
command1 | command2
16
2.2.7 Shell Arithmetic using expr and bc Commands
In shell scripting, arithmetic operations can be performed using different commands:
• expr Command: Used for integer arithmetic operations within shell scripts. It evaluates
and prints the result of expressions.
Example usage:
Supported operators in expr include addition (+), subtraction (-), multiplication (*), division
(/), modulus (
• bc Command: Stands for ’Basic Calculator’ and supports floating-point arithmetic and
advanced mathematical functions.
Example usage:
bc handles floating-point arithmetic and provides functions like sine, cosine, square root, etc.,
for more complex calculations.
These commands offer basic arithmetic functionalities within shell scripts. expr is suitable
for simple integer arithmetic, while bc provides a broader range of mathematical operations and
supports floating-point numbers.
1. Basic if Statement:
if [ condition ]; then
# Commands to execute if the condition is true
fi
2. if-else Statement:
if [ condition ]; then
# Commands to execute if the condition is true
else
# Commands to execute if the condition is false
fi
17
3. if-elif-else Statement:
if [ condition1 ]; then
# Commands to execute if condition1 is true
elif [ condition2 ]; then
# Commands to execute if condition2 is true
else
# Commands to execute if both condition1 and condition2 are false
fi
4. Nested if Statements:
if [ condition1 ]; then
if [ condition2 ]; then
# Commands to execute if both condition1 and condition2 are true
fi
fi
These variations enable conditional execution of commands based on different conditions within
shell scripts, offering flexibility in controlling the flow of the script.
1. Arithmetic Operators
• +, -, *, /, %: Perform addition, subtraction, multiplication, division, and modulus respectively.
2. Relational Operators
• -eq, -ne, -gt, -lt, -ge, -le: Compare numbers (equal, not equal, greater than, less than,
greater than or equal to, less than or equal to) within test or [ ] brackets.
18
3. String Operators
• =, !=, <, >: Compare strings (equal, not equal, less than, greater than) within test or [ ]
brackets.
4. Logical Operators
• &&, ||, !: Perform logical AND, logical OR, and logical NOT operations respectively.
5. Assignment Operators
• =, +=: Assign values to variables or concatenate strings.
6. Bitwise Operators
• &, |, ^, <<, >>, ~: Perform bitwise AND, OR, XOR, left shift, right shift, and bitwise NOT
operations respectively.
Understanding and utilizing these operators enable the creation of conditions, calculations,
string manipulations, and file property checks within shell scripts, enhancing their functionality
and flexibility.
case variable in
pattern1)
# Commands to execute if variable matches pattern1
;;
pattern2)
# Commands to execute if variable matches pattern2
;;
pattern3|pattern4)
# Commands to execute if variable matches pattern3 or pattern4
;;
*)
# Default commands to execute if no pattern matches
;;
esac
19
Example:
fruit="apple"
case $fruit in
apple)
echo "It’s an apple."
;;
banana|orange)
echo "It’s a banana or an orange."
;;
*)
echo "It’s another fruit."
;;
esac
This example evaluates the variable $fruit against different patterns and executes respective
blocks based on the matching pattern.
The case structure simplifies code readability when multiple conditions need evaluation against
a single variable or expression.
1. for Loop
The for loop iterates through a list of items or values. It is suitable when you have a known set of
elements to loop through.
Syntax:
for variable in list
do
# Commands to execute for each iteration
done
Example:
for i in 1 2 3 4 5
do
echo "Iteration: $i"
done
2. while Loop
The while loop executes a block of code as long as a specified condition remains true.
Syntax:
20
while [ condition ]
do
# Commands to execute as long as the condition is true
done
Example:
count=1
while [ $count -le 5 ]
do
echo "Count: $count"
((count++))
done
3. until Loop
The until loop executes a block of code until a specified condition becomes true.
Syntax:
until [ condition ]
do
# Commands to execute until the condition becomes true
done
Example:
count=1
until [ $count -gt 5 ]
do
echo "Count: $count"
((count++))
done
4. Nested Loops
You can nest loops within each other to create more complex control structures.
Example:
for i in {1..3}
do
echo "Outer Loop Iteration: $i"
for j in A B C
do
echo " Inner Loop Iteration: $j"
done
done
These loops in shell scripting provide various ways to iterate through data, execute code repeat-
edly based on conditions, and control the flow of a script.
21
2.3 Steps to Prepare and Execute a Shell Script
1. Create the Shell Script:
• Open a text editor or an Integrated Development Environment (IDE) to write the shell script.
• Write the desired commands and save the file with a .sh extension (e.g., script.sh).
chmod +x script.sh
– Using Bash:
bash script.sh
4. Verify Output:
• After executing the script, verify the output or actions performed by the script in the terminal
or through any generated files or changes made by the script.
22
6. Exit Code Analysis (Optional):
• After script execution, check the exit code by typing:
echo $?
An exit code of 0 generally indicates success, while other codes signify different types of errors
or warnings.
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
References
[1] Greg Gagne Abraham Silberschatz, Peter B. Galvin. Operating System Concepts. Wiley, 10
edition, 2018.
[2] Sumitabha Das. Unix Concepts And Applications. Wiley, 4 edition, 2006.
[3] Richard Stones Neil Matthew. Beginning Linux Programming. Wiley, 4 edition, 2007.
23
2.4 Sample Viva Questions
Question 1: Describe how to redirect input and output in a shell script.
Question 2: How do you read user input in a shell script? Explain with an example.
Question 3: Discuss different types of operators used in shell scripting (arithmetic, comparison,
logical, etc.).
Question 4: What are variables in shell scripting? How do you declare and use them?
Question 5: What is the significance of the shebang (#!) line in a shell script?
Question 6: What are the different types of shells commonly used in Unix/Linux?
Overall Rating 1 2 3 4 5 6 7 8 9 10
Practical Implementation 1 2 3 4 5 6 7 8 9 10
Lab-manual Readiness 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
24
2.6 Instructions for the Teacher to Conduct Lab Assessment 1
• Upon finishing the initial two experiments, you are required to carry out CAP1, which is
worth 100 marks [comprising two parts: J/E (50) and LM (50)].
• The calculation for LM marks is determined by: (Average of the teacher’s overall ratings in
Experiment 1 and Experiment 2) multiplied by 5.
25
Intentionally left blank for writing solutions to the provided lab exercises.
26
Intentionally left blank for writing solutions to the provided lab exercises.
27
Intentionally left blank for writing solutions to the provided lab exercises.
28
Intentionally left blank for writing solutions to the provided lab exercises.
29
3 Experiment 3: File Manipulation Using System Calls[1][3][2]
3.1 Objective
The goal of this lab is to introduce and apply fundamental system calls like open, read, write, lseek,
and close through programming exercises, addressing practical challenges encountered in real-world
scenarios.
30
3.2.2 Sample Programs
1. Program to Create and Open a File for Reading
int main ( ) {
int f i l e D e s c r i p t o r ;
c l o s e ( f i l e D e s c r i p t o r ) ; // C l o s e t h e f i l e
return 0 ;
}
int main ( ) {
char b u f f e r [ BUFFER SIZE ] ;
// 0 i s t h e f i l e d e s c r i p t o r o f s t a n d a r d i n p u t .
s s i z e t bytesRead = r e a d ( 0 , b u f f e r , BUFFER SIZE ) ;
w r i t e ( 1 , b u f f e r , bytesRead ) ; // 1 i s t h e f i l e d e s c r i p t o r o f s t a n d a r d o u t p u t .
return 0 ;
}
int main ( ) {
char data [ ] = ” This data w i l l be appended t o t h e f i l e . \ n” ;
31
int f i l e D e s c r i p t o r ;
return 0 ;
}
int main ( ) {
char b u f f e r [ BUFFER SIZE ] ;
int readFd , writeFd ;
s s i z e t bytesRead ;
while ( ( bytesRead = r e a d ( readFd , b u f f e r , BUFFER SIZE ) ) > 0 ) {
w r i t e ( writeFd , b u f f e r , bytesRead ) ;
}
c l o s e ( readFd ) ;
c l o s e ( writeFd ) ;
return 0 ;
}
5. a C program that reads characters from the 11th to the 20th position from a file
named ”input.txt” using the lseek system call.
int main ( ) {
32
int f i l e D e s c r i p t o r ;
char b u f f e r [ BUFFER SIZE ] ;
f i l e D e s c r i p t o r = open ( ” i n p u t . t x t ” , O RDONLY) ;
l s e e k ( f i l e D e s c r i p t o r , 1 0 , SEEK SET ) ;
r e a d ( f i l e D e s c r i p t o r , b u f f e r , BUFFER SIZE − 1 ) ;
b u f f e r [ BUFFER SIZE − 1 ] = ’ \0 ’ ;
p r i n t f ( ” C h a r a c t e r s from 11 th t o 20 th p o s i t i o n : %s \n” , b u f f e r ) ;
close ( fileDescriptor );
return 0 ;
}
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
References
[1] Greg Gagne Abraham Silberschatz, Peter B. Galvin. Operating System Concepts. Wiley, 10
edition, 2018.
[2] Sumitabha Das. Unix Concepts And Applications. Wiley, 4 edition, 2006.
[3] Richard Stones Neil Matthew. Beginning Linux Programming. Wiley, 4 edition, 2007.
33
of positions (e.g., shifting each character by 3 positions in the ASCII table).
Output: Save the encrypted content to a new file named ”encrypted.txt”.
Overall Rating 1 2 3 4 5 6 7 8 9 10
Practical Implementation 1 2 3 4 5 6 7 8 9 10
Lab-manual Readiness 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
34
Intentionally left blank for writing solutions to the provided lab exercises.
35
Intentionally left blank for writing solutions to the provided lab exercises.
36
Intentionally left blank for writing solutions to the provided lab exercises.
37
Intentionally left blank for writing solutions to the provided lab exercises.
38
4 Experiment 4: Directory Manipulation Using System Calls
4.1 Objective
In this lab, we’ll explore how shell commands like mkdir (used to create directories), rmdir (used to
remove directories) and ls used to list directory contents) actually work behind the scenes. These
commands rely on special functions called system calls such as mkdir, opendir, and readdir. By
learning about these functions, you’ll be able to understand how these commands function and even
write your own code using them.
• ino t d ino: This member represents the inode number of the directory entry.
• off t d off: It stores the offset of the next readdir call within the directory stream.
39
• unsigned short int d reclen: It denotes the length of this record.
• unsigned char d type: This member identifies the type of the file. For example, DT DIR for
directories, DT REG for regular files, and others based on the file type.
• char d name[]: This member holds the name of the directory entry. It is a character array
representing the name of the file or directory.
int main ( ) {
DIR ∗ d i r ;
struct d i r e n t ∗ e n t r y ;
dir = opendir ( ” . ” ) ;
if ( dir ) {
p r i n t f ( ” Contents o f t h e d i r e c t o r y : \ n” ) ;
while ( ( e n t r y = r e a d d i r ( d i r ) ) != NULL) {
p r i n t f ( ”%s \n” , entry −>d name ) ;
}
closedir ( dir );
}
return 0 ;
}
int main ( ) {
const char ∗ dirname = ” NewDirectory ” ;
40
return 0 ;
}
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
References
[1] Greg Gagne Abraham Silberschatz, Peter B. Galvin. Operating System Concepts. Wiley, 10
edition, 2018.
[2] Sumitabha Das. Unix Concepts And Applications. Wiley, 4 edition, 2006.
[3] Richard Stones Neil Matthew. Beginning Linux Programming. Wiley, 4 edition, 2007.
41
4.6 Evaluation Parameters and Rating Scale
4.6.1 Student’s Self Rating
Evaluation Parameters Rating (Out of 10)
Understanding of Required Concepts 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
Practical Implementation 1 2 3 4 5 6 7 8 9 10
Lab-manual Readiness 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
42
Intentionally left blank for writing solutions to the provided lab exercises.
43
Intentionally left blank for writing solutions to the provided lab exercises.
44
Intentionally left blank for writing solutions to the provided lab exercises.
45
Intentionally left blank for writing solutions to the provided lab exercises.
46
5 Experiment 5: Process Management using System Calls
5.1 Objective
By the end of this experiment, students will learn about different system commands used to manage
processes. They will also gain an understanding of orphan and zombie processes.
47
system call. If the parent fails to fetch the exit status of the terminated child (due to neglect or
termination), the zombie process remains in the process table as an inactive process entry.
int main ( ) {
pid t child pid ;
// C r e a t e a c h i l d p r o c e s s
child pid = fork ( ) ;
i f ( c h i l d p i d == 0 ) {
// The c h i l d p r o c e s s code s e c t i o n
p r i n t f ( ” C h i l d p r o c e s s : PID = %d\n” , g e t p i d ( ) ) ;
} else i f ( c h i l d p i d > 0) {
// The p a r e n t p r o c e s s code s e c t i o n
p r i n t f ( ” Parent p r o c e s s : C h i l d PID = %d\n” , c h i l d p i d ) ;
} else {
// Fork f a i l e d
p r i n t f ( ” Fork f a i l e d \n” ) ;
return 1 ;
}
return 0 ;
}
int main ( ) {
pid t child pid = fork ( ) ;
i f ( c h i l d p i d == 0 ) {
// C h i l d p r o c e s s
p r i n t f ( ” C h i l d p r o c e s s : PID = %d\n” , g e t p i d ( ) ) ;
s l e e p ( 2 ) ; // S l e e p t o e n s u r e t h e p a r e n t p r o c e s s t e r m i n a t e s f i r s t
p r i n t f ( ” C h i l d p r o c e s s : My p a r e n t ’ s PID = %d\n” , g e t p p i d ( ) ) ;
} else i f ( c h i l d p i d > 0) {
48
// Parent p r o c e s s
p r i n t f ( ” Parent p r o c e s s : PID = %d\n” , g e t p i d ( ) ) ;
p r i n t f ( ” Parent p r o c e s s : Terminating . . . \ n” ) ;
} else {
p r i n t f ( ” Fork f a i l e d \n” ) ;
return 1 ;
}
return 0 ;
}
int main ( ) {
pid t child pid = fork ( ) ;
i f ( c h i l d p i d == 0 ) {
// C h i l d p r o c e s s
p r i n t f ( ” C h i l d p r o c e s s : PID = %d\n” , g e t p i d ( ) ) ;
e x i t ( 0 ) ; // C h i l d p r o c e s s e x i t s i m m e d i a t e l y
} else i f ( c h i l d p i d > 0) {
// Parent p r o c e s s
p r i n t f ( ” Parent p r o c e s s : PID = %d\n” , g e t p i d ( ) ) ;
p r i n t f ( ” Parent p r o c e s s : C h i l d PID = %d\n” , c h i l d p i d ) ;
s l e e p ( 1 0 ) ; // S l e e p t o a l l o w time f o r t h e c h i l d t o become a zombie
p r i n t f ( ” Parent p r o c e s s : Terminating . . . \ n” ) ;
} else {
p r i n t f ( ” Fork f a i l e d \n” ) ;
return 1 ;
}
return 0 ;
}
49
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
References
[1] Greg Gagne Abraham Silberschatz, Peter B. Galvin. Operating System Concepts. Wiley, 10
edition, 2018.
[2] Sumitabha Das. Unix Concepts And Applications. Wiley, 4 edition, 2006.
[3] Richard Stones Neil Matthew. Beginning Linux Programming. Wiley, 4 edition, 2007.
P1
P2 P3
P4
P5
The program should create the specified process structure using the appropriate se-
quence of ‘fork()‘ system calls. Print PID and PPID of each process.
50
5.5 Sample Viva Questions
Question 1: Explain the fork system call in process management.
Question 2: Discuss the significance of the return values of the fork system call.
Overall Rating 1 2 3 4 5 6 7 8 9 10
Practical Implementation 1 2 3 4 5 6 7 8 9 10
Lab-manual Readiness 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
51
Intentionally left blank for writing solutions to the provided lab exercises.
52
Intentionally left blank for writing solutions to the provided lab exercises.
53
Intentionally left blank for writing solutions to the provided lab exercises.
54
Intentionally left blank for writing solutions to the provided lab exercises.
55
6 Experiment 6: Creation of Multithreaded Processes using
Pthread Library
6.1 Objective
Introduce the operations on threads, which include initialization, creation, join and exit functions
of thread using pthread library.
void ∗ t h r e a d f u n c t i o n ( void ∗ a r g ) {
p r i n t f ( ” I n s i d e t h e new t h r e a d ! \ n” ) ;
return NULL;
}
int main ( ) {
pthread t thread id ;
p t h r e a d c r e a t e (& t h r e a d i d , NULL, t h r e a d f u n c t i o n , NULL ) ;
p t h r e a d j o i n ( t h r e a d i d , NULL ) ;
return 0 ;
}
56
2. A C program that creates a thread and passes a message from the main function
to the thread.
int main ( ) {
pthread t thread id ;
p t h r e a d c r e a t e (& t h r e a d i d , NULL, t h r e a d f u n c t i o n , ” H e l l o from t h e main t h r e a d ! ” ) ;
p t h r e a d j o i n ( t h r e a d i d , NULL ) ;
return 0 ;
}
3. A C program where a thread returns a value to the main function using pointers.
void ∗ t h r e a d f u n c t i o n ( void ∗ a r g ) {
int ∗ r e t u r n V a l u e = m a l l o c ( s i z e o f ( int ) ) ;
∗ r e t u r n V a l u e = 1 4 3 ; // S e t t h e r e t u r n v a l u e
pthread exit ( returnValue ) ;
}
int main ( ) {
p t h r e a d t t h r e a d s [NUM THREADS ] ;
int ∗ t h r e a d r e t u r n ;
f r e e ( t h r e a d r e t u r n ) ; // Free a l l o c a t e d memory f o r r e t u r n v a l u e
return 0 ;
}
57
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
References
[1] Greg Gagne Abraham Silberschatz, Peter B. Galvin. Operating System Concepts. Wiley, 10
edition, 2018.
[2] Sumitabha Das. Unix Concepts And Applications. Wiley, 4 edition, 2006.
[3] Richard Stones Neil Matthew. Beginning Linux Programming. Wiley, 4 edition, 2007.
6.4 Lab Exercises: [Attempt any 3 within the designated lab hours]
Exercise 1: Develop a program using pthread to concatenate multiple strings passed to the thread
function.
Exercise 2: Create a pthread program to find the length of strings passed to the thread function.
Exercise 3: Implement a program that performs statistical operations (calculating average, max-
imum, and minimum) for a set of numbers. Utilize three threads, where each thread
performs its respective operation.
Exercise 4: Write a multithreaded program where a globally passed array of integers is divided
into two smaller lists and given as input to two threads. Each thread sorts their half
of the list and then passes the sorted lists to a third thread, which merges and sorts
them. The final sorted list is printed by the parent thread.
Exercise 5: Create a program using pthread create to generate multiple threads. Each thread
should display its unique ID and execution sequence.
Exercise 6: Create a threaded application that demonstrates graceful thread termination using
pthread exit for resource cleanup compared to abrupt termination via pthread cancel.
58
Question 4: Explain the differences between a thread and a process in terms of memory sharing
and execution context.
Question 5: Give two instances where a multi-threaded process offers benefits compared to a
single-threaded solution.
Overall Rating 1 2 3 4 5 6 7 8 9 10
Practical Implementation 1 2 3 4 5 6 7 8 9 10
Lab-manual Readiness 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
59
.
60
Intentionally left blank for writing solutions to the provided lab exercises.
61
Intentionally left blank for writing solutions to the provided lab exercises.
62
Intentionally left blank for writing solutions to the provided lab exercises.
63
Intentionally left blank for writing solutions to the provided lab exercises.
64
7 Experiment 7: Process Synchronization using Semaphore/-
Mutex
7.1 Objective
The objective of this lab experiment is to acquaint students with the concept of process synchro-
nization in concurrent programming using semaphore or mutex mechanisms.
7.2.3 Semaphore
Definition A semaphore is an abstract data type used for process synchronization in
concurrent programming. It controls access to shared resources among mul-
tiple processes or threads by maintaining a counter that can be incremented
or decremented.
Functionality Semaphores manage access to shared resources, prevent race conditions, and
ensure synchronization. They offer operations like initialization (sem init),
waiting (sem wait), signaling (sem post), and destruction (sem destroy).
Types Common types include Binary Semaphores (with values 0 and 1) and Count-
ing Semaphores (with values greater than 1).
65
7.2.4 Mutex
Definition A mutex (Mutual Exclusion) is a synchronization primitive used in multi-
threaded programming to control access to shared resources. It allows only
one thread at a time to access the resource, preventing concurrent access.
Functionality Mutexes ensure mutual exclusion, preventing race conditions and maintain-
ing data integrity. Operations include initialization (pthread mutex init),
locking (pthread mutex lock), unlocking (pthread mutex unlock), and
destruction (pthread mutex destroy).
Types Mutexes can be recursive (allows the same thread to lock it multiple times)
or non-recursive (deadlocks if the same thread tries to lock it multiple times).
int s h a r e d v a r i a b l e = 0 ;
void ∗ i n c r e m e n t v a r i a b l e ( void ∗ t h r e a d i d ) {
f o r ( int i = 0 ; i < MAX COUNT; i ++) {
s h a r e d v a r i a b l e ++;
}
p t h r e a d e x i t (NULL ) ;
}
int main ( ) {
p t h r e a d t t h r e a d s [NUM THREADS ] ;
66
f o r ( int i = 0 ; i < NUM THREADS; i ++) {
p t h r e a d c r e a t e (& t h r e a d s [ i ] , NULL, i n c r e m e n t v a r i a b l e , ( void ∗ ) i ) ;
}
p r i n t f ( ” Value o f s h a r e d v a r i a b l e a f t e r r a c e c o n d i t i o n : %d\n” , s h a r e d v a r i a b l e ) ;
return 0 ;
}
int s h a r e d v a r i a b l e = 0 ;
sem t semaphore ;
void ∗ i n c r e m e n t v a r i a b l e ( void ∗ t h r e a d i d ) {
f o r ( int i = 0 ; i < MAX COUNT; i ++) {
sem wait (&semaphore ) ;
s h a r e d v a r i a b l e ++;
s e m p o s t (&semaphore ) ;
}
p t h r e a d e x i t (NULL ) ;
}
int main ( ) {
p t h r e a d t t h r e a d s [NUM THREADS ] ;
s e m i n i t (&semaphore , 0 , 1 ) ; // I n i t i a l i z i n g semaphore w i t h v a l u e 1
67
s e m d e s t r o y (&semaphore ) ; // D e s t r o y i n g semaphore
p r i n t f ( ” Value o f s h a r e d v a r i a b l e a f t e r s y n c h r o n i z a t i o n : %d\n” , s h a r e d v a r i a b l e ) ;
return 0 ;
}
int s h a r e d v a r i a b l e = 0 ;
p t h r e a d m u t e x t mutex = PTHREAD MUTEX INITIALIZER ;
void ∗ i n c r e m e n t v a r i a b l e ( void ∗ t h r e a d i d ) {
f o r ( int i = 0 ; i < MAX COUNT; i ++) {
p t h r e a d m u t e x l o c k (&mutex ) ;
s h a r e d v a r i a b l e ++;
p t h r e a d m u t e x u n l o c k (&mutex ) ;
}
p t h r e a d e x i t (NULL ) ;
}
int main ( ) {
p t h r e a d t t h r e a d s [NUM THREADS ] ;
p t h r e a d m u t e x i n i t (&mutex , NULL ) ; // I n i t i a l i z i n g mutex
p t h r e a d m u t e x d e s t r o y (&mutex ) ; // D e s t r o y i n g mutex
p r i n t f ( ” Value o f s h a r e d v a r i a b l e a f t e r s y n c h r o n i z a t i o n : %d\n” , s h a r e d v a r i a b l e ) ;
return 0 ;
}
68
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
References
[1] Greg Gagne Abraham Silberschatz, Peter B. Galvin. Operating System Concepts. Wiley, 10
edition, 2018.
[2] Sumitabha Das. Unix Concepts And Applications. Wiley, 4 edition, 2006.
[3] Richard Stones Neil Matthew. Beginning Linux Programming. Wiley, 4 edition, 2007.
69
Question 4: Explain the functions pthread mutex init, pthread mutex lock, and pthread mutex unlock
in mutex usage.
Question 5: Discuss scenarios where mutexes are preferred over other synchronization mecha-
nisms.
Overall Rating 1 2 3 4 5 6 7 8 9 10
Practical Implementation 1 2 3 4 5 6 7 8 9 10
Lab-manual Readiness 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
70
Intentionally left blank for writing solutions to the provided lab exercises.
71
Intentionally left blank for writing solutions to the provided lab exercises.
72
Intentionally left blank for writing solutions to the provided lab exercises.
73
Intentionally left blank for writing solutions to the provided lab exercises.
74
8 Experiment 8: Inter Process Communication (IPC)
8.1 Objective
The aim of this laboratory is to introduce the Interprocess communication (IPC) mechanism of
operating system to allow the processes to communicate with each other.
8.2.2 Pipes
In C programming, pipes are a form of interprocess communication (IPC) that allows communi-
cation between two processes, with one process writing data into the pipe and the other process
reading from it. Pipes are one-way communication channels that can be either anonymous or
named.
75
• filedes[0] refers to the read end of the pipe.
• filedes[1] refers to the write end of the pipe.
Sample Program
int main ( ) {
int p i p e f d [ 2 ] ;
char data [ 1 0 0 ] ;
i f ( pipe ( p i p e f d ) < 0) {
p r i n f t ( ” pipe creation f a i l e d ” ) ;
return 1 ;
}
p i d t pid = f o r k ( ) ;
i f ( pid < 0) {
p r i n t f ( ” f o r k f a i l e d \n” ) ;
return 1 ;
}
i f ( p i d > 0 ) { // Parent p r o c e s s
// Write t o p i p e
c l o s e ( p i p e f d [ 0 ] ) ; // C l o s e t h e r e a d i n g end
char message [ ] = ” H e l l o , C h i l d P r o c e s s ! ” ;
w r i t e ( p i p e f d [ 1 ] , message , s i z e o f ( message ) ) ;
c l o s e ( p i p e f d [ 1 ] ) ; // C l o s e t h e w r i t i n g end
} e l s e { // C h i l d p r o c e s s
// Read from p i p e
c l o s e ( p i p e f d [ 1 ] ) ; // C l o s e t h e w r i t i n g end
r e a d ( p i p e f d [ 0 ] , data , s i z e o f ( data ) ) ;
p r i n t f ( ” R e c e i v e d message i n c h i l d : %s \n” , data ) ;
c l o s e ( p i p e f d [ 0 ] ) ; // C l o s e t h e r e a d i n g end
}
return 0 ;
}
76
• Syntax: int mkfifo(const char *pathname, mode t mode);
• pathname is the path and name of the named pipe.
• mode specifies the permissions for the named pipe.
Sample Code[3][1]
int main ( ) {
char ∗ f i f o = ” /tmp/ m y f i f o ” ; // Path t o t h e named p i p e
m k f i f o ( f i f o , 0 6 6 6 ) ; // C r e a t i n g a named p i p e
int f d ;
char data [ 1 0 0 ] ;
return 0 ;
}
1. Allocation: A process allocates a shared memory segment using the shmget() system call.
This call either creates a new shared memory segment or accesses an existing one based on a
provided key and size.
2. Attachment: After allocation, the process attaches the shared memory segment to its ad-
dress space using shmat(). This attaches the segment to a virtual address in the process’s
memory, allowing it to read from and write to the shared memory.
77
3. Usage: Processes that share this segment can read from and write to it, treating it like
any other memory region. Synchronization mechanisms such as semaphores or mutexes are
typically used to control access and prevent race conditions.
4. Detachment: When the process finishes using the shared memory, it detaches the segment
using shmdt(). This detaches the shared memory segment from the process’s address space.
5. Control Operations: The shmctl() function allows for control operations on the shared
memory segment, such as removing or modifying it.
8.2.6 Sample program to demonstrate shared memory segment creation and data
addition
int main ( ) {
void ∗shm ;
char buf [ 1 0 0 ] ;
int shmid ;
// C r e a t i n g a s h a r e d memory segment
shmid = shmget ( ( k e y t ) 1 2 3 , SHM SIZE , 0666 | IPC CREAT ) ;
i f ( shmid == −1) {
p r i n t f ( ” shmget E r r o r \n” ) ;
e x i t (EXIT FAILURE ) ;
}
78
p r i n t f ( ”The Key v a l u e o f s h a r e d memory i s %d\n” , shmid ) ;
// A t t a c h i n g t h e p r o c e s s t o t h e s h a r e d memory segment
shm = shmat ( shmid , NULL, 0 ) ;
i f ( shm == ( void ∗) −1) {
p r i n t f ( ” shmat E r r o r \n” ) ;
e x i t (EXIT FAILURE ) ;
}
p r i n t f ( ” P r o c e s s a t t a c h e d t o t h e a d d r e s s o f %p\n” , shm ) ;
// D e t a c h i n g s h a r e d memory
i f ( shmdt ( shm ) == −1) {
p r i n t f ( ”shmdt E r r o r \n” ) ;
e x i t (EXIT FAILURE ) ;
}
return 0 ;
}
79
#include <s t d i o . h>
#include < s t d l i b . h>
#include <s t r i n g . h>
#include <s y s / t y p e s . h>
#include <s y s / i p c . h>
#include <s y s /msg . h>
#include <e r r n o . h>
struct m s g b u f f e r {
long msg type ;
char m s g t e x t [ MAX MSG SIZE ] ;
};
int main ( ) {
k e y t key ;
int msg id ;
struct m s g b u f f e r message ;
// Manually g e n e r a t e a key w i t h o u t u s i n g f t o k
i f ( ( key = 0 x12345678 ) == −1) {
p r i n t f ( ” key E r r o r \n” ) ;
e x i t (EXIT FAILURE ) ;
}
80
e x i t (EXIT FAILURE ) ;
}
return 0 ;
}
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
References
[1] Greg Gagne Abraham Silberschatz, Peter B. Galvin. Operating System Concepts. Wiley, 10
edition, 2018.
[2] Sumitabha Das. Unix Concepts And Applications. Wiley, 4 edition, 2006.
[3] Richard Stones Neil Matthew. Beginning Linux Programming. Wiley, 4 edition, 2007.
81
Exercise 2: Demonstrate the usage of Shared Memory for IPC.
Tasks:
• Create a shared memory segment and attach it to multiple processes.
• Develop a producer-consumer model, where one process writes data into the
shared memory, and another process reads from it.
Exercise 3: Explore IPC using Message Passing techniques.
Tasks:
• Design two processes where one process sends a signal to another process.
• Develop signal handlers in both processes to manage incoming signals and per-
form specific actions based on the received signal.
Overall Rating 1 2 3 4 5 6 7 8 9 10
82
Student’s Signature: Date:
Practical Implementation 1 2 3 4 5 6 7 8 9 10
Lab-manual Readiness 1 2 3 4 5 6 7 8 9 10
Overall Rating 1 2 3 4 5 6 7 8 9 10
• The calculation for LM marks is determined by: (Average of the teacher’s overall ratings in
Experiment 7 and Experiment 8) multiplied by 5.
83
Intentionally left blank for writing solutions to the provided lab exercises.
84
Intentionally left blank for writing solutions to the provided lab exercises.
85
Intentionally left blank for writing solutions to the provided lab exercises.
86
Intentionally left blank for writing solutions to the provided lab exercises.
87