Os Lab Manual Answers
Os Lab Manual Answers
Os Lab Manual Answers
LAB WORKBOOK
22CS2109AA OPERATING SYSTEMS
1
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
LABORATORY WORKBOOK
HOD-CSE
K L UNIVERSITY
2
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
The lab framework comprises a creative element but shifts the time-intensive aspects outside of the Four-Hour
closed lab period. Within this structure, each lab includes THREE parts: Pre-lab, In-Lab and Post-lab.
a. Pre-Lab
The Prelab exercise is a homework assignment that links the lecture with the lab period - typically takes 2 hours
to complete. The goal is to make students familiar with the basic topics which make in-lab easy for them.
Students attending a two-hour closed lab are expected to make a good-faith effort to complete the Prelab
exercise before coming to the lab. Their work need not be perfect, but their effort must be real.
b. In-Lab
The In-lab section takes place during the actual lab period. The First hour of the lab period can be used to
resolve any problems the students might have experienced in completing the Prelab exercises. The intention is
to give productive feedback so that students leave the lab with working Prelab software - a significant
achievement on their part. During the second hour, students complete the In-lab exercise to strengthen the
concepts learned in the Prelab.
c. Post-Lab
The last phase of each lab is a post-Lab section that is done as exercise is a homework assignment that links the
lecture with the lab period - typically takes 2 hours to complete. The goal is to make students familiar with the
Advanced topics which learned from in-lab. In Post-Lab Skilling, students analyze the efficiency or adequacy of
given exercise.
3
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
4
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Table of Contents
WEEK Name of The Experiment / TOPIC Page
No.
1 BASIC UNIX COMMAND WITH EXAMPLES 06
3 PROCESS API 36
12 CONCURRENCY 134
5
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 1
(BASIC COMMANDS WITH EXAMPLES)
Prerequisite:
The "man" command is used to display the manual pages for various
commands, programs, and functions in the UNIX operating system. It
man
provides detailed information about the command's usage, options,
syntax, and examples.
The "who" command is used to display information about currently logged-in
users on the system. It shows the username, terminal, login time, and other
details.
who
6
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
The "touch" command is used to create new files or update the timestamp
touch (access and modification times) of existing files.
The "mv" command is used to move or rename files and directories. It can be
used to move files between directories or rename files.
mv
The "sort" command is used to sort the lines of text files in ascending or
sort descending order based on various criteria.
7
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
The "head" command is used to display the first few lines of a file. By
default, it shows the first 10 lines, but this can be customized using
options.
head
The "date" command is used to display or set the system date and time.
date It can also be used to format the output in different ways.
8
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In Lab Task:
1. Read the problem description and write all necessary commands/code as elaborated
below. Use space provided in the next page if required.
Problem Description : Stan lee wants to get started with terminal commands in Linux. Help him out to
perform the following set of statements:
a .He wants to know his current directory that he is working with, in the system. After identifying the
current directory, he desires to create a folder on his Desktop called Marvel.
Ans:
pwd
mkdir ~/Desktop/Marvel
b.Now, he wants to list out all the Avengers of the “Marvel” universe. He adds the following set of Avengers
to Avengers.txt:
i. Ironman
ii.Captain america
iii.Thor
iv.Hulk
v.Black widow
Ans:
c. After adding the names displayed above check whether the names are inserted or not.
Ans:
mv ~/Desktop/Marvel/Avengers.txt ~/Desktop
chmod ug+rwx ~/Desktop/Avengers.txt
chmod o+r ~/Desktop/Avengers.txt
ls -l ~/Desktop/Avengers.txt
9
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
d. Stan lee wants to relocate the file (Avengers.txt) from Marvel to Desktop, after relocating the file give
all the permissions to user and group and give only read permission to others. Verify the permissions
when done.
Ans:
mv ~/Desktop/Marvel/Avengers.txt ~/Desktop
chmod ug+rwx ~/Desktop/Avengers.txt
chmod o+r ~/Desktop/Avengers.txt
ls -l ~/Desktop/Avengers.txt
e. Stan lee now wants to add more avengers to the Marvel , Add the following set of new
avengers to Avengers.txt .
1. Black panther
2. Groot
3. Captain marvel
4. Spiderma
Ans:
echo "Black
panther" >>
~/Desktop/Avenge
rs.txt
~/Desktop/Avenge
rs.txt
echo "Captain
marvel" >>
~/Desktop/Avenge
rs.txt
echo "Spiderman"
10
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
>>
~/Desktop/Avenge
rs.txt
11
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
f. Sort the names of the file in lexicographical order and export the result to Sortedavengers.txt and
display the content of it.
Ans:
sort ~/Desktop/Avengers.txt > ~/Desktop/Sortedavengers.txt
cat ~/Desktop/Sortedavengers.txt
g. Now, Stanlee sends the first avenger from Sortedavengers.txt to visit Wakanda.txt(another file
in the desktop) as a part of mission to kill thanos. After sending , move the wakanda.txt to
marvel .
Ans:
head -n 1 ~/Desktop/Sortedavengers.txt > ~/Desktop/Wakanda.txt
mv ~/Desktop/Wakanda.txt ~/Desktop/Marvel
h. To know the status of the mission to kill Thanos , Stan lee pings the Avengers to the address
103.102.166.224 with 3 packets of data.
Ans:
ping -c 3 103.102.166.224
I. If pinging becomes successful then, the date is to be echoed to mission.log which is to be included in the
Marvel directory which he created earlier.
`
Ans
if ping -c 3 103.102.166.224; then echo $(date) >> ~/Desktop/Marvel/mission.log; fi
12
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
2. Write commands/code in the space provided for each of the questions below:
A. Count the number of users who logged in and display the result.
Ans.
Who | we -l
Ans.
ls -l | grep "^-" | wc -l
cmp Ans.
13
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
D. Display the file /etc/passwd from the 45th line using the more command and start
the vi editor on the current file and current line. Hint: Press ‘h’ or ‘?’Key While viewing the file
with more command to get the help.
Ans.
more +45 /etc/passwd
vi +45 /etc/passwd
calendar
. Ans
cal MM YYYY
F. Which options are required for “who” command to display the column headers and more details
list?
Ans:
who -H
14
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
POST LAB 1
15
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
It is used to create links between files. The two types of links that can be
created are hard links and symbolic links. Hard links create multiple directory
entries that point to the same underlying data, while symbolic links create a
ln special type of file that points to another file or directory.
It is used to remove (delete) files and directories from the file system. By
default, it does not prompt for confirmation, so it should be used with caution.
To remove directories, the -r or -rf option is used for recursive removal.
rm
It is used to copy files and directories from one location to another. It creates a
new copy of the file or directory with the specified name in the destination
location. The -r option is used for recursive copying of directories.
cp
It is used to remove (delete) empty directories from the file system. It can only
remove directories that do not contain any files or subdirectories.
rmdir
It is used for file compression and decompression. It compresses files using the
gzip algorithm and creates files with the extension ".gz". It can also
decompress gzip-compressed files.
gzip
16
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
It displays information about the system's free and used memory (RAM) and
swap space. It shows the total, used, and available memory along with buffers
and cached memory.
free
17
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
2. Write commands/code in the space provided for each of the questions below:
Ans.
hostname
B. How do you spell check a file and display the mistakes? (Hint:
ispell) Ans.
ispell -f file.txt
Ans
sum=$(expr 10 + 5)
difference=$(expr 10 - 5)
echo "Sum: $sum"
echo "Difference: $difference"
18
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
file2=GID’S)
Ans
E. Perform sort on the 2 and 4 fields (Create a new file name INPUT with Tab as a Delimiter and
having repetition of data in the fields)
F. Write a Grep command to search for a five-letter word, whose first letter is a ‘s’ and last letter ‘d’
G. Multiple jobs can be issued from the same command line using the operators: && and ||. Try
combining the commands, cat nonexistent and echo hello using each of these operators. Reverse the
order of the commands and try again. What are the rules about when the commands will be executed?
19
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK-2
(UNIX FILE OPERATIONS
AND SYSTEM CALLS)
Prerequisite:
● Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
● Opening an existing file (fopen) and Reading from a file (fscanf, fgets or fgetc)
● Writing to a file int fputc, fputs
● Moving to a specific location in a file (fseek, rewind) and Closing a file (fclose)
● Basic UNIX system calls on files.
1. Using the format “$man 3 Library call name”, Learn the following Standard
I/O Library functions and write the function prototypes.
Type $man 3 fopen on Linux machine, to get function prototypes for all the library
functions a.The fopen function opens a specified file.
#include <stdio.h>
FILE *fopen(const char *restrict pathname, const char *restrict
type); b.The standard I/O function fopen returns a pointer to a FILE
object.
Now write the functionality of file handling library functions in c given in the below:
SL NO FUNCTIO FUNCTIONALITY/PROTOTYPE
NS
1 fopen( ) It is used to open a file and returns a pointer to the file stream. It allows you to specify
the file name, mode (such as "r" for reading, "w" for writing, "a" for appending), and
other options. It enables you to perform various operations on the file, such as reading
from or writing to it.
2 fclose( It is used to close a file that was previously opened with fopen(). It ensures that any
) buffered data is written to the file and releases the resources associated with the file
stream. It is important to close files after using them to free up system resources.
20
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
3 getc( ) It is used to read a character from a file. It reads the next character from the file
pointed to by the file stream. It returns the character read as an unsigned char cast to
an int, or EOF if the end of the file is reached or an error occurs.
4 fscanf( ) It is used to read formatted data from a file. It reads data from the file
according to the specified format, similar to scanf(). It allows you to extract
data of different types (integers, floats, strings, etc.) from the file.
5 fprintf( ) It is used to write formatted data to a file. It writes data to the file in a
specified format, similar to printf(). It allows you to format and write data of
different types to the file.
6 gets( ) It is used to read a string from the standard input (keyboard) and store it in a
character array. However, it is generally considered unsafe to use due to the
possibility of buffer overflow. It is recommended to use safer alternatives
like fgets().
7 puts( ) It is used to write a string to the standard output (console) followed by a
newline character. It is a simple way to display a string on the screen.
8 fseek( ) It is used to set the file position indicator to a specific location within the
file. It allows you to move the position indicator forward or backward from
the beginning, end, or current position of the file. It is commonly used to
navigate within a file.
9 ftell( ) It is used to get the current file position indicator's position within the file. It
returns the current position as a long integer value.
10 rewind() It is used to reset the file position indicator to the beginning of the file. It is
equivalent to calling fseek(file, 0, SEEK_SET). It is commonly used to re-
read a file from the beginning or when you want to start reading or writing
from the beginning of the file again.
2. Using the format “$man 2 system call name”, write the prototypes for the following system calls
A. open( )
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
21
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
B. read( )
#include <unistd.h>
D. lseek()
#include <unistd.h>
E. creat( )
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
F. close( )
#include <unistd.h>
#include <unistd.h>
22
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In lab task
1. Writea UNIX System program that reads file.txt line by line and prints the first 10-digit
number in the given file (digits should be continuous), If not found then print the first 10
characters excluding numbers.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main() {
FILE *file;
char line[MAX_LINE_LENGTH];
int digitCount = 0;
int foundDigit = 0;
printf("%c", line[i]);
digitCount++;
foundDigit = 1;
} else {
// Check if we have found the desired number of digits
if (digitCount == DIGIT_COUNT) {
printf("\n");
fclose(file);
return 0;
}
// Reset the digit count if a non-digit character is encountered
digitCount = 0;
}
}
}
// If no 10-digit number was found, print the first 10 characters excluding numbers
if (!foundDigit) {
rewind(file);
fgets(line, sizeof(line), file);
for (int i = 0; i < DIGIT_COUNT && line[i] != '\0'; i++) {
if (!isdigit(line[i])) {
printf("%c", line[i]);
24
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
2. Writea UNIX System program that saves 10 random numbers to a file, using own “rand.h”
header file which contains your own random ( ) function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_COUNT 10
unsigned int seed = 1;
unsigned int rand() {
seed = (seed * 1103515245 + 12345) & 0xFFFFFFFF;
return seed;
}
int main() {
FILE *file;
int numbers[NUM_COUNT];
return 0;
}
3. Write a UNIX system program that creates a file with a hole in it.
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd;
off_t offset = 1024; // Offset to create the hole
return 0;
}
26
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
POST LAB 2
1. Write commands/code in the space provided for each of the questions below:
a.Use the cut command on the output of a long directory listing in order to display only the file
permissions. Then pipe this output to sort and unique to filter out any double lines. Then use the wc
to count the different permission types in this directory.
Ans
ls -l | cut -d ' ' -f 1 | sort | uniq -c
b. Try ln -s /etc/passwd passwords and check with ls-l. Did you find anything
extra? Ans.
ln -s /etc/passwd passwords
ls -l passwords
After running the ls -l passwords command, we will see the details of the symbolic
link. It should display the link name, the arrow symbol "->", and the target file or
c.Create a new Directory LABTEMP and Copy the files from /var/log into it and display the files
whose first alphabet is consonant that do not begin with uppercase letters that has an extension of
exactly three characters.
Ans.
mkdir LABTEMP
cp /var/log/* LABTEMP/
cd LABTEMP
find . -type f -name '[^AEIOUaeiou[:upper:]]???.*' -printf "%f\n"
Explanation:
mkdir LABTEMP: This command creates a new directory named "LABTEMP" in the current working directory.
cp /var/log/* LABTEMP/: This command copies all files from the "/var/log" directory into the "LABTEMP"
directory.
27
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
find .: Searches for files within the current directory and its subdirectories.
-type f: Filters the search to only include regular files.
-name '[^AEIOUaeiou[:upper:]]???.*': Specifies the pattern for file names that match the criteria:
[^AEIOUaeiou[:upper:]]: Matches any non-vowel consonant or non-uppercase letter.
???: Matches exactly three characters.
.*: Matches any extension after the three characters.
-printf "%f\n": Prints only the file name (excluding the directory path) on separate lines.
After running these commands, you will have the "LABTEMP" directory created and populated with the files
copied from "/var/log." Then, the final command will display the file names that meet the specified criteria.
running?
Ans. uptime -p
usage
Ans. free -h
Hierarchy
Ans
28
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
regular users.
system configuration.
g.Create a file using cat and find the number of lines, words and
characters in it.
29
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Ans.
2. wc my_file.txt
cmp)
Ans.
command?
Ans.
echo "\\"
split)
30
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Ans.
k.What happens when you enter a shell metacharacter * with the echo
command
. Ans.
If the shell has filename expansion (globbing) enabled: If there are files in the
current directory that match the pattern represented by *, the shell will expand *
to the list of matching filenames before passing the expanded list to the echo
command. The echo command will then display each matching filename
separated by spaces. For example, if you have files file1.txt, file2.txt, and
file2.txt file3.txt, and the echo command will display file1.txt file2.txt file3.txt.
If the shell does not have filename expansion (globbing) enabled: If filename
expansion is disabled or if there are no files in the current directory that match
the pattern represented by *, the echo command will treat * as a literal character
and simply display it as part of the output. For example, if there are no files in
the current directory or if there are no files with names starting with *, running
echo * will display * as the output. In summary, the behavior of the echo
expansion is enabled or disabled and whether there are files in the current
31
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
result
existing file
Ans.
c.Redirect standard output and standard error streams for cat command with an example in
one step.
Ans.
example: Let's say we have a file named "example.txt" with the following content:
csharp
Now, let's run the cat command with redirection to save both the output and error messages into a file named
"output.txt":
shell
32
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
b. Zip a group of files (ERROR, newfile, infile, passwd, group) and unzip
them Ans.
zip archive.zip ERROR newfile infile passwd group
N. Create a file called "hello.txt" in your home directory using the command cat -u > hello.txt. Ask
your partner to change into your home directory and run tail -f hello.txt. Now type several lines into
hello.txt. What appears on your partner's screen?
Ans.
If we run the command cat -u > hello.txt, it will create a file named "hello.txt" and allow you to enter
text into it. The -u option is used to disable output buffering. You can type several lines of text into the file and
press Enter after each line.
When your partner changes into your home directory and runs tail -f hello.txt, they will start a continuous display
of the contents of the "hello.txt" file. The tail -f command shows the last few lines of a file and keeps the file open
for real-time updates. Your partner will see the lines you typed into "hello.txt" as you add them, appearing on
their screen as they are written to the file.
Please note that the commands and file operations I described here are based on a typical Linux/Unix
environment. The behavior may vary depending on the operating system and command-line tools being used.
O. Change the umask value and identify the difference with the earlier using
touch, ls –l
Ans.
33
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
The umask value determines the default permissions applied when creating
new files and directories. By default, the umask value is usually set to 022,
which subtracts the permission bits 022 (---w--w--) from the maximum
allowed permissions (777 for directories and 666 for files), resulting in
o change the umask value, you can use the umask command followed by the
desired value. For example, to set the umask value to 077, you would run:
umask 077
Now, let's compare the difference when creating a new file using touch and listing its
Run the following command to create a file called "test.txt" using touch:
touch test.txt
ls -l test.txt
In this case, the default permissions for the file are set to -rw-r--r--, which means the owner has read and write
permissions, while the group and others have only read permissions.
umask 077
34
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
touch newfile.txt
ls -l newfile.txt
diff
P. Save the output of the who command in a file, display it, display lines count on the
terminal.
Ans.
. Run the who command and redirect its output to a file using the > symbol. For example:
This command will execute the who command and save its output in a file called
cat who_output.txt
The cat command will display the contents of the "who_output.txt" file on the terminal.
Show the line count of the file using the wc command with the -l option:
wc -l who_output.txt
The wc -l command will count the number of lines in the "who_output.txt" file and display
35
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Please note that these commands assume a Unix-like environment. If you are using a
q.Two or more commands can be combined, and the aggregate output can send to an output file. How
to perform it. Write a sample command line.
Ans.
The main command line is:
command1 && command2 > output.txt
r. Display all files in the current directory that begins with "a", "b" or "c" and are at least 5 characters
long Ans.
ls -l: This command lists the files and directories in the current directory in long format.
|: The pipe symbol (|) is used to redirect the output of the ls -l command as input to the next command.
grep -E '^[abc].{4,}': The grep command with the -E option enables extended regular expressions. The pattern
'^[abc].{4,}' matches files that begin with "a", "b", or "c" and have at least 5 characters in total. Here's the
.{4,}: Matches any character (except a newline) for at least 4 times, ensuring a total length of at least 5 characters.
The result will be a list of files in the current directory that satisfy the given criteria: they start with "a", "b", or "c"
and have a length of at least 5 characters. The -l option in ls ensures that additional details like permissions, owner,
36
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
S. Display all files in the current directory that begin and with don't end with "x", "y" or
ls -l | grep -E '^[^xyz].*[^xyz]$'
T. Display all files in the current directory that begin with the letter D and have three more
characters.
Ans.
ls -l D??*
Ans:
ls -l > file_list.txt
37
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 3
(PROCESS
API)
Prerequisite:
1.Write brief description and prototypes in the space given below for the following process sub system
call EX:- “$ man system call name”
1. fork( )
The fork() system call creates a new process by duplicating the existing process. The new process, called the child process,
is an identical copy of the parent process, except for a few attributes. After forking, both the parent and child processes
continue execution from the point where fork() was called, but they have different process IDs (PIDs).
Prototype: $ man fork
The getpid() system call returns the process ID (PID) of the calling process. The getppid() system call returns the parent
process ID (PPID) of the calling process.
Prototype: $ man getpid, $ man getppid
The exit() system call terminates the calling process and returns the exit status to the operating system. It
performs necessary cleanup tasks before the process is removed from the system.
38
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
39
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
4. shmget()
The shmget() system call creates a shared memory segment or accesses an existing one. It is used for inter-
process communication, allowing multiple processes to share a common memory area.
Prototype: $ man shmget
5. wait()
The wait() system call suspends the calling process until one of its child processes terminates. It allows the
parent process to wait for the completion of child processes and obtain their exit statuses.
Prototype: $ man wait
6. sleep()
The sleep() system call suspends the execution of the calling process for a specified number of seconds. It is
used to introduce a delay in program execution.
Prototype: $ man sleep
7. exec()
The exec() system call replaces the current process with a new process. It loads a new program into the current
process's memory space and begins its execution. There are multiple variants of the exec() system call, such as execlp(),
execvp(), execv(), execl(), each with different ways of specifying the program to be executed.
Prototype: $ man exec
8. waitpid()
The waitpid() system call suspends the calling process until a specific child process terminates. It provides
more control over which child process to wait for compared to wait().
Prototype: $ man waitpid
These are different variants of the exec() system call that allow the execution of a new program within the
current process. They differ in how the program and its arguments are specified. execlp() and execvp() search for the
program in the directories listed in the PATH environment variable, while execv() and execl() require the full path to the
program.
Prototypes: $ man execlp, $ man execvp, $ man execv, $ man execl
10. _exit ()
The _exit() system call terminates the calling process immediately without performing any cleanup tasks. Unlike
exit(), it does not invoke any registered cleanup functions or flush any buffered I/O.
Prototype: $ man _exit
40
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
11. Opendir()
The opendir() system call opens a directory stream for the specified directory path. It allows reading the contents
of the directory, such as the names of the files and subdirectories within it. It returns a pointer to the directory stream, which
is used for subsequent directory operations.
Prototype: $ man opendir
12. Readdir()
The readdir() system call reads the next entry from the directory stream opened by opendir(). It retrieves
information about the next file or subdirectory within the directory. It returns a pointer to a structure containing the
information, or NULL if the end of the directory stream is reached.
Prototype: $ man readdir
41
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In lab task:
1.write a program for implementing process management using the following system calls of UNIX
operating system: fork, exec, getpid, exit, wait, close.
#include <stdio.h>
#include <unistd.h>
#include <sys/types .h>
#include <sys/wait.h>
int main() {
pid_t pid;
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
return 0;
}
42
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
2.To write a program for implementing Directory management using the following system calls of
UNIX operating system: opendir, readdir.
#include <stdio.h>
#include <dirent.h>
int main() {
DIR *dir;
struct dirent *entry;
dir = opendir(".");
if (dir == NULL) {
perror("opendir");
return 1;
}
closedir(dir);
return 0;
}
43
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
3. T-series creates a text document(song.txt) that contains lyrics of a song. They want to know how many
lines and words are present in the song.txt. They want to utilize Linux directions and system calls to
accomplish their objective. Help T-series to finish their task by utilizing a fork system call. Print the
number of lines in song.txt using the parent process and print the number of words in it using the child
process.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
return lineCount;
}
return wordCount;
}
int main() {
FILE *file;
pid_t pid;
int lineCount, wordCount;
if (file == NULL) {
44
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
perror("fopen");
return 1;
}
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
wordCount = countWords(file);
rewind(file);
lineCount = countLines(file);
wait(NULL);
fclose(file);
return 0;
}
45
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
POST LAB 3
1. Write a C program to create a process in UNIX (using fork ()) and perform redirection.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
int main() {
pid_t pid;
int fd;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
fd = open("output.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) {
perror("open");
return 1;
}
dup2(fd, STDOUT_FILENO);
close(fd);
return 0;
}
46
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid, ppid;
return 0;
}
3. write a program to create child process that sleeps for 5 seconds and after 5 seconds kill the child
process with process id.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int main() {
pid_t pid;
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
sleep(5);
return 0;
} else {
wait(NULL);
kill(pid, SIGKILL);
return 0;
}
48
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 4
(PROCESS
SCHEDULING)
Pre-requisites:
● Knowledge on simple system calls and process scheduling
SCHEDULING FUNCTIONALITY
ALGORITHMS
FCFS is a scheduling algorithm where the processes are executed in
the order they arrive in the ready queue.
The functionality of FCFS is to schedule processes based on their
FCFS
arrival time, executing the first process that arrives first.
When a process completes its execution, the next process in the
queue is selected to run
49
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
SCHEDULING
ALGORITHMS FUNCTIONALITY
Round Robin is a scheduling algorithm where each process is given
a fixed time slice or quantum to execute.
The functionality of Round Robin is to allocate CPU time to each
ROUND ROBIN
process in a round-robin fashion, allowing each process to execute
for a specific time period before switching to the next process.
It ensures fair sharing of the CPU among processes and prevents
starvation.
50
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
51
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In Lab Task:
1. Write a C program to implement FCFS process scheduling algorithm by considering arrival times.
#include <stdio.h>
struct Process {
int pid;
int arrivalTime;
int burstTime;
};
waitingTime[0] = 0;
completionTime[0] = processes[0].burstTime;
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
sjfScheduling(processes, n);
return 0;
}
53
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
2. Write a C program to implement SJF process scheduling algorithm by considering arrival times.
#include <stdio.h>
struct Process {
int pid;
int arrivalTime;
int burstTime;
int waitingTime;
int turnaroundTime;
int completed;
};
if (shortestJob != -1) {
processes[shortestJob].waitingTime = currentTime - processes[shortestJob].arrivalTime;
processes[shortestJob].turnaroundTime = processes[shortestJob].waitingTime +
processes[shortestJob].burstTime;
totalWaitingTime += processes[shortestJob].waitingTime;
totalTurnaroundTime += processes[shortestJob].turnaroundTime;
processes[shortestJob].completed = 1;
completedProcesses++;
currentTime += processes[shortestJob].burstTime;
}
else {
currentTime++;
}
}
int main() {
int n;
printf("Enter the number of processes: ");
scanf("%d", &n);
calculateWaitingTime(processes, n);
return 0;
}
55
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
3. Write a C program to implement Round Robin process scheduling algorithm by considering arrival times
#include <stdio.h>
#include <stdlib.h>
struct Process {
int pid;
int arrivalTime;
int burstTime;
int remainingTime;
int waitingTime;
int turnaroundTime;
};
struct Node {
struct Process* process;
struct Node* next;
};
struct Queue {
struct Node* front;
struct Node* rear;
};
if (queue->rear == NULL) {
queue->front = newNode;
queue->rear = newNode;
}
else {
queue->rear->next = newNode;
queue->rear = newNode;
}
}
queue->front = queue->front->next;
if (queue->front == NULL)
queue->rear = NULL;
free(temp);
56
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
return process;
}
int currentTime = 0;
int completedProcesses = 0;
float totalWaitingTime = 0, totalTurnaroundTime = 0;
if (queue->front == NULL) {
currentTime++;
continue;
}
int main() {
int n;
int timeQuantum;
4.Write a C program to implement Priority process scheduling algorithm by considering arrival times
(Highest Priority First)
#include <stdio.h>
struct Process {
int pid;
int arrivalTime;
int burstTime;
int priority;
int waitingTime;
int turnaroundTime;
};
int main() {
int n;
priorityScheduling(processes, n);
return 0;
}
59
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Post Lab:
1. Write C Program to simulate Multi Level Feedback Queue CPU Scheduling algorithm.
#include <stdio.h>
struct Process {
int pid;
int burstTime;
int remainingTime;
int level;
};
executeProcess(currentProcess, timeQuantum[currentProcess->level]);
}
}
}
}
int main() {
int n;
int numOfLevels;
60
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
return 0;
}
61
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_PROCESSES 10
struct Process {
int pid;
int ticketCount;
};
// Generate random numbers and execute processes based on their probability ranges
srand(time(NULL));
free(probabilityRanges);
}
62
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
int main() {
int n;
int totalTickets;
lotteryScheduling(processes, n, totalTickets);
return 0;
}
63
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 5
(VIRTUALIZING THE CPU AND MEMORY, SHELL
SCRIPTING)
Prerequisite:
● CPU Virtualization
● Virtualizing the Memory
● Concept of Creating simple shell
shell
Copy code
if condition
then
# code to be executed if the condition is true
else
# code to be executed if the condition is false
fi
if-then-elif-fi:
64
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
shell
Copy code
if condition1
then
# code to be executed if condition1 is true
elif condition2
then
# code to be executed if condition2 is true
else
# code to be executed if all conditions are false
fi
65
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Shell arithmetic test conditions Shell scripts can perform arithmetic tests using the (( )) construct.
Arithmetic test conditions include comparisons such as equal to (==), not
equal to (!=), greater than (>), less than (<), etc.
What is one benefit of writing Automation: Shell scripts automate repetitive tasks, reducing manual effort.
shell scripts? Customization: Shell scripts allow customization of commands and utilities
based on specific requirements.
Efficiency: Shell scripts can perform complex operations efficiently and
quickly.
Portability: Shell scripts are portable across different Unix-like operating
systems.
Shell scripts can accept command line arguments provided when running
Command Line
the script.
Arguments
These arguments can be accessed within the script using special variables
like $1, $2, etc., where $1 represents the first argument, $2 represents the
second argument, and so on.
Environmental variables are variables that store information about the
environment in which the shell script is running.
They include variables like PATH, HOME, USER, etc., which hold
Environmental important information used by the shell.
Variables Environmental variables can be accessed within the script using the $
symbol followed by the variable name, such as $PATH, $HOME, $USER,
etc.
Which looping construct can The looping construct "for-do-done" is used to perform an action on listed
be used to perform an action items or iterate over a specified range of values.
on listed items? The loop iterates through each item or value in the list and executes the
specified code block.
Syntax:
looping construct: for-do-done shell
Copy code
for item in list
do
# Code to be executed for each item
done
Exit codes are used to indicate the status of script execution.
When would you By convention, an exit code of 0 indicates successful execution, and non-
want to use an exit zero codes indicate some form of error or failure.
code in your script? Exit codes are useful when scripting to check if a command or script
executed successfully and take appropriate actions based on the exit code.
66
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In Lab Task:
1. Program to demonstrate the Virtualizing the CPU – Time sharing using pre-emptive scheduling.
#include <stdio.h>
#define MAX_PROCESSES 10
struct Process {
int pid;
int burstTime;
int remainingTime;
};
if (currentProcess->remainingTime > 0) {
if (currentProcess->remainingTime <= timeSlice) {
currentTime += currentProcess->remainingTime;
currentProcess->remainingTime = 0;
completedProcesses++;
}
else {
currentTime += timeSlice;
currentProcess->remainingTime -= timeSlice;
}
executeProcess(currentProcess, timeSlice);
}
int main() {
int n;
int timeSlice;
virtualizeCPU(processes, n, timeSlice);
return 0;
}
2. Write a shell script to Display System Information
System information refers to the collection of details and statistics related to a computer system. It
encompasses various aspects such as the hostname, kernel version, operating system, CPU information,
memory usage, disk space, and network configuration. The hostname represents the unique name of the
system within a network. The kernel version indicates the specific version of the operating system's
core. The operating system identifies the software platform running on the system, providing the
foundation for executing programs and managing resources. CPU information includes details about the
processor, such as its model name and architecture. Memory information reveals the current memory
usage, including total available memory and usage statistics. Disk information presents data about the
storage devices connected to the system, including their capacity and usage. Network information
provides an overview of the network interfaces and their configurations, such as IP addresses and
network protocols. Collectively, this system information is crucial for understanding and managing the
resources and capabilities of a computer system.
3. Write a shell script Using Command Substitution, Special and Positional Parameters, Shifting Command
Line Arguments.
The shell script showcases various features and techniques commonly used in shell scripting. It
demonstrates command substitution by assigning the current date to a variable using $(date +%Y-
%m-%d). Special parameters like $0, $#, $$, and $? provide valuable information about the script's
execution, such as the script name, the number of arguments passed, the process ID, and the exit
status of the last command. Positional parameters, accessed through $1, $2, and $@, allow for the
retrieval of command line arguments. Additionally, the script demonstrates the shifting of
command line arguments using the shift command, enabling the repositioning of arguments for
further processing. By combining these techniques, shell scripts gain versatility and the ability to
handle a wide range of tasks efficiently and dynamically.
4.Write a shell script that use until ... do ... done
The until ... do ... done loop is a powerful construct in shell scripting that allows for the repeated execution
of a code block until a specified condition evaluates to true. The loop begins by checking the condition. If the
condition is false, the code block within the do and done statements is executed. Once the code block completes
68
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
execution, the loop checks the condition again. If the condition is still false, the code block is executed again. This
process continues until the condition becomes true, at which point the loop terminates, and the script continues
executing the subsequent statements.
The condition in the until statement can be any valid shell expression or command that evaluates to either true or
false. Typically, the condition involves the use of comparison operators or logical expressions to evaluate variables,
command outputs, or other shell expressions.
Inside the loop, you can include any desired code or commands. This allows for flexibility in performing tasks such
as iterative calculations, file processing, repetitive operations, and more. You can use variables, conditional
statements, arithmetic operations, and function calls within the loop to customize the behavior and functionality of
your script.
It's important to note that the loop will execute at least once, regardless of the initial condition. If the condition is
initially true, the code block will not execute, and the loop will terminate immediately.
The until ... do ... done loop provides a valuable tool for controlling the flow of a shell script based on specific
conditions. It allows for the repeated execution of code until a desired state or condition is reached. By utilizing
this loop construct effectively, you can create robust and dynamic shell scripts to automate tasks, perform
iterative operations, and handle complex logic within your script
#!/bin/bash
rows=5
spaces=$((rows-1))
dots=1
echo ""
69
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
spaces=$((spaces-1))
dots=$((dots+2))
done
do
echo -n "."
done
echo ""
spaces=$((spaces+1))
dots=$((dots-2))
done
In this script, the variable rows represents the number of rows in the diamond pattern. We start by setting the
number of spaces (spaces) to rows - 1 and the number of dots (dots) to 1 for the upper half of the diamond.
The script then uses nested for loops to draw the upper half of the diamond. The outer loop iterates over the rows,
and the inner loops handle the spaces and dots for each row. The number of spaces decreases by 1 in each
iteration, while the number of dots increases by 2.
After drawing the upper half, the script proceeds to draw the lower half of the diamond. It sets the number of
spaces to 1 and decreases the number of dots by 2 in each iteration.
To change the size of the diamond, you can modify the value of the rows variable. The script will adjust the
pattern accordingly.
Save the script to a file, e.g., diamond_pattern.sh, and make it executable using the command chmod +x
diamond_pattern.sh. Then, you can execute the script by running ./diamond_pattern.sh in the terminal.
70
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Post Lab:
1. Write a c program that displays all command line arguments and environment variables.
#include <stdio.h>
#include <stdlib.h>
printf("\nEnvironment variables:\n");
char **env = environ;
while (*env) {
printf("%s\n", *env);
env++;
}
return 0;
}
2. In C Program Memory Layout, we can see various segments involved during the runtime of an application.
Write a program to print the addresses of all the segments and the address of variables residing in their
respective segments.
#include <stdio.h>
#include <stdlib.h>
int global_variable;
int main() {
int local_variable;
static int static_variable;
free(heap_variable);
return 0;
}
3. Write a UNIX system program shell.c -- Accepts user input as a command to be executed. Uses the strtok
library function for parsing command line.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
char command[BUFFER_SIZE];
char *args[BUFFER_SIZE / 2 + 1];
int status;
while (1) {
printf("Shell > ");
fgets(command, BUFFER_SIZE, stdin);
if (pid < 0) {
perror("Fork failed");
exit(EXIT_FAILURE);
} else if (pid == 0) {
execvp(args[0], args);
72
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
perror("Execvp failed");
exit(EXIT_FAILURE);
} else {
return 0;
}
73
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 6
(MEMORY MANAGEMENT & ALLOCATION
TECHNIQUES)
Prerequisite:
● General idea on memory allocation techniques
● malloc(), realloc(), calloc(), free() library functions
● Concept of altering program break
● Basic strategies of managing free space (first-fit , best-fit , worst-fit)
● Concepts of Splitting and coalescing in free space management
Pre-Lab Task:
Memory Fixed Partitioning MFT divides the available memory into fixed-sized partitions or regions.
Technique (MFT) Each partition is allocated to a specific process and remains dedicated to
that process throughout its execution.
74
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Write the functionality, The brk() system call sets the program break, which is the end of the
arguments required, and the process's data segment. It is used to adjust the size of the heap dynamically.
possible return values in
different cases of the The sbrk() system call is used to adjust the program break by a specified
following system calls brk() increment. It is often used to request additional memory from the operating
,sbrk(). system.
75
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In Lab Task:
1. write a C program to implement Memory Management concept using the technique best fit,
worst fit and first fit algorithms.
#include <stdio.h>
#include <stdlib.h>
// Function prototypes
void initializeMemory(MemoryBlock *memory);
void displayMemory(MemoryBlock *memory);
void bestFit(MemoryBlock *memory, int process_size);
void worstFit(MemoryBlock *memory, int process_size);
void firstFit(MemoryBlock *memory, int process_size);
int main() {
MemoryBlock memory[MAX_MEMORY_SIZE];
int choice, process_size;
initializeMemory(memory);
while (1) {
printf("\n------ MENU ------\n");
printf("1. Display Memory\n");
printf("2. Best Fit\n");
76
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
switch (choice) {
case 1:
displayMemory(memory);
break;
case 2:
printf("Enter the process size: ");
scanf("%d", &process_size);
bestFit(memory, process_size);
break;
case 3:
printf("Enter the process size: ");
scanf("%d", &process_size);
worstFit(memory, process_size);
break;
case 4:
printf("Enter the process size: ");
scanf("%d", &process_size);
firstFit(memory, process_size);
break;
case 5:
exit(0);
default:
printf("Invalid choice!\n");
}
}
return 0;
}
77
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
if (best_index == -1) {
printf("No suitable memory block found for the process.\n");
return;
}
78
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
memory[best_index].allocated = 1;
printf("Memory block allocated successfully.\n");
}
if (worst_index == -1) {
printf("No suitable memory block found for the process.\n");
return;
}
memory[worst_index].allocated = 1;
printf("Memory block allocated successfully.\n");
}
#include <stdio.h>
#include <stdlib.h>
#define PAGE_SIZE 4
#define MEMORY_SIZE 16
typedef struct {
int page_number;
int frame_number;
int valid;
} PageTableEntry;
int main() {
int num_pages, logical_address;
while (1) {
printf("\nEnter the logical address (-1 to exit): ");
scanf("%d", &logical_address);
if (logical_address == -1)
break;
free(page_table);
return 0;
}
if (page_table[page_number].valid) {
int physical_address = (page_table[page_number].frame_number * PAGE_SIZE) + offset;
printf("Logical address %d maps to physical address %d\n", logical_address, physical_address);
} else {
printf("Page fault occurred for logical address %d\n", logical_address);
if (free_frame != -1) {
// Assign the free frame to the page
page_table[page_number].frame_number = free_frame;
page_table[page_number].valid = 1;
81
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Post Lab:
1. Demonstrate Allocating Memory on the Heap with your own implementation of malloc() and
free() using free list and UNIX system calls.
Implementing your own version of malloc() and free() using a free list and UNIX system calls
can be quite complex and beyond the scope of a simple response. However, I can provide you with a high-level
overview of the steps involved and the concepts you'll need to consider. Keep in mind that this is a simplified
explanation and doesn't cover all the intricacies and optimizations of a complete memory allocator
implementation.
Here's an outline of the steps involved in implementing your own memory allocator using a free list and UNIX
system calls:
1.Allocate a large block of memory: Use a UNIX system call like sbrk() or mmap() to allocate a large block of
memory from the operating system. This block will serve as the heap for your memory allocator.
2.Define a free list data structure: Create a data structure (e.g., linked list) to manage the free blocks of memory.
Each free block should contain information such as the size of the block and a pointer to the next free block.
3.Initialize the free list: When you allocate the initial heap, add a single free block to the free list, representing the
entire heap.
4.Implement malloc(): When the user calls malloc(size), your allocator should search the free list for a free block
that is large enough to satisfy the allocation request. If a suitable block is found, split it into two parts: one to
fulfill the requested size and the other as a new free block. Update the free list accordingly, and return a pointer to
the allocated memory.
5.Implement free(): When the user calls free(ptr), your allocator should take the pointer ptr and mark the
corresponding memory block as free. You need to merge adjacent free blocks to prevent fragmentation and
maintain a consolidated free list.
6.Handle edge cases: Consider special cases, such as merging free blocks during allocation or deallocation,
handling invalid inputs, and optimizing memory utilization (e.g., coalescing adjacent free blocks).
Remember that implementing a complete and efficient memory allocator is a complex task that requires careful
consideration of various factors, such as memory alignment, synchronization, thread safety, and performance
optimization. It's recommended to study existing memory allocators like the GNU C Library's malloc()
implementation (e.g., dlmalloc) to understand advanced techniques and best practices.
82
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
2. Develop a program to illustrate the effect of free() on the program break. This program
allocates multiple blocks of memory and then frees some or all of them, depending on its
(optional) command-line arguments. The first two command-line arguments specify the
number and size of blocks to allocate. The third command-line argument specifies the loop step
unit to be used when freeing memory blocks. If we specify 1 here (which is also the default if
this argument is omitted), then the program frees every memory block; if 2, then every second
allocated block; and so on. The fourth and fifth command-line arguments specify the range of
blocks that we wish to free. If these arguments are omitted, then all allocated blocks (in steps
given by the third command-line argument) are freed. Find the present address of the program
break using sbrk() and expand the program break by the size 1000000 using brk().
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void printProgramBreak() {
void *current_break = sbrk(0);
printf("Program Break: %p\n", current_break);
}
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Insufficient command-line arguments!\n");
printf("Usage: ./program <num_blocks> <block_size> [step_unit] [start_block] [end_block]\n");
return 1;
}
int num_blocks = atoi(argv[1]);
int block_size = atoi(argv[2]);
int step_unit = (argc >= 4) ? atoi(argv[3]) : 1;
int start_block = (argc >= 5) ? atoi(argv[4]) : 0;
int end_block = (argc >= 6) ? atoi(argv[5]) : num_blocks - 1;
printProgramBreak();
printf("Memory allocated.\n");
83
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
printProgramBreak();
return 0;
}
84
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 7
(PAGE REPLACEMENT TECHNIQUES)
Prerequisite:
● Accessing of memory with paging.
● Page replacement techniques.
Pre-Lab Task:
85
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
A page fault occurs when a program references a page that is not present in
the main memory.
Concept of Page When a page fault occurs, the operating system needs to fetch the required
Fault page from secondary storage (disk) into a free page frame in the main
memory.
The main functionality of handling page faults is to ensure that all
necessary pages are loaded into memory when needed, thereby minimizing
the impact on the program's execution.
Page faults are an essential part of virtual memory systems and are
managed through page replacement algorithms to optimize memory usage
and minimize the frequency of page faults.
86
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In - Lab Task:
#include <stdio.h>
#define MAX_FRAMES 3
#define MAX_PAGES 12
int findPageToReplace(int pages[], int pageCount, int frames[], int frameCount, int currentIndex) {
int victim = currentIndex;
while (1) {
victim = (victim + 1) % pageCount;
if (!isPageInFrames(pages[victim], frames, frameCount)) {
return victim;
}
}
}
printf("Simulation started:\n");
pageFaults++;
printf("Page fault occurred.\n");
} else {
printf("No page fault.\n");
}
printFrames(frames, frameCount);
}
printf("Simulation completed.\n");
printf("Total page faults: %d\n", pageFaults);
}
int main() {
int pages[MAX_PAGES] = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};
int frames[MAX_FRAMES] = {-1, -1, -1};
return 0;
}
#include <stdio.h>
#define MAX_FRAMES 3
#define MAX_PAGES 12
int findPageToReplace(int pages[], int pageCount, int frames[], int frameCount, int currentIndex) {
int victim = currentIndex;
while (1) {
victim = (victim + 1) % pageCount;
if (!isPageInFrames(pages[victim], frames, frameCount)) {
return victim;
}
}
}
printf("Simulation started:\n");
printf("Simulation completed.\n");
printf("Total page faults: %d\n", pageFaults);
}
int main() {
int pages[MAX_PAGES] = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};
int frames[MAX_FRAMES] = {-1, -1, -1};
return 0;
}
89
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Post Lab:
#include <stdio.h>
#define MAX_FRAMES 3
#define MAX_PAGES 12
return lruIndex;
}
int pageFaults = 0;
int recent[MAX_PAGES] = {0};
int time = 1;
printf("Simulation started:\n");
printf("Simulation completed.\n");
printf("Total page faults: %d\n", pageFaults);
}
int main() {
int pages[MAX_PAGES] = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};
int frames[MAX_FRAMES] = {-1, -1, -1};
return 0;
}
#include <stdio.h>
#include <stdbool.h>
#define MAX_FRAMES 3
#define MAX_PAGES 12
void printFrames(int frames[], int frameCount) {
printf("Frames: ");
for (int i = 0; i < frameCount; i++) {
if (frames[i] == -1) {
printf(" - ");
91
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
} else {
printf(" %d ", frames[i]);
}
}
printf("\n");
}
int findLFUPage(int pages[], int pageCount, int frames[], int frameCount, int frequency[]) {
int lfuIndex = 0;
int minFrequency = frequency[frames[0]];
return lfuIndex;
}
printf("Simulation started:\n");
92
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
updatePageFrequency(pages[i], frequency);
printFrames(frames, frameCount);
}
printf("Simulation completed.\n");
printf("Total page faults: %d\n", pageFaults);
}
int main() {
int pages[MAX_PAGES] = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};
int frames[MAX_FRAMES] = {-1, -1, -1};
return 0;
}
93
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 8
(FILE ORGANIZATION)
Prerequisite:
● Basic functionality of Files.
● Complete idea of file structure, file types, file access mechanisms.
Pre-Lab Task:
File Organization terms FUNCTIONALITY
File structure
Link()
Ordinary files
Chown()
94
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Directory files
Chgrp()
inode
Chmod()
Stat(), lstat()
truncate()
95
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In lab task
96
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
97
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
98
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
99
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
100
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
101
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
102
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
3. Directories are also files, and they can be opened, read, and written in the
same way as regular files. Write a system program that lists only directories -
Uses S_IFMT and S_ISDIR macros.
103
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
104
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 9
(DISK SHEDULING ALGORITHMS)
Prerequisite:
● Basic functionality of Disk Scheduling Algorithms.
● Complete idea of FCFS, SCAN and C-SCAN.
Pre-Lab Task:
Disk Scheduling Parameters FUNCTIONALITY
Seek time
Rotational Latency
105
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Transfer time
106
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In Lab Task:
107
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
108
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
109
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
110
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
111
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
112
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Post Lab:
113
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
114
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
115
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
116
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
117
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 10
(INTER PROCESS COMMUNICATION)
Prerequisite:
● Basic functionality of IPC.
● Complete idea of different methods like shmget, shmat, msgget, msgsnd, msgctl
● Basic functionality of pipes, sockets, RPC
Pre-Lab Task:
IPC terms FUNCTIONALITY
Pipes
Shared memory
118
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Semaphores
Signals
Message Queues
119
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
UNIX Domain
Sockets
RPC
In lab task
120
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
121
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
122
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
123
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
124
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
125
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
126
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
127
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
128
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
129
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 11
(DEADLOCKS & PTHREADS)
Prerequisite:
● Basic functionality of Deadlocks.
● Pthreads
● Complete idea of Deadlock avoidance and Prevention
● Semaphores, Mutex
Pre-Lab Task:
Deadlock Conditions FUNCTIONALITY
Mutual Exclusion
130
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
No Preemption
Detaching a Thread
Terminating a Thread
Circular Wait
Cancelling a Thread
Comparing Thread
IDs
Binary Semaphores
Condition Variables
Counting
Semaphores
Mutex
Busy Waiting
131
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In Lab Task:
132
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
133
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
2. Pthreads have nondeterministic start-up and uncontrolled scheduling. It gets worse while Shared Data –to an
increment problem that uses the exchange primitive to build a lock.
134
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
135
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Post Lab:
1. Write a "hello world" pthreads program that demonstrates thread creation and termination.
136
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
2. Show how two locks can cause problems (deadlock) and makes it more clearly via printing exactly what
is happening. two-locks-print.c.
137
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
138
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
WEEK - 9
(CONCURRENCY)
Prerequisite:
● Basic idea on concurrent data structures Linked lists and queues
● Basic idea on concurrent hash tables
● Producer and consumer problems
● Dining-Philosophers problem
Pre-Lab Task:
Concept FUNCTIONALITY
Concurrency
Semaphores
139
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Concept FUNCTIONALITY
Dining-Philosophers
problem
Producer –
Consumer problem
140
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
In Lab Task:
141
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
142
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
143
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
144
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
145
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Post Lab:
146
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
147
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
3. Write a Unix System program to make A Parent Waiting for Its Child using semaphores.
4. Demonstrate simple child/parent signaling example (parent Waiting for Child) and develop a more efficient
signaling via condition variables.
148
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
149
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 1
Understand and use essential commands, regular expressions to analyse text, command-line
environments, and Access remote systems,
o Access a shell prompt and issue commands with correct syntax
o Use input-output redirection (>, >>, |, 2>, etc)
o Use grep and regular expressions to analyse text
o Access remote systems using ssh
o Log in and switch users in multi-user targets
Write commands/Command Line/code for some of the sub-questions in the space provided to each
of the main topics given below:
1) man - an interface to the system reference manuals
Give Description for the following options
a) man -K
b) man -f
c) man -l
d) man -w
2) Directories
a) make a directory
3) Users
a) Display the terminal name we are logged on to
b) list the information for only the user running the command
c) show the systems current time and low long it has been up for
d) name of the real use who logged into the system
150
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
4) System Information
a) see basic info about the system & kernel
d) change hostname
c) see the path the command will execute if run with absolute path
b) -a (show hidden)
c) -l (detailed)
8) Input/output Redirection
a) Redirect standard output [1] (override the file if it exist)
b) Append contend
9) Regular Expressions - The grep command -> grep, egrep, fgrep - print lines that match patterns
Give Description for the following options of grep command.
a) -E, --extended-regexp
b) -i, --ignore-case
c) -v, --invert-match
10) Create a file with name “patterns.txt” with the following text and write command line for given questions.
hello linux academy
linuxacademy hello world
hello world linuxacademy
linuxacademy
linuxacademy
linuxacademy
#linuxacademy
LinuxAcademy
aaaaaaaaaaa
a{1,}
12312
3
lionuxacademy
b) See all lines that not start by '#' with ^ in front of pattern
b) SSH config file: Explore and write Common SSH Configuration Options
152
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
153
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
c) download files
d) upload files
a) bash profile is a customization scrip for login shell, it execute when you login in a shell
a) Write the path of the file for: global profile, execute for all users
154
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 2
Understand and use essential tools for handling files, directories, and documentation
o Archive, compress, unpack, and uncompress files using tar, star, gzip, and bzip2
o Create and edit text files
o Create, delete, copy, and move files and directories
o Create hard and soft links
o List, set, and change standard ugo/rwx permissions
o Locate, read, and use system documentation including man, info, and files in /usr/share/doc
Write commands/Command Line/code for some of the sub-questions in the space provided to each
of the main topics given below:
1. Archive, Compress, Unpack and Uncompress files using tar, star, gzip and bzip2
a) create an archive
b)see files inside an archive.tar
c) once is in tar format it can be compressed
d)Create a compressed tar archive
e)Extract a compressed tar archive
f) compress and archive in one command
g) uncompress archive step by step
h)uncompress in one command
i) see the difference between files in tar and current directory
j) gzip command Create a compressed file
k) gzip command Decompress a file
l) Create compressed tar archive using with bzip2
m) Extract a compressed tar archive with bzip2
n) Combining individual files in a compressed archive using zip
o) Combining complete folders in a compressed archive using zip
p) Decompress and extract an archive using unzip
q) Show all files of an archive using unzip
r) List the commands with options to view compressed files
2. start utility
a) create archive
b)extract archive, it doesn't override already existing files
c) extract one file of archive
d)Create an archive retaining SELinux context
11. Review the following commands and give a command line for each.
a) cat (1) - concatenate files and print on the standard output
b) less (1) - opposite of more
c) more (1p) - display files on a page-by-page basis
d) head (1) - output the first part of files
e) tail (1) - output the last part of files
f) sort (1) - sort lines of text files
g) wc (1p) - word, line, and byte or character count
h) grep (1) - print lines matching a pattern
i) sed (1) - stream editor for filtering and transforming text
j) uniq (1) - report or omit repeated lines
k) diff (1) - compare files line by line
l) paste (1) - merge lines of files
m) touch (1) - change file timestamps
n) cp (1) - copy files and directories
12. Linux have 2 types of links: symbolic and hard
a) Create hard link for a file
b)Create soft link to a given file (or directory)
c) delete/remove symbolic link
17. Locate, Read and Use System Documentation with man, info and
/usr/share/doc apropos command
apropos command is used to search the manual page names and descriptions
a) search manual pages of passwd command
b)if retuns nothing, you need to index man pages with
c) consult man page in section 5 of passwd
18. info command- info is gnu information utility
a) get information of info
b)info pages are locate in
c) how to navigate
d)apropos in info
If a program doesn't have man or info pages, use --help or -h. Also, you can browse documentation in
/usr/share/doc/
19. locate command - locate is used to search documentation, executables, etc
a) search for passwd
b)update locate db
20. which command - The 'which' program shows the full path of (shell) commands
a) search for passwd executable
21. whatis command - whatis command is used to locate the binary, source, and manual page files for a
command
a) search for passwd
22. whereis command - whereis - locate the binary, source, and manual page files for a command
a) search for passwd
23. Enable automatic update of the locate database on RHEL 8 using systemd timer
e)find all files that have been modified within the last three days
f) see stat of file
g) find files own by specific user
h)get uid
i) find files by uid
j) find only files that own by specific user
k) find only files that own by specific user and execute one command
26. Getting Package Related Information
a) find out what package (in the repo) provides a file or package.
b) List Files package provides
c) Find manual page for package (-d)
d) Find the full package name use rpm, locate, and grep.
27. Copy /etc/fstab to /var/tmp name admin, the user1 could read, write and modify it, while user2
without any permission.
28. Locate all files owned by user Eric and copy all those files under /root/Eric-files
29. Find string empty in /usr/share/dict/words and put into /root/emptyword.
30. Change user krish user id from 1200 to 1284.
31. Create group named newgroup with GID 3099
Write commands/Command Line/code for the collection of given tasks/labs in the space provided.
Task 1 :
Find all setuid files on the system and save the list
Task 2 :
Find all log messages in /var/log/messages that contain "ACPI", and export them to a file called /root/logs. Then
archive all of /var/log and save it to /tmp/log_archive.tgz
Task 3 :
Create tar files compressed with gzip and bzip2 of /home and extract them
Task 4 :Create an empty file hard1 under /tmp and display its attributes. Create hard links hard2 and hard3. Edit
hard2 and observe the attributes. Remove hard1 and hard3 and list the attributes again
Task 5 :Create an empty file soft1 under /root pointing to /tmp/hard2. Edit soft1 and list the attributes after
editing. Remove hard2 and then list soft1
Task 6 :Create a file perm_file1 with read permissions for owner, group and other. Add an execute bit for the
owner and a write bit for group and public. Revoke the write bit from public and assign read, write, and execute
bits to the three user categories at the same time. Revoke write from the owning group and revoke write and
execute bits from public
158
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 3
159
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 4
Operate running systems, including booting into different run levels, identifying processes, starting
and stopping virtual machines, and controlling services
o Boot, reboot, and shut down a system normally
o Boot systems into different targets manually
o Interrupt the boot process in order to gain access to a system
o Identify CPU/memory intensive processes and kill processes
o Adjust process scheduling
o Manage tuning profiles
o Locate and interpret system log files and journals
o Preserve system journals
o Start, stop, and check the status of network services
o Securely transfer files between systems
Write commands/Command Line/code for the few the sub-questions in the space provided for each of
the topics given below:
1. Boot, Reboot and Shutdown a
System Reboot system
a) reboot with systemd
2. Shutdown system
a) use shutdown to reboot in 5 minutes
b) shutdown immediately
c) stop all services with systemctl
d) power off with systemctl
f) enter the linux command to specify the kernel and root directory.
This can take some trial and error and using tab will help
g) specify the RAM disk command and file location to load into memory
h) boot the machine
6. Reinstalling GRUB2
a) see the config files and remove
b) reinstall grub2
c) attempt to re-created the grub.cfg file
7. Modify GRUB Timeout
a) edit config file
b) rebuild grub configuration
8. Modify GRUB Boot Order
a) see what GRUB is botting into
b) see details
c) set default kernel to 1
9. Resetting the Root User Password
a) we can update the password without seeing it
b) interact with GRUB as shown above. Find boot string that starts with
linux16 and append or
c) append rd.break. This interrupts the boot sequence before the root
filesystem is mounted
d) confirm presence of root filesystem
e) enters emergency mode and remount root file system in read/write mode
f) change root filesystem
g) enter a new password
h) create an empty hidden file called .autorelabel at the root of the
directory tree to instruct the system to perform SELinux relabelling
i) we can run another command at the emergency prompt
10. Linux Kernel
a) determine the Kernel version
b) see available kernels
c) view currently loaded modules
d) see detail about a module
e) see info about kernel
f) see information about a module
g) change a default module
11. systemd
a) see dependencies of a unit
b) see current target
12. Units
a) list all known units and their status
b) see units of type socket
c) see loaded and active targets
13. Targets are logical collection of units. They are a special systemd unit type with the .target
file extension.
a) list all service units
b) list all units of type socket
c) lit unit files
d) check the status of atd
e) list dependencies
f) show details for the atd service
g) view time spent by each task during the boot process
161
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Write commands/Command Line/code for the collection of given tasks/labs in the space provided.
Operate running systems
163
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Task 1 :
Modify the GRUB timeout and make it 1 second instead of 5 seconds
Task 2 :
Terminate the boot process at an early stage to access a debug shell to reset the root password
Task 3 :
Download the latest available kernel packages from the Red Hat Customer Portal and install them
Task 4 :
Install the tuned service, start it and enable it for auto-restart upon reboot. Display all available profiles and the
current active profile. Switch to one of the available profiles and confirm. Determine the recommended profile for
the system and switch to it. Deactive tuning and reactivate it
Task 5:
Launch the command dd if=/dev/zero of=/dev/null three times as a background job. Increase the priority of one of
these ps Change the priority of the same process again, but this time use the value -15. Observe the difference. Kill
all the dd processes you just started
Task 6 :
Configure the journal to be persistent across system reboots. Make a configuration file that writes all messages with
an info priority to the file /var/log/messages.info. Configure logrotate to keep ten old versions of log files
Task 7:
Copy the /etc/hosts file to the /tmp direcotry on server2 using scp command. Try to connect to server2 as user root
and copy the /etc/passwd file to you home directory
Task 8 :
Donwload and install the apache web service. try to configure apache to log error messages through syslog using the
facility local1 Create a rule that send all messages that it receives from local1 (That used above) facility to
/var/log/httpd-error.log
verify the last changed by accessing a page that does not exist
164
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 5
Write commands/Command Line/code for some of the sub-questions in the space provided to each of
the main topics given below:
165
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
6. Add New Partitions and Logical Volumes and Swap to a System Non-Destructively
Add swap space
a) see current memory/swap
b) create lvm partition for swap
c) create swap signature
d) activate swap
e) deactivate swap
f) add swap to /etc/fstab file
g) mount swap from fstab
h) see swap status
7. XFS
a) show file system utilization
b) calculate disk usage of directories and file systems
c) displays block device attributes
d) list all mounted file systems in tree form
e) determine UUID of file system
f) determine the label set
8. Label a file system:
a) if we wanted to check changes in the fstab file:
9. Access Control Lists
a) see the ACLs for the file
10. Changing ACLs:
a) Prevent a user from accessing a file
b) see the changes on the file
c) to revet the changes
d) give a user permissions
e) remove all acls from a directory
f) set a default acl for newly created files
g) remove default in current directory
Write commands/Command Line/code for the collection of given tasks/labs in the space provided.
Task 1 :
Create a 2 GB gpt partition and format the partition with xfs and mount the device persistently
Task 2 :
Assign partition type "msdos" to /dev/sdc for using it as an MBR disk. Create and confirm a 100MB
primary partition on the diskTask 3 :
Delete the sdb1 partition that was created in Task1 above
Task 4 :
Initialise one partition sdb1 (90MB) and one disk sdc (250MB) for use in LVM. Create a volume group
called vgbook and add both physical volumes to it. Use the PE size of 16MB and list and display the
166
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Task 5:
Create two logical volumes, lvol1 and lvbook1, in the vgbook volume group. Use 120MB for lvol0 and
192MB for lvbook1. Display the details of the volume group and the logical volumes
Task 6 :
Add another partition sdb2 of size 158MB to vgbook to increase the pool of allocatable space. Initialise
the new partition prior to adding it to the volume group. Increase the size of lvbook1 to 336MB. Display
the basic information for the physical volumes, volume group, and logical volume
Task 7 :
Rename lvol0 to lvbook2. Decrease the size of lvbook2 to 50MB using the lvreduce command and then
add 32MB with the lvresize command. Remove both logical volumes. Display the summary for the
volume groups, logical volumes, and physical volumes
Task 8 :
Uninitialise all three physical volumes - sdb1, sdb2, and sdb - by deleting the LVM structural information
from them. Use the pvs command for confirmation. Remove the partitions from the sdd disk and verify
that all disks are now in their original raw state
Task 9 :
Create a new logical volume (LV-A) with a size of 30 extents that belongs to the volume group VG-A
(with a PE size of 32M). After creating the volume, configure the server to mount it persistently on /mnt
Task 10 :
Create 1 swap area in a new 40MB partition called sdc3 using the mkswap command. Create another swap
area in a 140MB logical volume called swapvol in vgfs. Add their entries to the /etc/fstab file for
persistence. Use the UUID and priority 1 for the partition swap and the device file and priority 2 for the
logical volume swap. Activate them and use appropriate tools to validate the activation
167
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 6
Create and configure file systems and file system attributes, such as permissions, encryption, access
control lists, and network file systems
o Create, mount, unmount, and use vfat, ext4, and xfs file systems
o Mount and unmount network file systems using NFS
o Extend existing logical volumes
o Create and configure set-GID directories for collaboration
o Configure disk compression
o Manage layered storage
o Diagnose and correct file permission problems
Write commands/Command Line/code for some of the sub-questions in the space provided to each of
the main topics given below:
1. Create, Mount, Unmount and Use VFAT, EXT4 and XFS File
Systems Create a partition
a) partitioning disk an create a primary partition
b) format to vfat
c) mount filesystem
d) see active mount points
e) edit fstab to make change persistent
f) example of mount for vfat filesystem
g) force create filesystem
2. Repartitioning the same disk
a) first umount
b) delete partition. press 'd' to delete. press 'n' to create a new partition an leave defaults
c) format to ext4
d) mount filesystem
e) edit fstab to make change persistent
f) example of mount for vfat filesystem
3. Check filesystem and repair any issue
a) for vfat and ext filesystems exixts fsck command
b) check vfat filesystem
c) check ext4 filesystem. first you need to umount
d) for ext filesystems you don't need to specify the filesystem in fsck
command
4. See details about filesystem
a) see information about filesystem
b) see uuid
c) set label
5. xfs troubleshooting
a) see info about xfs filesystem
b) set label
c) repair xfs filesystem
168
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
169
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Write commands/Command Line/code for the collection of given tasks/labs in the space provided.
Task 1 :
Create 2x100MB partitions on the /dev/sdb disk, initialise them separately with the Ext4 and XFS file system types
create mount points called /ext4fs and /xfs1
attach them to the directory structure, verify their availability and usage
mount them persistantly using their UUIDS
Task 2 :
Create a volume group called vgfs comprised of a 160MB physical volume created in a partition on the /dev/sdb
disk. The PE size for the volume group should be set at 16MB. Create 2 logical volumes called ext4vol and xfsvol
of size 80MB each and initialise them with the Ext4 and XFS file system types. Ensure that both file systems are
persistently defined using their logical volume device filenames. Create mount points /ext4fs2 and /xfsfs2, mount
the file systems, and verify their availability and usage
Task 3 :
Grow the size of the vgfs volume group that was created above by adding another disk to it. Extend the ext4vol
logical volume along with the file system it contains by 40MB
Task 4 :
Create a directory called /common and export it to server in read/write mode. Ensure that NFS traffic is allowed
through the firewall. Confirm the export
Task 5 :
Mount the /common that exported in task 4 . Create a mount point called /local. Add the remote share to the file
system table for persistence. Create a test file in the mount point and confirm the file creation on the NFS
server
Task 6 :
Create users user100, user200 and group sgrp with GID 9999. add user100 and user200 to this group. Create a
directory /sdir with ownership and owning groups belong to root and sgrp, and set the setgid bit on /sdir
Task 7:
Create a file under /tmp as user100 and try to delete it as user200. Unset the sticky bit on /tmp and try to erase the
file again. Restore the sticky bit on /tmp
Automount
Task 1 :
Configure a direct map to automount the NFS share /common that is available from server2. Install the relevant
software, create a local mount point /autodir, and set up AutoFS maps to support the automatic mounting. Note that
/common is already mounted on the /local mount point on server1 via fstab. Ensure there is no conflict in
configuration or functionality between the 2
Task 2:
On server1 (NFS server), create a user account called user30 with UID 3000. Add the /home directory to the list of
NFS shares so that it becomes available for remote mount. On server2 (NFS client), create a user account called
user30 with UID 3000, base directory /nfshome, and no user home directory. establish an indirect map to automount
the remote home directory of user30 under /nfshome. Observe that the home directory of user30 is automounted
under /nfshome when you sign in as user30
Task 3 :
Configura Autofs
All Ldapuser2 home directory is exported via NFS, which is available on
classroom.example.com (172.25.254.254) and your NFS-exports directory is /home/guests for
170
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Ldapuser2,
Ldapuser2's home directory is classroom.example.com:/home/guests/ldapuse2
171
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Task 2 :
Delete the vdo-vol1 volume that was created above and confirm the removal. Create a VDO volume called vdo1 of
logical size 16GB on the sdc disk. Initialise the volume with the XFS file system type, define it for persistence
using its device files, create a mount point called /xfsvdo1, attach it to the directory structure, and verify its
availability and usage
Task 3 :
Install the Stratis software packages, start the Stratis service, and mark it for autostart on subsequent system reboots
Task 4 :
Create a Stratis pool called strpool and a file system strfs2 by reusing the 1GB sdb disk. Display information about
the pool, file system, and device used. Expand the pool to include another 1GB disk sdc and confirm
Task 5 :
Destroy the Stratis file system and the pool that was created, expanded in the above tasks. Verify the deletion with
appropriate commands
Task 6 :
Create a new STRATIS volume according to the following requirements:
The volume is named 'stratisfs' belongs to 'stratispool'
The volume must be mounted permanent under '/stratisvolume'
Copy all the files from '/var/log/audit/' and subdirectories to /stratisvolume
Take a snapshot of stratisfs named stratissnap.
172
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 7
Deploy, configure, and maintain systems, including software installation, update, and core services
o Schedule tasks using at and cron
o Start and stop services and configure services to start automatically at boot
o Configure systems to boot into a specific target automatically
o Configure time service clients
o Install and update software packages from Red Hat Network, a remote repository, or from
the local file system
o Work with package module streams
o Modify the system bootloader
Write commands/Command Line/code for some of the sub-questions in the space provided to each
of the main topics given below:
3. Start and stop services and configure services to start automatically at boot
a) To check the status of a service:
b) To start a service:
c) To stop a service:
d) To make a service reload its configuration:
e) To make a service reload its configuration or restart if it can't reload:
f) To make a service start on boot:
g) To stop a service starting on boot:
h) To check if a service is enabled:
i) To check if a service has failed:
j) To view the configuration file for a service:
k) To view the dependencies for a service:
l) To stop a service from being run by anyone but the system and from being started on boot:
m) To remove a mask:
4. Configure systems to boot into a specific target automatically
a) To get the default target:
b) To list available targets:
c) To change the default target:
173
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
6. Install and update software packages from Red Hat Network, a remote repository, or from the
local file system
a) An RPM package name follows the below format:
b) subscription-manager command can be used to link a Red Hat subscription to a system.
c) The dnf command is the front-end to rpm and is the preferred tool for package management. The
yum command has been superseded by dnf in RHEL 8. It requires that the system has access to a
software repository. The primary benefit of dnf is that it automatically resolves dependencies by
downloading and installing any additional required packages.To list enabled and disabled
repositories:
d) To list enabled and disabled repositories:
e) To search for a package:
f) To view more information about a particular package:
g) To install a package:
h) To remove a package:
i) To find a package from a file:To install a package locally:
j) To view available groups:To install a group (e.g. System Tools):
k) To remove a group (e.g. System Tools):
l) To see the history of installations using dnf:
m) To undo a particular installation (e.g. ID=22):
n) To redo a particular installation (e.g. ID=22):
o) To add a repository using the dnf config manager:
p) To enable a repository using the dnf config manager:
q) To disable a repository using the dnf config manager:
r) To create a repository:
Write commands/Command Line/code for the collection of given tasks/labs in the space provided.
Task 1 :
As Bob, create a once-off job that creates a file called /testresults/Hello.sh containing the text "Hello World. This is
Admin." in 2 days later
Task 2:
Set the system time zone and configure the system to use NTP
Task 3 :
Create a periodic job that appends the current date to the file ~/tracking every 5 minutes every Sunday and
Wednesday between the hours of 3am and 4am. Remove the ability of bob to create cron jobs
Task 4 :
Create a daily cron job at 4:27PM for the Derek user that runs cat /etc/redhat-release and redirects the output to
/home/derek/release
Task 5 :
Submit a job as user100 to run the date command at 11:30pm on March 31, 2022, and have the output and any error
messages generated redirected to /tmp/date.out. List the submitted job and then remove it
Task 6 :
Access the repositories that are available on the RHEL 8 image. Create a definition file for the repositories and
confirm
Task 7 :
Verify the integrity and authenticity of a package called dcraw located in the /mnt/AppStream/Packages directory on
the installation image and then install it. Display basic information about the package, show files it contains, list
documentation files, verify the package attributes and remove the package
Task 8 :
Determine if the cifs-utils package is installed and if it is available for installation. Display its information before
installing it. Install the package and display its information again. Remove the package along with its dependencies
and confirm the removal
Task 9 :
Perform management operations on a package group called system tools. Determine if this group is already installed
and if it is available for installation. List the packages it contains and install it. Remove the group along with its
dependencies and confirm the removal
Task 10 :
Perform management operations on a module called postgresql. Determine if this module is already installed and if
it is available for installation. Show its information and install the default profile for stream 10. Remove the module
profile along with any dependencies and confirm its removal
175
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 8
Write commands/Command Line/code for some of the sub-questions in the space provided to each of the
main topics given below:
Write commands/Command Line/code for the collection of given tasks/labs in the space provided.
Task 1 :
Create a connection profile for the new network interface on server using a text editing tool. Assign the IP
172.10.10.110/24 with gateway 172.10.10.1 and set it to autoactivate at system reboots. Deactivate and reactive this
interface at the command prompt
Task 2 :
Create a connection profile using the nmcli command for the new network interface that was added to server2.
Assign the IP 172.10.10.120/24 with gateway 172.10.10.1, and set it to autoactivate at system reboot. Deactivate
and reactivate this interface at the command prompt
Task 3 :
Update the /etc/hosts file on both server1 and server2. Add the IP addresses assigned to both connections and map
them to hostnames. Test connectivity from server to client and from client to server using their IP addresses and
then their hostnames
Task 4 :
Determine the current active zone. Add and activate a permanent rule to allow HTTP traffic on port 80, and then add
a runtime rule for traffic intended for TCP port 443. Add a permanent rule to the internal zone for TCP port range
5901 to 5910. Confirm the changes and display the contents of the affected zone files. Switch the default zone to the
internal zone and activate it
Task 5 :
Remove the 2 permanent rules added above. Switch back to the public zone as the default zone, and confirm the
changes
Task 6 :
Set the system hostname to server1.example.com and alias server1. Make sure that the new hostname is reflected in
the command prompt
177
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment – 9
Write commands/Command Line/code for some of the sub-questions in the space provided to each of
the main topic given below:
2. Change Passwords and Adjust Password Aging for Local User Accounts
a) password file stored
b) user file
c) see password expiration
d) set account expire day
e) set password expire in 90 days
f) remove expire day for account
g) set inactivity number of days
178
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
6. Change passwords and adjust password aging for local user accounts
a) To change the password for a user:
b) To view user password expiry information:
c) To set the password expiry for a user 30 days from now:
d) To set the password expiry date:To set the password to never expire:
7. Create, delete, and modify local groups and group memberships
a) To create a group:
b) To create a group with a specific GID:
c) To delete a group:
d) To modify the name of a group:
e) To modify the GID of a group:
f) To add a user to a group:
g) To view the members of a group:
h) To remove a user from a group:
8. Configure superuser access
a) To view the sudoers file:
b) Members of the wheel group can use sudo on all commands. To add a user to the wheel group:
c) To allow an individual user sudo access to specific commands:
Write commands/Command Line/code for the collection of given tasks/labs in the space provided.
Task 1 :
Create three users (Derek, Tom, and Kenny) that belong to the instructors group. Prevent Tom's user from accessing
a shell, and make his account expire 10 day from now
Task 2 :
Add 3 new users alice, bob and charles. Create a marketing group and add these users to the group. Create a
directory /marketing and change the owner to alice and group to marketing. Set permissions so that members of the
marketing group can share documents in the directory but nobody else can see them. Give charles read-only
permission. Create an empty file in the directory
Task 3 :
Create user300 with the default attributes in the useradd and login.defs files. Assign this user a password and show
179
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Task 4 :
For user200 change the login name to user200new, UID to 2000, home directory to /home/user200new, and login
shell to /sbin/nologin. Display the line entry for user2new from the passwd for validation. Remove this user and
confirm the deletion
Task 5 :
Configure password ageing for Derek using the chage command . Set the mindays to 7, maxdays to 28, and
warndays to 5. Verify the new settings. Rerun the command and set account expiry to January 31, 2023
Task 6 :
Configure password aging for using the PASSWD command. Set the mindays to 10, maxdays to 90, and warndays
to 14, and verify the new settings. Set the number of inactivity days to 5 and ensure that the user is forced to change
their password upon next login
Task 7 :
Create a group called linuxadm with GID 5000 and another group called dba sharing the GID 5000. Add Derek as a
secondary member to group linuxadm
Task 8 :
Change the linuxadm group name to sysadm and the GID to 6000. Modify the primary group for Derek to sysadm.
Remove the sysadm group and confirm
180
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 10
Write commands/Command Line/code for some of the sub-questions in the space provided to each
of the main topics given below:
Manage security
1. Configure firewall settings using firewall-cmd/firewalld
a) Network settings such as masquerading and IP forwarding can also be configured in the firewall-
config GUI application. To install this application:
b) To set port forwarding in the kernel setting:
2. Create and use file access control lists
a) To give a user read and write access to a file using an access control list:
b) To restrict a user from accessing a file using an access control list:
c) To remove an access control list for a user:
d) To give a group read and execute access to a directory recursively using an access control list:
e) To remove an access control list for a group:
182
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
m) see context
n) ls -lZ
o) restore context
p) see context
q) test the page
r) remove one context.
first list
s) remove context
t) search for context in /content
u) restore context
v) test the page
Write commands/Command Line/code for the collection of given tasks/labs in the space provided.
Task 1 :
Create a file acluser as user100 in /tmp and check if there are any ACL settings on the file. Apply access ACLs on
the file for user100 for read and write access. Add user200 to the file for full permissions. Remove all access ACLs
from the file
183
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Task 2 :
Generate a password-less ssh key pair using RSA for user100 on server. Distribute the public key to client and
attempt to log on to client from server. Show the log file message for the login attempt
Task 3 :
Remove the sshd service rule from the runtime configuration on server and try to access the server from the client
using the ssh command
Task 4:
Create a directory sedir1 under /tmp and a file sefile1 under sedir1. Check the context on the directory and file.
Change the SELinux user and type to user_u and public_content_t on both and verify
Task 5 :
Add the current context on sedir1 to the SELinux policy database to ensure a relabeling will not reset it to its
previous value. Next, you will change the context on the directory to some random values. Restore the default
context from the policy database back to the directory recursively
Task 6 :
Add a non-standard port 8010 to the SELinux policy database for the httpd service and confirm the addition.
Remove the port from the policy and verify the deletion
Task 7 :
Create a file called sefile2 under /tmp and display its context. Copy this file to the /etc/default directory, and observe
the change in the context. Remove sefile2 from /etc/default, and copy it again to the same destination, ensuring that
the target file receives the source file's context
Task 8 :
Display the current state of the Boolean nfs_export_all_rw. Toggle its value temporarily, and reboot the system. Flip
its value persistently after the system has been back up
184
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Operating Systems
21CS2109AA
Advanced Lab Experiment - 11
Write commands/Command Line/code for some of the sub-questions in the space provided to each
of the main topics given below:
Manage containers
1. Find and retrieve container images from a remote registry
a) To search for an image in a remote repository and download it:
4. Perform basic container management such as running, starting, stopping, and listing running
containers
a) To start, stop and remove a container:
b) view container details, use -a to see all
c) Note that the SELinux Boolean referred to above can be found using:
Task 1 :
Download the Apache web server container image (httpd 2.4) and inspect the container image. Check the exposed
ports in the container image configuration
185
21CS2109AA-OPERATING SYSTEMS ADVANCED LAB WORKBOOK
Task 2 :
Run the httpd container in the background. Assign the name myweb to the container, verify that the container is
running, stop the container and verify that it has stopped, and delete the container and the container image
Task 3 :
Pull the Apache web server container image (httpd 2.4) and run the container with the name webserver. Configure
webserver to display content "Welcome to container-based web server". Use port 3333 on the host machine to
receive http requests. Start a bash shell in the container to verify the configuration
Task 4 :
Configure the system to start the webserver container at boot as a systemd service. Start/enable the systemd service
to make sure the container will start at boot, and reboot the system to verify if the container is running as expected
Task 5 :
Create a container logserver from an image rsyslog in server1 from registry.redhat.io
Configure the container with systemd services by an existing user user10.
Service name should be container-logserver, and configure it to start automatically across reboot.
Configure your host journal to store all journal across reboot, copy all *.journal from /var/log/journal and
all subdirectories to /home/user10/container_logserver
Configure automount /var/log/journal from logserver (container) to /home/user10/container_logserver
when container starts.
186