CSE325 OS Laboratory Manual
CSE325 OS Laboratory Manual
Prepared By
1|P a g e
List of Experiments:
2 Shell Programming 7
6 Creation of Multithreaded 23
Processes using Pthread Library
2|P a g e
General Guidelines for the students
1. The teacher will check students’ lab manual regularly, sign the manual and ensure the
progressive learning of the students.
2. The teacher should create practical components by following the path on UMS:
UMS Navigation >> Learning Management System (LMS) >> Practical Components.
3. Create two components (1. J/E: Job Execution, 2. LM: Lab Manual Completion)
of 50-50 marks each.
4. There will be total 4 continuous assessment practical (CAP) conducted during the
semester (100 marks each).
5. Best 3 out of 4 will be considered in grade calculation by the end of the semester.
3|P a g e
Experient 1 – Introduction to Linux Commands
Aim
To study important Shell commands to perform various operations. Students will also
do a comparative study of Linux and Windows commands.
Learning Objective
Students will learn and practice different Shell commands to work on the Linux shell prompt.
They will gain the ability to perform a wide range of tasks using these commands.
Theory
4|P a g e
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
Lab Exercise(s)
1. Explore the file system of a Window system and a Linux system, and write prime
differences.
2. Create a file in you Linux system, in your current user’s home directory, named as
file1.txt. Write your name and Registration number in the file1.txt using cat
command. Now rename the file using mv command, the new name must be
“yourRegistratioinNo.txt”.
3. Create a copy of the file you have created with your registration number. Now delete
the original file.
4. Create a directory with your name and move all the files (using mv command) created
by you in currently logged in user’s home directory.
5. Create multiple directories using single command. (Directories name can your
friends’ name.
Viva Questions
1. How Windows is different from Linux.
2. Differentiate internal and external commands in Linux.
3. Name any 3 Windows and Linux flavours.
4. List different file systems used in Windows and Linux.
5. What are the different types of files in Linux environment?
5|P a g e
S. No. Parameter Max Marks Obtained Marks
1 Conceptual/procedural 15
understanding of the student
2 Student is able to answer sample 15
viva questions
3 Completion of Lab exercises 20
Signature of Faculty with date
6|P a g e
Experient 2- Shell Programming
Aim
The aim of this laboratory is to introduce the shell script that offers the student with an
interface to include a sequence of commands need to employ frequently for saving time.
Learning Objective
Students will be able to learn the basics of shell scripting to use variables, accept input from
a user and perform tests and make decisions.
Description
A shell program, frequently called as a shell script, is basically a program composed of shell
commands. Each command within the script is executed by the shell in sequence. Shell script
files are created with editors such as vi and stored with the .sh extension. Set execute
permission for shell script file using chmod command and execute with the sh or bash
command in the terminal.
Shell Variables
User can include user-defined variables in a shell script program using the following format,
var_name=string
EX: day="Sunday"
In the above example, the variable “day” is assigned with the value "Sunday".
In the above example, wc command accepts the input from the standard input and displays
the number of lines, words and characters.
7|P a g e
Here, the output of the ls command is redirected to the file with the name “test.txt”
Shell arithmetic
The shell enables the arithmetic expressions to be evaluated using the commands let or expr
x=2
y=3
let "a = $x + $y"
b=`expr $x + $y`
echo "Sum is $a"
echo "Sum is $b"
Flow control
The shell supports various commands to control the flow of execution in a program. The basic
constructs which provide the flow control are,
o if, if-then, if-then-else, if-then-elif-then-else
o case
The if command is fairly simple on the surface; it makes a decision based on the exit status of
a command. The if command's syntax looks like this:
if <condition>
then
commands
elif <condition>
then
commands
else
commands
fi
case construction
The case command evaluates the given test expression and performs the matching operation
against each case value to continue the execution of commands. The default condition (*) will
be executed with no match is found. The basic syntax of the case...esac statement is,
8|P a g e
case <test-value> in
value1)
<commands>
;;
value2)
<commands>
;;
value3)
<commands>
;;
*) Default statement to be executed
;;
esac
Sample program
The following shell program demonstrates the selection of a number with case statement.
num="one"
case "$num" in
"one") echo "Number is 1."
;;
"two") echo " Number is 2."
;;
"three") echo " Number is 3."
;;
*) echo " No Number."
;;
esac
Loops
Loops in shell scripting are used to execute a set of commands for a certain number of times.
These loops will execute the commands repeatedly until a condition fulfils. The basic loops
in shell scripting are,
• While loop
• For loop
while loop
while [expression]
do
command-list
done
9|P a g e
The commands in the while expression are executed to enter into the loop for executing the
command-list.
num=0
for loop
The for loop executes a set of commands for a specified number of times. The syntax
of for loop in shell scripting is presented as follows,
This for loop includes a number of items in the list and var is a looping variable. The for loop
will execute the command-list for each item in the list.
num=1
for i in $list
do
echo $num
num=`expr $num + 1`
done
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
10 | P a g e
Lab Exercise(s)
Viva Questions
1. What do you understand by a shell?
2. How can you define a Shell Variable?
3. What is the alternative to if-else if-else statements in bash?
4. How can we get input in shell script?
5. How set executable permission on a shell script file?
1 Conceptual/procedural 15
understanding of the student
2 Student is able to answer sample 15
viva questions
3 Completion of Lab exercises 20
Signature of Faculty with date
11 | P a g e
Experient 3- File Manipulation using System Calls
Aim
The objective of this laboratory is to introduce the working behind the copy(cp) command.
Copy(cp) command uses system calls like open, read, write and lseek to copy the contents of
one file to another and read what users enters and write the same in the file.
Learning Objective
Student will be able to learn the working of system calls and the working behind some most
used command in Linux shell.
This section provides syntax of system calls used in this chapter. More about the system calls
can be read using manual page/ help in Linux shell.
• open: to create a file and open the file in read/write and append mode.
• read: to open a file in read mode and read from file or console.
• write: to open a file in write mode and write on file or console.
• close: to close a file.
• lseek: to set the pointer inside the file to a position.
Sample Programs
int main() {
int n, m;
n = open("new_file", O_RDONLY);
printf("File descriptor is %d \n", n);
return 0;
12 | P a g e
}
int main() {
int n, m;
char buffer[100];
return 0;
}
int main() {
int a, b, c, d;
char buffer[100];
return 0;
}
int main() {
int a, b, c, d;
char buffer[100];
13 | P a g e
printf("The value of b: %d , c: %d \n", b, c);
return 0;
}
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
Lab Exercise(s)
1. Create a program using system calls to copy either the first half or the second half of a
file into a new file.
2. Develop a program using system calls to read input from the console until the user
inputs '$', and then save the input into a file.
3. Design a program using system calls to read the contents of a file without using a char
array and display the contents directly on the console. Please refrain from using built-
in functions like sizeof() and strlen().
Viva Question
1. Which system call is used to change the position of the file pointer?
2. What does the read system call return?
3. What value does the open system call return?
4. What is passed as the first argument of the read/write system call?
5. If a file is to be appended, in which mode should it be opened using the open system
call?
6. How can we use the lseek system call to handle file appending?
7. What value does the lseek system call return?
8. Which system call can be used to determine the size of a file?
9. How can we find the size of a file using the lseek system call?
14 | P a g e
S. No. Parameter Max Marks Obtained Marks
1 Conceptual/procedural 15
understanding of the student
2 Student is able to answer sample 15
viva questions
3 Completion of Lab exercises 20
Signature of Faculty with date
15 | P a g e
Experient 4- Directory Manipulation using System Calls
Aim
The objective of this laboratory is to introduce the working behind the command mkdir and
ls. These commands use system calls like mkdir, opendir, readdir, to copy the contents of one
file to another and read what users enters and write the same in the file.
Learning Objective
Student will be able to learn the working of directory system calls and the working behind
some most used command in Linux shell.
Theory
This section provides syntax of system calls used in this chapter. More about the system calls
can be read using manual page/ help in Linux shell.
Dirent Structure
Dirent structure can be read using man readdir as LINUX manual page.
struct dirent
{
Ino_t d_ino; /* inode number */
off_ t d_off; /* off_set to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported by all file system types */
char d_name[256]; /* filename */
};
16 | P a g e
Outline of Programs
1. Program to use directory system call and print the contents of the directory
#include<stdio.h>
#include<dirent.h>
int main()
{
DIR *dp;
struct dirent *dptr;
int b = mkdir(“Dir1", 0777);
dp=opendir(“Dir1");
while(NULL !=(dptr = readdir(dp)))
{
printf(“\%s \n", dptr ->d_name);
printf(\%d \n",dptr->d_type);
}
return 0;
}
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
Lab Exercise(s)
1. Create a program using directory system calls to make a new directory on the desktop,
then create a file inside that directory, and finally, list the contents of the directory.
2. Develop a program using directory and file manipulation system calls to copy the
contents of one directory into a newly created directory.
17 | P a g e
S. No. Parameter Max Marks Obtained Marks
1 Conceptual/procedural 15
understanding of the student
2 Student is able to answer sample 15
viva questions
3 Completion of Lab exercises 20
Signature of Faculty with date
18 | P a g e
Experient 5 – Processes Management using System Calls
Aim
Learning Objective
Students will be able to learn the creation of a process using fork() call
Theory
Outline of Programs
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
int main()
{
int pid;
pid=getpid();
printf("current process pid is %d",pid);
printf("forking a child process \n");
pid=fork();
if(pid==0)
{
printf("child process id: %d and its parent id: %d", getpid(),
getppid());
}
else
{
printf("parent process id %d",getpid());
}
return 0;
}
19 | P a g e
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
int main()
{
int pid;
pid=getpid();
printf(“current process pid is %d", pid);
printf(“forking a child process \n");
pid=fork();
if(pid==0)
{
printf(“child process is sleeping");
sleep(10);
printf(“orphan child parent id: %d", getppid());
}
else
{
printf(“parent process completed");
}
return 0;
}
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
int main()
{
pid_t a;
a=fork();
if(a>0)
{
sleep(20);
printf(“PID of Parent %d", getpid());
}
else
{
printf(”PID of CHILD %d", getpid());
exit(0);
}
}
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
20 | P a g e
Lab Exercise(s)
1. Write a program using system calls for operation on process to simulate that n fork
calls create (2n – 1) child processes.
1. Write a program using systems for operations on processes to create a hierarchy of
processes P1 → P2 → P3. Also print the id and parent id for each process.
2. Write a program using system calls for operation on processes to create a hierarchy
of processes as given in figure 1. Also, simulate process p4 as orphan and P5 as zombie.
P1
P2 P4
P3 P5
P1
P2 P5
21 | P a g e
P3 P6
P4 P7
Viva Questions
1 Conceptual/procedural 15
understanding of the student
2 Student is able to answer sample 15
viva questions
3 Completion of Lab exercises 20
Signature of Faculty with date
22 | P a g e
Experient 6- Creation of Multithreaded Processes using Pthread Library
Aim
Introduce the operations on threads, which include initialization, creation, join and exit
functions of thread using pthread library.
Learning Objective
Theory
This section provides syntax of thread functions. More about the system calls can be
read using manual page/ help in Linux shell.
Outline of Programs
#include <stdio.h>
#include <pthread.h>
char *a;
void *func() {
printf("In thread function \n");
pthread_exit("Exit thread function \n");
}
int main() {
pthread_t thread1;
void *result;
23 | P a g e
pthread_join(thread1, &result);
return 0;
}
#include<pthread.h>
#include<stdlib.h>
void *myfunc(void *myvar);
int main (int argc, char *argv[])
{
pthread t thread1, thread2;
char *msg1= "first thread";
char *msg2= "second thread";
int ret1, ret2;
ret1 = pthread_create(&thread1, NULL, myfunc,(void *) msg1);
ret2 = pthread_create(&thread2, NULL, myfunc,(void *) msg2);
printf("Main function after pthread_create \n");
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("first thread ret1= %d \n", ret1);
printf("first thread ret1= %d \n", ret1);
return 0;
}
#include <stdio.h>
#include <pthread.h>
int *a;
struct arg_struct {
24 | P a g e
int arg1;
int arg2;
int arg3;
};
int main() {
pthread_t some_thread;
struct arg_struct args;
args.arg1 = 5;
args.arg2 = 7;
void *result;
pthread_create(&some_thread, NULL, &print_the_arguments, &args);
pthread_join(some_thread, &result); /* Wait until the thread is finished */
printf("%d \n", (int)result);
return 0;
}
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
Lab Exercise(s)
1. Write a program using pthread to concatenate the strings, where multiple strings are
passed to thread function.
2. Write a program using pthread to find the length of string, where strings are passed
to thread function.
3. Write a program that performs statistical operations of calculating the average,
maximum and minimum for a set of numbers. Create three threads where each performs
their respective operations.
25 | P a g e
4. Write a multithreaded program where an array of integers is passed globally and is
divided into two smaller lists and given as input to two threads. The thread will sort their
half of the list and will pass the sorted list to a third thread which merges and sorts the
list. The final sorted list is printed by the parent thread.
Viva Questions
1 Conceptual/procedural 15
understanding of the student
2 Student is able to answer sample 15
viva questions
3 Completion of Lab exercises 20
Signature of Faculty with date
26 | P a g e
Experient 7- Process Synchronization using Semaphores/Mutex
Aim
Learning Objective
Student will be able to learn the concept of mutex and semaphores using pthread
library. some classical problems of process synchronization will be simulated and
solved.
Theory
This section provides syntax of mutex and semaphore functions. More about the
system calls can be read using manual page/ help in Linux shell.
#include <stdio.h>
#include <pthread.h>
int shared = 5;
void *func1() {
int local;
/* Critical section */
local = shared;
local = local + 1;
sleep(5); /* Causes a context switch */
shared = local;
/* Critical section */
27 | P a g e
printf("shared in func1: %d \n", shared);
pthread_exit(NULL);
}
void *func2() {
int local;
/* Critical section */
local = shared;
local = local - 1;
shared = local;
/* Critical section */
printf("shared in func2: %d \n", shared);
pthread_exit(NULL);
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, func1, NULL);
pthread_create(&t2, NULL, func2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
2. Program to remove race condition using mutex
#include <stdio.h>
#include <pthread.h>
int shared = 5;
pthread_mutex_t l; /* Mutex variable l */
void *func1() {
int local;
/* Critical section */
pthread_mutex_lock(&l); /* Applying lock using l (initially false) */
local = shared;
local = local + 1;
sleep(5); /* Causes a context switch */
shared = local;
pthread_mutex_unlock(&l); /* Releasing lock using l */
/* Critical section */
printf("shared in func1: %d \n", shared);
pthread_exit(NULL);
}
void *func2() {
int local;
/* Critical section */
pthread_mutex_lock(&l); /* If acquired by func1, l will return true */
28 | P a g e
local = shared;
local = local - 1;
shared = local;
pthread_mutex_unlock(&l); /* Releasing lock using l */
/* Critical section */
printf("shared in func2: %d \n", shared);
pthread_exit(NULL);
}
int main() {
pthread_t t1, t2;
pthread_mutex_init(&l, NULL); /* Initialize the mutex variable l */
pthread_create(&t1, NULL, func1, NULL);
pthread_create(&t2, NULL, func2, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_mutex_destroy(&l); /* Destroy the mutex variable l */
return 0;
}
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
int shared = 5;
void *func1() {
int local;
/* Critical section */
local = shared;
local = local + 1;
shared = local;
29 | P a g e
sem_post(&s); /* Releasing lock using s */
/* Critical section */
pthread_exit(NULL);
void *func2() {
int local;
/* Critical section */
local = shared;
local = local - 1;
shared = local;
/* Critical section */
pthread_exit(NULL);
int main() {
pthread_join(t1, NULL);
pthread_join(t2, NULL);
30 | P a g e
return 0;
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
Lab Exercise(s)
1. Implement the producer consumer problem using pthreads and mutex operations.
Test Cases:
(a) A producer only produces if buffer is empty and consumer only consumes if some
content is in the buffer.
(b) A producer produces(writes) an item in the buffer and consumer
consumes(deletes) the last produces item in the buffer.
(c) A producer produces(writes) on the last consumed(deleted) index of the buffer.
2. Implement the reader writer problem using semaphore and mutex operations to
synchronize n readers active in reader section at a same time, and one writer active at a
time.
Test Cases:
(a) If n readers are active no writer is allowed to write.
(b) If one writer is writing no other writer should be allowed to read or write on the
shared variable.
Viva Questions
31 | P a g e
Learning Outcomes (What I have Learnt)
1 Conceptual/procedural 15
understanding of the student
2 Student is able to answer sample 15
viva questions
3 Completion of Lab exercises 20
Signature of Faculty with date
32 | P a g e
Experient 8- Inter Process Communication using Pipes/Shared Memory
Aim
The aim of this laboratory is to introduce the Inter-process communication (IPC) mechanism
of operating system to allow the processes to communicate with each other.
Learning Objective
Students will be able to learn various IPC techniques to exchange the information between
different processes in a system.
Description
Inter Process Communication (IPC) is a mechanism offered by the operating system two
provide communication between two or more cooperating processes. This communication
mechanism helps the processes to transfer or share data and coordinate activities. Inter process
communication is supported by all UNIX systems. The IPC can be used between processes on
a single computer system as well as on different systems. The examples of IPC methods include
Pipes, FIFOs (named pipes), Shared memory, Message queues and Remote Procedure Call.
Pipes
Pipes are the oldest form of UNIX System IPC and are provided by all UNIX systems. Pipes
only provides half duplex communication between processes that have a common ancestor.
#include <unistd.h>
The pipe function returns two file descriptors through the fd argument. The fd[0] is a file
descriptor that a process can use to read the data from the pipe, and fd[1] is a different file
descriptor that a process in use to write data to the pipe.. The following figure shows the data
flow between two ends of a half-duplex pipe in a process.
33 | P a g e
Ex: The pipe communication between the parent and the child processes.
The following figure shows the creation of a child process and IPC between parent and child
process using pipe method.
In the pipe from the parent to the child, the parent closes the read end of the pipe (fd[0]), and
the child closes the write end (fd[1]). The following figure demonstrates the resulting design of
descriptors.
34 | P a g e
Sample program
1. The following program illustrates the creation of a child process and data transfer using
pipes.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
int main() {
int fd[2], nb;
pid_t cpid;
char inf[] = " Welcome to LPU\n";
char rbuff[50];
pipe(fd);
if (cpid == 0) {
close(fd[0]);
write(fd[1], inf, (strlen(inf) + 1));
printf("The information written in the pipe by child is: %s", inf);
exit(0);
} else {
close(fd[1]);
nb = read(fd[0], rbuff, sizeof(rbuff));
printf("The information received by the Parent process from the pipe is: %s", rbuff);
}
return 0;
}
2. The following program illustrates the creation of a child process and two way
communication using pipes.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
int main() {
int fd1[2], fd2[2], nb;
35 | P a g e
pid_t cpid;
char inf1[] = "Welcome to LPU";
char inf2[] = "Thank you";
char buff[100];
pipe(fd1);
pipe(fd2);
if (cpid == 0) {
close(fd1[0]);
close(fd2[1]);
write(fd1[1], inf1, strlen(inf1) + 1);
nb = read(fd2[0], buff, sizeof(buff));
printf("\n The information received by the Child process is: %s\n", buff);
exit(0);
} else {
close(fd1[1]);
close(fd2[0]);
write(fd2[1], inf2, strlen(inf2) + 1);
nb = read(fd1[0], buff, sizeof(buff));
printf("\n The information received by the parent process is: %s\n", buff);
}
return 0;
}
Shared Memory
Shared Memory is another important IPC mechanism where system memory is shared between
two or more processes. Here, communication is done through this shared memory where
modifications done by one process can be seen by another process. The operating system assigns
a memory segment in the address space for several processes to read and write without
involving the kernel during the data exchange. The basic steps involved in the shared memory
communication are,
a. Requesting the operating system for a memory segment that can be shared between
processes.
b. Associating the memory segment to the address space of the calling process.
shmget() is used to create the shared memory segment. The syntax of the function is shown
below.
#include <sys/ipc.h>
#include <sys/shm.h>
36 | P a g e int shmget (key_t key, size_t size, int shmflg);
• The first parameter indicates the unique number recognizing the shared segment.
• The second parameter indicates the size of the shared segment (e.g., 1024 or 2048 byt
es).
• The third parameter indicates the permissions on the shared segment.
shmat() is used to connect the shared segment with the process's address space. The syntax
of the function is shown below.
#include <sys/types.h>
#include <sys/shm.h>
void *shmat(int shmid, const void *shmaddr, int shmflg);
shmdt(): This function is used to detach the shared segment from a process
shmctl(): This function allows the a process to control the shared memory segment.
3. The following program illustrates the creation of a shared memory segment and adding data
into it.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
#include <string.h>
37 | P a g e
int main() {
void *shm;
char buf[200];
int shmid;
shm = shmat(shmid, NULL, 0); // Attaching the process to the shared memory segment
strcpy(shm, buf);
return 0;
Video Reference:
https://youtube.com/playlist?list=PLWjmN065fOfGdAZrlP6316HVHh8jlvefD
Lab Exercise(s)
1. Implement IPC using named pipes concept.
38 | P a g e
2. Implement IPC using message passing technique
3. Implement IPC using message queue technique
Viva Questions
1. What is function of named pipe?
2. Can named pipes be bidirectional?
3. Differentiate shared memory and message passing
4. Which is faster shared memory or message queue?
1 Conceptual/procedural 15
understanding of the student
2 Student is able to answer sample 15
viva questions
3 Completion of Lab exercises 20
Signature of Faculty with date
39 | P a g e
Practice exercises organized by experiment
Exercise 2
1. Create a new directory called "lab_exercises" in your home directory.
2. Inside the "lab_exercises" directory, create a new file called "file1.txt" and write some
text in it.
3. Create a copy of "file1.txt" and name it "file2.txt" using the cp command.
4. Verify that "file2.txt" is an exact copy of "file1.txt" by opening both files and
comparing their contents.
5. Create a new directory called "backup" inside the "lab_exercises" directory.
6. Move "file1.txt" and "file2.txt" to the "backup" directory using the mv command.
7. Verify that both files have been moved to the "backup" directory by listing its
contents.
8. Create a new file called "file3.txt" in the "lab_exercises" directory and write some text
in it.
9. Create a new directory called "archive" inside the "lab_exercises" directory.
10. Move "file3.txt" to the "archive" directory and rename it to "file3_backup.txt" using
the mv command.
11. Verify that "file3_backup.txt" has been moved to the "archive" directory and that its
contents are the same as "file3.txt".
12. Create a new directory called "temp" inside the "lab_exercises" directory.
13. Create a new file called "file4.txt" in the "temp" directory and write some text in it.
14. Move "file4.txt" to the "lab_exercises" directory using the mv command.
15. Verify that "file4.txt" has been moved to the "lab_exercises" directory and that its
contents are the same as before.
Shell Programming
Exercise 1
A. Write a script that displays "Hello, World!" when executed.
B. Modify the script to accept a command line argument and display "Hello,
<argument>!" instead of "Hello, World!".
Exercise 2
Write a script that accepts two command line arguments and displays their sum.
40 | P a g e
Exercise 3
A. Write a script that accepts a directory name as a command line argument and displays
the number of files in that directory.
B. Modify the script to display the number of files in the directory and all its
subdirectories.
Exercise 4
A. Write a script that accepts a filename as a command line argument and displays the
number of lines, words, and characters in that file.
B. Modify the script to accept multiple file names as command line arguments and
display the number of lines, words, and characters in each file.
Exercise 5
A. Declare a variable called "name" and assign your name to it. Display the value of the
variable using the echo command.
B. Declare a variable called "age" and assign your age to it. Display the value of the
variable using the echo command.
C. Declare a variable called "color" and assign your favorite color to it. Display the value
of the variable using the echo command.
Exercise 6
Declare a variable called "num1" and assign the value 10 to it. Declare a second
variable called "num2" and assign the value 5 to it. Add the values of the two variables and
display the result using the echo command.
Exercise 7
A. Declare a variable called "filename" and assign the value "sample.txt" to it. Use the
variable to create a new file with that name using the touch command.
B. Declare a variable called "directory" and assign the value "myfolder" to it. Use the
variable to create a new directory with that name using the mkdir command.
Exercise 8
Declare a variable called "files" and assign a list of filenames to it. Use a loop to display the
contents of each file in the list using the cat command.
Exercise 9
A. Write a command that displays the contents of a file called "file1.txt" on the screen.
B. Use input redirection to create a new file called "file2.txt" with the contents of
"file1.txt".
C. Write a command that appends the contents of "file1.txt" to the end of "file2.txt".
Exercise 10
A. Write a for loop that prints the numbers from 1 to 10 on the screen.
B. Modify the loop to print only the even numbers from 1 to 10.
Exercise 11
A. Write a loop that displays the names of all files in the current directory.
B. Modify the loop to display only the names of files with the extension ".txt".
Exercise 12
A. Write a case/esac statement that displays a message on the screen based on the value
of a variable called "day". If the value is "Monday", the message should be "It's the start of
the week". If the value is "Friday", the message should be "Thank goodness it's Friday!". For
any other value, the message should be "Just another day".
41 | P a g e
B. Modify the case/esac statement to use a read command to read the value of "day"
from the user.
Exercise 13
Write a case/esac statement that calculates the area of a geometric shape based on the user's
input. If the input is "square", the statement should ask the user for the length of the side and
display the area. If the input is "rectangle", the statement should ask the user for the length
and width and display the area. If the input is "circle", the statement should ask the user
Exercise 14
A. Write an if statement that checks if a variable called "x" is greater than 10. If it is,
display the message "x is greater than 10".
B. Modify the if statement to check if "x" is equal to 10 as well. If it is, display the
message "x is equal to 10".
Exercise 2
Write a program in C that reads the contents of a file called "input.txt" and writes them to a
new file called "output.txt". You should use system calls like open(), read(), and write().
Exercise 3
Write a program in C that reads a file called "input.txt" and counts the number of lines in the
file. You should use system calls like open(), read(), and write().
Exercise 4
A. Write a C program that creates a file called "numbers.txt" and writes 100 integers to
it, one integer per line.
B. Using the lseek system call, move the file pointer to the beginning of the file.
C. Read the first 10 integers from the file and print them to the console.
Exercise 5
Write a C program that prints the last 10 characters of a file named as "input.txt" on the
screen. Use open, read, write and lseek system calls.
Exercise 6
Write a C program that prints half content of a file named as "input.txt" on the screen. Use
open, read, write and lseek system calls. If there are 100 characters written in the file, your
program should display the first 50 characters on the screen.
Exercise 1
A. Write a C program that opens a directory called "my_directory" and reads all the files
and directories inside it.
B. For each file and directory, print its name and whether it is a file or a directory.
C. Count the number of files and directories inside the "my_directory" directory.
D. Close the directory.
42 | P a g e
Process Management using System Calls
Exercise 1
Write a C program that uses the fork system call to create a child process. In the child
process, print the process ID (PID) and the parent process ID (PPID). In the parent process,
print the PID and the child's PID.
Exercise 2
Write a C program that uses the fork system call to create a child process. In the child
process, print a message indicating that it is the child process. In the parent process, print a
message indicating that it is the parent process.
Exercise 3
Write a C program that uses the fork system call to create a child process. In the child
process, create a file called "child.txt" and write the message "This is the child process" to it.
In the parent process, create a file called "parent.txt" and write the message "This is the
parent process" to it.
Exercise 4
Write a C program that uses the fork system call to create a child process. In the child
process, print the sum of the first 100 positive integers. In the parent process, print the sum of
the first 1000 positive integers.
Exercise 1
Write a C program that creates two threads using the Pthread library. Each thread should
print its thread ID to the console.
Exercise 2
Write a C program that creates two threads using the Pthread library. One thread should
generate a random number, print it to the console and another should check for a prime
number.
Exercise 3
Write a C program that creates two threads using the Pthread library. One thread should print
even numbers from 2 to 100, and the other thread should print odd numbers from 1 to 99.
Exercise 1
Write a C program to create two threads that increment a shared variable using a mutex to
synchronize access to the variable.
Exercise 2
Write a C program to create two processes that increment a shared variable using semaphores
to synchronize access to the variable.
Exercise 3
43 | P a g e
Write a C program to create two processes that implement a producer-consumer model using
semaphores to synchronize access to the shared buffer.
Exercise 1
Write a C program that creates a file called "file1.txt" and writes some text to it. Then, use
the dup system call to create a duplicate file descriptor for the file. Finally, use the duplicate
file descriptor to write some more text to the file.
Exercise 2
Write a C program that creates two pipes using the pipe system call. Then, fork a child
process. In the parent process, use the dup2 system call to redirect the standard input to one
end of the pipe, and the standard output to the other end of the pipe. In the child process, read
from the standard input and write to the standard output.
Exercise 3
Write a C program that takes a file name as a command-line argument. Use the open, dup,
and dup2 system calls to open the file, create two duplicate file descriptors for it, and redirect
the standard input and standard output to those file descriptors. Then, read from the standard
input and write to the standard output.
Exercise 4
Write a C program that creates a file called "file1.txt" and writes some text to it. Then, use
the dup2 system call to create a duplicate file descriptor for the file, and close the original file
descriptor. Finally, use the duplicate file descriptor to read the text from the file and write it
to the standard output.
Exercise 1
Write a C program that creates a named pipe (FIFO) using the mkfifo system call. Then, fork
a child process. In the parent process, write some data to the pipe using the write system call.
In the child process, read the data from the pipe using the read system call.
Exercise 2
Write a C program that creates a named pipe called "mypipe" using the mkfifo system call.
Then, use the open system call to open the pipe for writing. Write some data to the pipe using
the write system call. Finally, use the cat command to read the data from the pipe.
Exercise 3
Write a C program that creates a named pipe called "mypipe" using the mkfifo system call.
Then, use the open system call to open the pipe for reading. Read some data from the pipe
using the read system call. Finally, use the echo command to write the data to the standard
output.
Exercise 4
44 | P a g e
Write a C program that creates a named pipe called "mypipe" using the mkfifo system call.
Then, fork a child process. In the parent process, use the open system call to open the pipe for
writing. In the child process, use the open system call to open the pipe for reading. Then,
write some data to the pipe in the parent process and read the data from the pipe in the child
process.
Exercise 5
Write a program in C that creates a child process using fork(). The parent process should read
a message from the user and send it to the child process using a pipe. The child process
should then read the message from the pipe and print it to the console.
Shared Memory
Exercise 1
Implement a simple message passing system using shared memory in C. Create a parent
process that forks a child process and communicates with it using the shared memory.
Use the shmget, shmat, and shmdt functions to create a shared memory segment, attach to it,
and detach from it. The parent process should write a message to the shared memory
segment, and the child process should read and print the message.
45 | P a g e