Oslab Manual
Oslab Manual
OSLab Manual
Lab Manual
TE – Information Technology
P:F:-LTL-UG / 03 / R1 Sheet 1 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
AIM : Study of Basic Linux Commands: echo, ls, read, cat, touch, test, loops,
arithmetic comparison, conditional loops, grep, sed etc.
Theory :
1. pwd command
Use the pwd command to find out the path of the current working directory
(folder) you’re in. The command will return an absolute (full) path, which is
basically a path of all the directories that starts with a forward slash (/). An
2. cd command
To navigate through the Linux files and directories, use the cd command. It
requires either the full path or the name of the directory, depending on the
mand: cd Photos.
P:F:-LTL-UG / 03 / R1 Sheet 2 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
On a side note, Linux’s shell is case sensitive. So, you have to type the name’s
3. ls command
If you want to see the content of other directories, type ls and then the direc-
content of Documents.
ls -al will list the files and directories with detailed information like the
4. cat command
cat (short for concatenate) is one of the most frequently used commands in
Linux. It is used to list the contents of a file on the standard output (sdout).
To run this command, type cat followed by the file’s name and its extension.
P:F:-LTL-UG / 03 / R1 Sheet 3 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
to convert a file to upper or lower case use, cat filename | tr a-z A-Z
>output.txt
5. cp command
Use the cp command to copy files from the current directory to a different di -
tures would create a copy of scenery.jpg (from your current directory) into
6. mv command
The primary use of the mv command is to move files, although it can also be
The arguments in mv are similar to the cp command. You need to type mv,
the file’s name, and the destination’s directory. For example: mv file.txt /
home/username/Documents.
7. mkdir command
Use mkdir command to make a new directory — if you type mkdir Music it
P:F:-LTL-UG / 03 / R1 Sheet 4 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
8. rmdir command
If you need to delete a directory, use the rmdir command. However, rmdir
9. rm command
The rm command is used to delete directories and the contents within them.
use rm -r.
Note: Be very careful with this command and double-check which directory
you are in. This will delete everything and there is no undo.
The touch command allows you to create a blank new file through the Linux
Web.html to create an HTML file entitled Web under the Documents direc-
tory.
P:F:-LTL-UG / 03 / R1 Sheet 5 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
You can use this command to locate a file, just like the search command in
Windows. What’s more, using the -i argument along with this command will
make it case-insensitive, so you can search for a file even if you don’t remem -
To search for a file that contains two or more words, use an asterisk (*). For
example, locate -i school*note command will search for any file that con-
Similar to the locate command, using find also searches for files and directo-
ries. The difference is, you use the find command to locate files within a
given directory.
As an example, find /home/ -name notes.txt command will search for a file
Another basic Linux command that is undoubtedly helpful for everyday use
is grep. It lets you search through all the text in a given file.
To illustrate, grep blue notepad.txt will search for the word blue in the
notepad file. Lines that contain the searched word will be displayed fully.
P:F:-LTL-UG / 03 / R1 Sheet 6 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Short for “SuperUser Do”, this command enables you to perform tasks that
this command for daily use because it might be easy for an error to occur if
15. df command
Use df command to get a report on the system’s disk space usage, shown in
percentage and KBs. If you want to see the report in megabytes, type df -m.
16. du command
If you want to check how much space a file or a directory takes, the du (Disk
Usage) command is the answer. However, the disk usage summary will show
disk block numbers instead of the usual size format. If you want to see it in
bytes, kilobytes, and megabytes, add the -h argument to the command line.
The head command is used to view the first lines of any text file. By default,
it will show the first ten lines, but you can change this number to your liking.
For example, if you only want to show the first five lines, type head -n 5 file-
name.ext.
P:F:-LTL-UG / 03 / R1 Sheet 7 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
This one has a similar function to the head command, but instead of showing
the first lines, the tail command will display the last ten lines of a text file.
Short for difference, the diff command compares the contents of two files
line by line. After analyzing the files, it will output the lines that do not
match. Programmers often use this command when they need to make pro-
The tar command is the most used command to archive multiple files into
a tarball — a common Linux file format that is similar to zip format, with
This command is quite complex with a long list of functions such as adding
new files into an existing archive, listing the content of an archive, extracting
the content from an archive, and many more. Check out some practical ex -
P:F:-LTL-UG / 03 / R1 Sheet 8 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
chmod is another Linux command, used to change the read, write, and exe-
cated, you can read the full tutorial in order to execute it properly.
In Linux, all files are owned by a specific user. The chown command enables
For instance, chown linuxuser2 file.ext will make linuxuser2 as the owner of
the file.ext.
the kill command. It will send a certain signal to the misbehaving app and in -
There is a total of sixty-four signals that you can use, but people usually only
time to save all of its progress. If you don’t specify the signal when en-
will be lost.
P:F:-LTL-UG / 03 / R1 Sheet 9 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Besides knowing the signals, you also need to know the process identification
number (PID) of the program you want to kill. If you don’t know the PID, sim-
After knowing what signal you want to use and the PID of the program, enter
Confused about the function of certain Linux commands? Don’t worry, you
can easily learn how to use them right from Linux’s shell by using
the man command. For instance, entering man tail will show the manual in-
AIM:
OBJECTIVE:
P:F:-LTL-UG / 03 / R1 Sheet 10 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
THEORY:
Shell scripts are executed in a separate child shell process. This is done by
providing special interpreter line at the beginning (starting with #!).
To run the script we make it executable and then invoke the script name.
$ chmod +x script.sh or $ chmod 755 script.sh
$ script.sh
User can explicitly spawn a child shell of his choice with the script name as
argument. In this case it is not mandatory to include the interpreter line.
The read statement is the shell’s internal tool for taking inputs from the user, i.e.,
making scripts interactive. It is used with one or more variable. When we use a
statement like
read name
The script pauses at that point to take i/p from the keyboard. Since this is the
P:F:-LTL-UG / 03 / R1 Sheet 11 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
The shell script accepts arguments from the command line. The first argument is
read by shell into parameter $1, second into $2, and so on.
Example:
$ grep “director” emp.lst >/home/vishal; echo$?
Cmd1 && Cmd2: The Cmd2 will execute only when Cmd1 is succeeds.
Cmd1 || Cmd2: The Cmd2 will execute only when Cmd1 is fails.
Example:
$ grep “director” emp.lst >/home/vishal && echo “Pattern found in file”
THE if CONDITIONAL
P:F:-LTL-UG / 03 / R1 Sheet 12 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
test use certain operator to evaluate the condition on its right and returns either
true or false exit status, which is then used by if for making decisions.
Numeric Comparison
Example:
Test True if
S1 = S2 String S1 is equal to String S2
S1 != S2 String S1 is not equal to String S2
-n stg String stg is not a null String
-z stg String stg is a null String
stg String stg is assigned and not a null String
P:F:-LTL-UG / 03 / R1 Sheet 13 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
test also permits the checking of more than one condition in the same line using
the –a (AND) and –o(OR) operators.
Example:
File Tests
test can be used to test various file attributes like its type or permissions.
Example:
#!/bin/sh
if [ ! -e $1 ] ; then
echo “ File does not exists ”
elif [ ! -r $1 ] ; then
echo “ File is not readable ”
elif [ ! -w $1 ] ; then
echo “ File is not writable ”
else
echo “ File is both readable and writable ”
fi
Test true if
-f file file exists and is a regular file
-r file file exists and is a readable
-w file file exists and is a writable
-x file file exists and is a executable
-d file file exists and is a directory
-s file file exists and has a size greater than zero
case statement matches an expression or string for more than one alternative, in
more efficient manner than if.
Form:
case expr in
pattern 1) cmd1 ;;
pattern 2) cmd2 ;;
pattern 3) cmd3 ;;
esac
P:F:-LTL-UG / 03 / R1 Sheet 14 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Computation
expr can perform four basic arithmetic operation as well as modulus function
String Handling
Assignments
1. Use a script to take two numbers as arguments and output their sum using
i) bc ii) expr.
Include error checking to test if two arguments were entered.
2. Write a shell script that uses find to look for a file and echo a suitable msg
if the file is not found. You must not store the find output in a file.
P:F:-LTL-UG / 03 / R1 Sheet 15 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
ASSIGNMENT No: 2
AIM:
Process control system calls: The demonstration of FORK, EXECVE and WAIT
system calls along with zombie and orphan states.
1. Implement the C program in which main program accepts the integers to
be sorted. Main program uses the FORK system call to create a new
process called a child process. Parent process sorts the integers using
sorting algorithm and waits for child process using WAIT system call to
sort the integers using any sorting algorithm. Also demonstrate zombie
and orphan states.
2. Implement the C program in which main program accepts an integer array.
Main program uses the FORK system call to create a new process called a
child process. Parent process sorts an integer array and passes the sorted
array to child process through the command line arguments of EXECVE
system call. The child process uses EXECVE system call to load new
program which display array in reverse order.
OBJECTIVE:
This assignment covers the UNIX process control commonly called for process
creation, program execution and process termination. Also covers process
model, including process creation, process destruction, zombie and orphan
processes.
THEORY:
Process in UNIX:
Process IDs
Each process in a Linux system is identified by its unique process ID, sometimes
referred to as pid. Process IDs are 16-bit numbers that are assigned sequentially
by Linux as new processes are created.
When referring to process IDs in a C or C++ program, always use the pid_t
typedef, which is defined in <sys/types.h>.A program can obtain the process ID
of the process it’s running in with the getpid() system call, and it can obtain the
process ID of its parent process with the getppid() system call.
Creating Processes
P:F:-LTL-UG / 03 / R1 Sheet 16 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
1. Using system
The system function in the standard C library provides an easy way to execute a
command from within a program, much as if the command had been typed into a
shell. In fact, system creates a subprocess running the standard Bourne shell
(/bin/sh)and hands the command to that shell for execution.
The system function returns the exit status of the shell command. If the shell
itself cannot be run, system returns 127; if another error occurs, system returns –
1.
2. Using fork
A process can create a new process by calling fork. The calling process becomes
the parent, and the created process is called the child. The fork function copies
the parent's memory image so that the new process receives a copy of the
address space of the parent. Both processes continue at the instruction after the
fork statement (executing in their respective memory images).
SYNOPSIS
#include <unistd.h>
pid_t fork(void);
The fork function returns 0 to the child and returns the child's process ID to the
parent. When fork fails, it returns –1.
When a process creates a child, both parent and child proceed with execution
from the point of the fork. The parent can execute wait to block until the child
finishes. The wait function causes the caller to suspend execution until a child's
status becomes available or until the caller receives a signal.
SYNOPSIS
#include <sys/wait.h>
P:F:-LTL-UG / 03 / R1 Sheet 17 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
If wait returns because the status of a child is reported, these functions return
the process ID of that child. If an error occurs, these functions return –1.
P:F:-LTL-UG / 03 / R1 Sheet 18 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Example:
pid_t childpid;
childpid =
wait(NULL); if
(childpid != -1)
printf("Waited for child with pid %ld\n", childpid);
Status values
POSIX specifies six macros for testing the child's return status. Each takes the
status value returned by a child to wait as a parameter. Following are the two
such macros:
SYNOPSIS
#include <sys/wait.h>
WIFEXITED(int stat_val)
WEXITSTATUS(int stat_val)
New program execution within the existing process (The exec Function)
The fork function creates a copy of the calling process, but many applications
require the child process to execute code that is different from that of the
parent. The exec family of functions provides a facility for overlaying the process
image of the calling process with a new image. The traditional way to use the
fork–exec combination is for the child to execute (with an exec function) the new
program while the parent continues to execute the original code.
SYNOPSIS
#include <unistd.h>
1. int execl(const char *path, const char *arg0, ... /*, char *(0) */);
P:F:-LTL-UG / 03 / R1 Sheet 19 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
2. int execle (const char *path, const char *arg0, ... /*, char *(0),
P:F:-LTL-UG / 03 / R1 Sheet 20 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
execlp(): It does same job except that it will use environment variable
PATH to determine which executable to process. Thus a fully qualified path name
would not have to be used. The function execlp() can also take the fully
qualified name as it also resolves explicitly.
e.g. execlp("ls", "ls", "-l", NULL);
execvp(): It does same job expect that it will use environment variable
PATH to determine which executable to process. Thus a fully qualified path name
would not have to be used.
e.g. execvp("ls", argv);
3. execve( ):
int execve(const char *filename, char *const argv[ ], char *const envp[ ]);
P:F:-LTL-UG / 03 / R1 Sheet 21 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Process Termination
Normally, a process terminates in one of two ways. Either the executing program
calls the exit() function, or the program’s main function returns. Each process
has an exit code: a number that the process returns to its parent. The exit code is
the argument passed to the exit function, or the value returned from main.
Zombie Processes
If a child process terminates while its parent is calling a wait function, the child
process vanishes and its termination status is passed to its parent via the wait
call. But what happens when a child process terminates and the parent is not
calling wait? Does it simply vanish? No, because then information about its
termination—such as whether it exited normally and, if so, what its exit status is
—would be lost. Instead, when a child process terminates, is becomes a zombie
process.
A zombie process is a process that has terminated but has not been cleaned up
yet. It is the responsibility of the parent process to clean up its zombie children.
The wait functions do this, too, so it’s not necessary to track whether your child
process is still executing before waiting for it. Suppose, for instance, that a
program forks a child process, performs some other computations, and then calls
P:F:-LTL-UG / 03 / R1 Sheet 22 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
wait. If the child process has not terminated at that point, the parent process will
block in the wait call until the child process finishes. If the child process finishes
before the parent process calls wait, the child process becomes a zombie. When
the parent process calls wait, the zombie child’s termination status is extracted,
the child process is deleted, and the wait call returns immediately.
Orphan Process:
An Orphan Process is nearly the same thing which we see in real world.
Orphan means someone whose parents are dead. The same way this is a process,
whose parents are dead, that means parents are either terminated, killed or
exited but the child process is still alive.
# ps -elf | head -1; ps -elf | awk '{if ($5 == 1 && $3 != "root") {print $0}}' |
head
This will show you all the orphan processes running in your system. The
P:F:-LTL-UG / 03 / R1 Sheet 23 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
output from this command confirms that they are Orphan processes but does
not mean that they are all useless, so confirm from some other source also
before killing them.
Daemon Process:
It is a process that runs in the background, rather than under the direct
control of a user; they are usually initiated as background processes.
1. Creates new process without fully copying the address space of the
parent.
2. vfork guarantees that the child runs first, until the child calls exec or exit.
3. When child calls either of these two functions(exit, exec), the parent
resumes.
INPUT:
OUTPUT:
1. Sorted array.
2. Status of number to be searched.
FAQS:
Is Orphan process different from an Zombie process ?
Are Orphan processes harmful for system ?
P:F:-LTL-UG / 03 / R1 Sheet 24 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Example 1
#include <stdio.h>
#include <unistd.h>
int main()
{
printf(“The process ID is %d\n”, (int) getpid());
printf(“The parent process ID is %d\n”, (int) getppid());
return 0;
}
Example 2
#include <stdlib.h>
int main()
{
int return_value;
return_value=system(“ls –l /”);
return return_value;
}
Example 3
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
P:F:-LTL-UG / 03 / R1 Sheet 25 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
int main()
{
pid_t child_pid;
printf(“The main program process ID is %d\n”, (int) getpid());
child_pid=fork();
if(child_pid!=0) {
printf(“This is the parent process ID, with id %d\n”, (int) getpid());
printf(“The child process ID is %d\n”, (int) chi;d_pid);
}
else
printf(“This is the child process ID, with id %d\n”, (int) getpid());
return 0;
}
Example 4
Determining the exit status of a child.
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
void show_return_status(void)
{
pid_t childpid;
int status;
childpid = wait(&status); if
(childpid == -1)
perror("Failed to wait for child");
else if (WIFEXITED(status))
printf("Child %ld terminated with return status %d\n",
(long)childpid, WEXITSTATUS(status));
Example 5
#include <stdio.h>
#include <stdlib.h>
P:F:-LTL-UG / 03 / R1 Sheet 26 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
pid_t childpid;
childpid = fork();
if (childpid == -1)
{ perror("Failed to fork");
return 1;
}
if (childpid == 0) {
/* child code */
execl("/bin/ls", "ls", "-l", NULL);
perror("Child failed to exec ls"); return
1;
}
if (childpid != wait(NULL)) {
/* parent code */
perror("Parent failed to wait due to signal or error"); return
1;
}
return 0;
}
Example 6
Making a zombie process
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t child_pid;
//create a child process
child_pid=fork();
if(child_pid>0) {
//This is a parent process. Sleep for a minute
sleep(60)
}
else
{
P:F:-LTL-UG / 03 / R1 Sheet 27 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Example 7
Demonstration of fork system call
#include<stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
char *msg;
int n;
printf(“Program starts\n”);
pid=fork();
switch(pid)
{
case -1:
printf(“Fork error\n”);
exit(-1);
case 0:
msg=”This is the child process”;
n=5;
break;
default:
msg=”This is the parent process”;
n=3;
break;
}
while(n>0)
{
puts(msg);
sleep(1);
P:F:-LTL-UG / 03 / R1 Sheet 28 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
n--;
}
return 0;
}
Example 8
Demo of multiprocess application using fork()system call
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int pfd[2];
int ret_val,nread;
pid_t pid;
ret_val=pipe(pfd);
if(ret_val==-1)
{
perror(“pipe error\n”);
exit(ret_val);
}
pid=fork();
switch(pid)
{
case -1:
printf(“Fork error\n”);
exit(pid);
case 0:
do_child_proc(pfd);
exit(0);
default:
do_parent_proc(pfd);
exit(pid);
}
wait(NULL);
P:F:-LTL-UG / 03 / R1 Sheet 29 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
return 0;
}
P:F:-LTL-UG / 03 / R1 Sheet 30 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
ASSIGNMENT No: 3
AIM: Implement C program for CPU scheduling algorithms: Shortest Job First
(SJF) and Round Robin with different arrival time.
THEORY:
Shortest Job First scheduling works on the process with the shortest burst time
or duration first.
This is the best approach to minimize waiting time.
This is used in Batch Systems.
It is of two types:
1. Non Pre-emptive
2. Pre-emptive
To successfully implement it, the burst time/duration time of the
processes should be known to the processor in advance, which is
practically not feasible all the time.
This scheduling algorithm is optimal if all the jobs/processes are available
at the same time. (either Arrival time is 0 for all, or Arrival time is same for
all)
Consider the below processes available in the ready queue for execution, with
arrival time as 0 for all and given burst times.
P:F:-LTL-UG / 03 / R1 Sheet 31 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
As you can see in the GANTT chart above, the process P4 will be picked up first
as it has the shortest burst time, then P2, followed by P3 and at last P1.
We scheduled the same set of processes using the First come first serve
algorithm in the previous tutorial, and got average waiting time to be 18.75 ms,
whereas with SJF, the average waiting time comes out 4.5 ms.
If the arrival time for processes are different, which means all the processes are
not available in the ready queue at time 0, and some jobs arrive after some time,
in such situation, sometimes process with short burst time have to wait for the
current process's execution to finish, because in Non Pre-emptive SJF, on arrival
of a process with short duration, the existing job/process's execution is not
halted/stopped to execute the short job first.
This leads to the problem of Starvation, where a shorter process has to wait for a
long time until the current longer process gets executed. This happens if shorter
jobs keep coming, but this can be solved using the concept of aging.
P:F:-LTL-UG / 03 / R1 Sheet 32 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
P:F:-LTL-UG / 03 / R1 Sheet 33 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Important terms:
P:F:-LTL-UG / 03 / R1 Sheet 34 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
In the above diagram, arrival time is not mentioned so it is taken as 0 for all
processes.
Note: If arrival time is not given for any problem statement then it is taken as 0
for all processes; if it is given then the problem can be solved accordingly.
Explanation:
The value of time quantum in the above example is 5.Let us now calculate the
Turn around time and waiting time for the above example :
P:F:-LTL-UG / 03 / R1 Sheet 35 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
P1 21 32-0=32 32-21=11
P2 3 8-0=8 8-3=5
P3 6 21-0=21 21-6=15
P4 2 15-0=15 15-2=13
Average waiting time is calculated by adding the waiting time of all processes
and then dividing them by no.of processes.
average waiting time = waiting time of all processes/ no.of processes
average waiting time=11+5+15+13/4 = 44/4= 11ms
P:F:-LTL-UG / 03 / R1 Sheet 36 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
P:F:-LTL-UG / 03 / R1 Sheet 37 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
THEORY:
Semaphores:
An integer value used for signaling among processes. Only three operations may
be performed on a semaphore, all of which are atomic: initialize, decrement, and
increment.
The decrement operation may result in the blocking of a process, and the
increment operation may result in the unblocking of a process. Also known as a
counting semaphore or a general semaphore.
Counting semaphore
The counting semaphores are free of the limitations of the binary semaphores. A
counting semaphore comprises:
An integer variable, initialized to a value K (K>=0). During operation it can as-
sume any value <= K, a pointer to a process queue. The queue will hold the PCBs
of all those processes, waiting to enter their critical sections. The queue is imple-
mented as a FCFS, so that the waiting processes are served in a FCFS order.
P:F:-LTL-UG / 03 / R1 Sheet 38 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
P:F:-LTL-UG / 03 / R1 Sheet 39 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Figure illustrates the structure of buffer b. The producer can generate items and
store them in the buffer at its own pace. Each time, an index (in) into the buffer is
incremented. The consumer proceeds in a similar fashion but must make sure
that it does not attempt to read from an empty buffer. Hence, the
CONCLUSION:
FAQ
P:F:-LTL-UG / 03 / R1 Sheet 40 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
THEORY:
Semaphores:
An integer value used for signaling among processes. Only three operations may
be performed on a semaphore, all of which are atomic: initialize, decrement, and
increment.
The decrement operation may result in the blocking of a process, and the
increment operation may result in the unblocking of a process. Also known as a
countingsemaphore or a general semaphore.
Counting semaphore
The counting semaphores are free of the limitations of the binary semaphores. A
counting semaphore comprises:
P:F:-LTL-UG / 03 / R1 Sheet 41 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
P:F:-LTL-UG / 03 / R1 Sheet 42 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Thus, readers are processes that are not required to exclude one another and
writers are processes that are required to exclude all other processes, readers
and writers alike. Before proceeding, let us distinguish this problem from two
others: the general mutual exclusion problem and the producer/consumer
problem. In the readers/writers problem readers do not also write to the data
area, nor do writers read the data area while writing.
A more general case, which includes this case, is to allow any of the processes to
read or write the data area. In that case, we can declare any portion of a process
that accesses the data area to be a critical section and impose the general mutual
exclusion solution. The reason for being concerned with the more restricted case
is that more efficient solutions are possible for this case and that the less
efficient solutions to the general problem are unacceptably slow.
For example, suppose that the shared area is a library catalog. Ordinary users of
the library read the catalog to locate a book. One or more librarians are able to
update the catalog.
In the general solution, every access to the catalog would be treated as a critical
section, and users would be forced to read the catalog one at a time. This would
clearly impose intolerable delays. At the same time, it is important to prevent
writers from interfering with each other and it is also required to prevent
reading while writing is in progress to prevent the access of inconsistent
information.
This is not a special case of producer-consumer. The producer is not just a writer.
It must read queue pointers to determine where to write the next item, and it
must determine if the buffer is full. Similarly, the consumer is not just a reader,
because it must adjust the queue pointers to show that it has removed a unit
from the buffer.
int readcount;
semaphore x = 1,wsem = 1;
void reader()
{
while (true)
{
semWait (x);
readcount++;
if(readcount == 1)
semWait (wsem);
semSignal (x);
READUNIT();
P:F:-LTL-UG / 03 / R1 Sheet 43 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
semWait (x);
readcount;
if(readcount == 0)
semSignal (wsem);
semSignal (x);
}
}
void writer()
{
while (true)
{
semWait (wsem);
WRITEUNIT();
semSignal (wsem);
}
}
void main()
{
readcount = 0;
parbegin (reader,writer);
}
Threads
Including the file pthread.h provides us with other definitions and prototypes
that we will need in our code, much like stdio.h for standard input and output
routines.
#include <pthread.h>
int pthread_create(pthread_t *thread, pthread_attr_t*attr,
void*(*start_routine)(void *), void *arg);
This function is used to create the thread. The first argument is a pointer to
pthread_t.
When a thread is created, an identifier is written to the memory location to
which this variable points. This identifier enables us to refer to the thread. The
P:F:-LTL-UG / 03 / R1 Sheet 44 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
next argument sets the thread attributes. We do not usually need any special
attributes, and we can simply pass NULL as this argument. The final two
arguments tell the thread the function that it is to start executing and the
arguments that are to be passed to this function.
void *(*start_routine)(void *)
pthread_join is the thread equivalent of wait that processes use to collect child
processes. This function is declared as follows:
#include <pthread.h>
The first parameter is the thread for which to wait, the identifier that
pthread_create filled in for us. The second argument is a pointer to a pointer that
itself points to the return value from the thread. This function returns zero for
success and an error code on failure.
This function initializes a semaphore object pointed to by sem, sets its sharing
option
P:F:-LTL-UG / 03 / R1 Sheet 45 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
and gives it an initial integer value. The pshared parameter controls the type of
semaphore. If the value of pshared is 0, the semaphore is local to the current
process. Otherwise, the semaphore may be shared between processes. Here we
are interested only in semaphores that are not shared between processes. At the
time of writing, Linux doesn’t support this sharing,and passing a nonzero value
for pshared will cause the call to fail.
The next pair of functions controls the value of the semaphore and is declared as
follows:
#include <semaphore.h>
int sem_wait(sem_t * sem);
int sem_post(sem_t * sem);
If both programs try to increase the value by 1, the semaphore will always be
correctly increased in value by 2.
The sem_wait function atomically decreases the value of the semaphore by one,
but always waits until the semaphore has a nonzero count first. Thus, if you call
sem_wait on a semaphore with a value of 2, the thread will continue executing
but the semaphore will be decreased to 1.
If sem_wait is called on a semaphore with a value of 0, the function will wait until
some other thread has incremented the value so that it is no longer 0. If two
threads are both waiting in sem_wait for the same semaphore to become
nonzero and it is incremented once by a third process, only one of the two
waiting processes will get to decrement the semaphore and continue; the other
will remain waiting. This atomic “test and set” ability in a single function is what
makes semaphores so valuable.
Again, this function takes a pointer to a semaphore and tidies up any resources
that it may have. If we attempt to destroy a semaphore for which some thread is
waiting, we will get an error. Like most Linux functions, these functions all return
0 on success.
P:F:-LTL-UG / 03 / R1 Sheet 46 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
References :
CONCLUSION:
FAQ
P:F:-LTL-UG / 03 / R1 Sheet 47 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
ASSIGNMENT NO: 5
THEORY :
P:F:-LTL-UG / 03 / R1 Sheet 48 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Some data structures that are used to implement the banker's algorithm are:
1. Available
It is an array of length m. It represents the number of available resources of each
type. If Available[j] = k, then there are k instances available, of resource type Rj.
2. Max
It is an n x m matrix which represents the maximum number of instances of each
resource that a process can request. If Max[i][j] = k, then the process Pi can
request atmost k instances of resource type Rj.
3. Allocation
It is an n x m matrix which represents the number of resources of each type
currently allocated to each process. If Allocation[i][j] = k, then process Pi is
currently allocated k instances of resource type Rj.
4. Need
It is a two-dimensional array. It is an n x m matrix which indicates the remaining
resource needs of each process. If Need[i][j] = k, then process Pi may need k
more instances of resource type Rj to complete its task.
A) Safety Algorithm
A safety algorithm is an algorithm used to find whether or not a system is in
its safe state. The algorithm is as follows:
1. Let Work and Finish be vectors of length m and n, respectively. Initially,
Work = Available
P:F:-LTL-UG / 03 / R1 Sheet 49 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
This means, initially, no process has finished and the number of available
resources is represented by the Available array.
2. Find an index i such that both
Finish[i] ==false
Needi <= Work
Go to step 2.
When an unfinished process is found, then the resources are allocated and the
process is marked finished. And then, the loop is repeated to check the same for
all other processes.
4. If Finish[i] == true for all i, then the system is in a safe state.
That means if all processes are finished, then the system is in safe state.
This algorithm may require an order of mxn² operations in order to determine
whether a state is safe or not.
P:F:-LTL-UG / 03 / R1 Sheet 50 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
3.Now we will assume that resources are assigned to process Pi and thus
perform the following steps:
Available= Available-Requesti ;
Allocationi=Allocationi +Requesti;
Needi =Needi - Requesti;
If the resulting resource allocation state comes out to be safe, then the
transaction is completed and, process Pi is allocated its resources. But in this
case, if the new state is unsafe, then Pi waits for Requesti, and the old resource-
allocation state is restored.
Example:
Let us consider the following snapshot for understanding the banker's
algorithm:
Process Allocation A B
Max A B C Available A B C
es C
P1 212 322
P:F:-LTL-UG / 03 / R1 Sheet 51 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
P2 401 902
P3 020 753
P4 112 112
Solution:
1. The Content of the need matrix can be calculated by using the formula given
below:
Need = Max – Allocation
P:F:-LTL-UG / 03 / R1 Sheet 52 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
P:F:-LTL-UG / 03 / R1 Sheet 53 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
= (5, 3, 4) + (4, 0, 1)
= (9, 3, 5) now, (New Available)
7. Now again check for Process P3, Need = (7, 3, 3)
Available = (9, 3, 5)
Need <=Available = True
The request for P3 is granted.
Available = Available +Allocation
= (9, 3, 5) + (0, 2, 0) = (9, 5, 5)
8. Now again check for Process P0, = Need (3, 2, 1)
= Available (9, 5, 5)
Need <= Available = True
So, the request will be granted to P0.
Safe sequence: < P1, P4, P2, P3, P0>
The system allocates all the needed resources to each process. So, we can
say that the system is in a safe state.
3. The total amount of resources
The total amount of resources will be calculated by the following formula:
The total amount of resources= sum of columns of allocation + Available
= [8 5 7] + [2 1 0] = [10 6 7]
P:F:-LTL-UG / 03 / R1 Sheet 54 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
ASSIGNMENT NO: 6
AIM: Implement the C program for Page Replacement Algorithms: FCFS, LRU,
and Optimal for frame size as minimum three.
OBJECTIVE:
This assignment helps the students understand the Page Replacement
Algorithms in Unix/Linux and how to implement it in C
THEORY:
P:F:-LTL-UG / 03 / R1 Sheet 55 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
2. Remove some other process completely from the memory to free frames.
3. Find some pages that are not being used right now, move them to the disk
to get free frames. This technique is called Page replacement and is most
commonly used.
4.
In this case, if a process requests a new page and supposes there are no free
frames, then the Operating system needs to decide which page to replace. The
operating system must use any page replacement algorithm in order to select
the victim frame. The Operating system must then write the victim frame to the
disk then read the desired page into the frame and then update the page tables.
And all these require double the disk access time.
Page Replacement in OS
In Virtual Memory Management, Page Replacement Algorithms play an
important role. The main objective of all the Page replacement policies is to
decrease the maximum number of page faults.
Page Fault – It is basically a memory error, and it occurs when the current
programs attempt to access the memory page for mapping into virtual address
space, but it is unable to load into the physical memory then this is referred to as
Page fault.
P:F:-LTL-UG / 03 / R1 Sheet 56 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
This algorithm helps to decide which pages must be swapped out from the main
memory in order to create a room for the incoming page. This Algorithm wants
the lowest page-fault rate.
P:F:-LTL-UG / 03 / R1 Sheet 57 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Advantages
This algorithm is simple and easy to use.
FIFO does not cause more overhead.
Disadvantages
This algorithm does not make the use of the frequency of last used time
rather it just replaces the Oldest Page.
There is an increase in page faults as page frames increases.
The performance of this algorithm is the worst.
Example:
A system uses 3 page frames for storing process pages in main memory. It uses
the First in First out (FIFO) page replacement policy. Assume that all the page
frames are initially empty. What is the total number of page faults that will occur
while processing the page reference string given below-
4 , 7, 6, 1, 7, 6, 1, 2, 7, 2
Also calculate the hit ratio and miss ratio.
Solution-
Total number of references = 10
P:F:-LTL-UG / 03 / R1 Sheet 58 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
From here,
Alternatively,
Miss ratio
= 1 – Hit ratio
= 1 – 0.4
= 0.6 or 60%
Example:
P:F:-LTL-UG / 03 / R1 Sheet 59 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
A system uses 3 page frames for storing process pages in main memory. It uses
the Least Recently Used (LRU) page replacement policy. Assume that all the page
frames are initially empty. What is the total number of page faults that will occur
while processing the page reference string given below-
4 , 7, 6, 1, 7, 6, 1, 2, 7, 2
Also calculate the hit ratio and miss ratio.
Solution-
Total number of references = 10
From here,
Total number of page faults occurred = 6
This algorithm mainly replaces the page that will not be used for the longest
time in the future. The practical implementation of this algorithm is not possible.
Practical implementation is not possible because we cannot predict in
advance those pages that will not be used for the longest time in the
future.
This algorithm leads to less number of page faults and thus is the best-
known algorithm
Also, this algorithm can be used to measure the performance of other
algorithms.
P:F:-LTL-UG / 03 / R1 Sheet 60 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Advantages of OPR
This algorithm is easy to use.
This algorithm provides excellent efficiency and is less complex.
For the best result, the implementation of data structures is very easy
Disadvantages of OPR
In this algorithm future awareness of the program is needed.
Practical Implementation is not possible because the operating system is
unable to track the future request
Example:
A system uses 3 page frames for storing process pages in main memory. It uses
the Optimal page replacement policy. Assume that all the page frames are
initially empty. What is the total number of page faults that will occur while
processing the page reference string given below-
4 , 7, 6, 1, 7, 6, 1, 2, 7, 2
Also calculate the hit ratio and miss ratio.
Solution-
Total number of references = 10
From here,
Total number of page faults occurred = 5
In the similar manner as above-
Hit ratio = 0.5 or 50%
Miss ratio = 0.5 or 50%
P:F:-LTL-UG / 03 / R1 Sheet 61 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
OBJECTIVES:
THEORY:
FIFOs
A first-in, first-out (FIFO) file is a pipe that has a name in the filesystem.
Any process can open or close the FIFO; the processes on either end of the pipe
need not be related to each other. FIFOs are also called named pipes
You can make a FIFO using the mkfifo command. Specify the path to the FIFO on
the command line. For example, create a FIFO in /tmp/fifo by invoking this:
% mkfifo /tmp/fifo
% ls -l /tmp/fifo
prw-rw-rw-
1 samuel users 0 Jan 16 14:04 /tmp/fifo
The first character of the output from ls is p, indicating that this file is actually a
FIFO (named pipe). In one window, read from the FIFO by invoking the following:
Then type in some lines of text. Each time you press Enter, the line of text is sent
through the FIFO and appears in the first window. Close the FIFO by pressing
Ctrl+D in the second window. Remove the FIFO with this line:
% rm /tmp/fifo
Creating a FIFO
Create a FIFO programmatically using the mkfifo function.The first argument is
the path at which to create the FIFO; the second parameter specifies the pipe’s
P:F:-LTL-UG / 03 / R1 Sheet 62 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
owner, group, and world permissions, and a pipe must have a reader and a writer,
the permissions must include both read and write permissions. If the pipe cannot
be created (for instance, if a file with that name already exists), mkfifo returns –
1. Include<sys/types.h> and <sys/stat.h> if you call mkfifo.
Accessing a FIFO
Access a FIFO just like an ordinary file. To communicate through a FIFO, one
program must open it for writing, and another program must open it for reading.
Either low-level I/O functions like open, write, read, close or C library I/O
functions (fopen, fprintf, fscanf, fclose, and soon) may be used.
For example, to write a buffer of data to a FIFO using low-level I/O routines, you
could use this code:
close (fd);
To read a string from the FIFO using C library I/O functions, you could use this
code:
fclose (fifo);
A FIFO can have multiple readers or multiple writers. Bytes from each writer are
written atomically up to a maximum size of PIPE_BUF (4KB on Linux). Chunks
from simultaneous writers can be interleaved. Similar rules apply to simultaneous
reads.
CONCLUSION:
P:F:-LTL-UG / 03 / R1 Sheet 63 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
THEORY:
Shared Memory
Shared memory allows two unrelated processes to access the same logical
memory. Shared memory is a very efficient way of transferring data between
two running processes. Shared memory is a special range of addresses that is
created by IPC for one process and appears in the address space of that process.
Other processes can then “attach” the same shared memory segment into their
own address space. All processes can access the memory locations just as if the
memory had been allocated by malloc. If one process writes to the shared
memory, the changes immediately become visible to any other process that has
access to the same shared memory.
Shared memory provides an efficient way of sharing and passing data between
multiple processes. By itself, shared memory doesn’t provide any
synchronization facilities. Because it provides no synchronization facilities, we
usually need to use some other mechanism to synchronize access to the shared
memory.
P:F:-LTL-UG / 03 / R1 Sheet 64 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
The arrows show the mapping of the logical address space of each process to the
physical memory available. In practice, the situation is more complex because the
available memory actually consists of a mix of physical memory and memory
pages that have been swapped out to disk. The functions for shared memory
resemble those for semaphores:
#include <sys/shm.h>
P:F:-LTL-UG / 03 / R1 Sheet 65 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
As with semaphores, the include files sys/types.h and sys/ipc.h are normally
automatically included by shm.h.
As with semaphores, the program provides key, which effectively names the
shared memory segment, and the shmget function returns a shared memory
identifier that is used in subsequent shared memory functions. There’s a special
key value, IPC_PRIVATE, that creates shared memory private to the process.The
second parameter, size, specifies the amount of memory required in bytes.The
third parameter, shmflg, consists of nine permission flags that are used in the
same way as the mode flags for creating files. A special bit defined by IPC_CREAT
must be bitwise ORed with the permissions to create a new shared memory
segment. It’s not an error to have the IPC_CREAT flag set and pass the key of an
existing shared memory segment. The IPC_CREAT flag is silently ignored if it is
not required.If the shared memory is successfully created, shmget returns a
nonnegative integer, the shared memory identifier. On failure, it returns –1.
shmat()
When we first create a shared memory segment, it’s not accessible by any
process. Toenable access to the shared memory, we must attach it to the address
space of a process. We do this with the shmat function:
The first parameter, shm_id, is the shared memory identifier returned from
shmget. The second parameter, shm_addr, is the address at which the shared
memory is to be attached to the current process. This should almost always be a
null pointer, which allows the system to choose the address at which the memory
appears.The third parameter, shmflg, is a set of bitwise flags. The two possible
values are SHM_R for writing and SHM_W for write access. If the shmat call is
successful, it returns a pointer to the first byte of shared memory. On failure –1
is returned.
shmctl( )
P:F:-LTL-UG / 03 / R1 Sheet 66 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
mode_t shm_perm.mode;}
The first parameter, shm_id, is the identifier returned from shmget. The second
parameter,command, is the action to take. It can take three values, shown in the
following table.
Command Description
IPC_STAT : Sets the data in the shmid_ds structure to reflect the values
associated with the shared memory.
IPC_SET: Sets the values associated with the shared memory to those provided
in the shmid_ds data structure, if the process has permission to do so.
The third parameter, buf, is a pointer to the structure containing the modes and
permissions for the shared memory.
References :
P:F:-LTL-UG / 03 / R1 Sheet 67 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
ASSIGNMENT No: 8
INTRODUCTION
In operating systems, seek time is very important. Since all device requests are
linked in queues, the seek time is increased causing the system to slow down.
Disk Scheduling Algorithms are used to reduce the total seek time of any
request.
PURPOSE
The purpose of this material is to provide one with help on disk scheduling
algorithms. Hopefully with this, one will be able to get a stronger grasp of what
disk scheduling algorithms do.
These algorithms are not hard to understand, but they can confuse someone
because they are so similar. What we are striving for by using these algorithms is
keeping Head Movements (# tracks) to the least amount as possible. The less the
head has to move the faster the seek time will be. I will show you and explain to
you why C-LOOK is the best algorithm to use in trying to establish less seek time.
P:F:-LTL-UG / 03 / R1 Sheet 68 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Given the following queue -- 95, 180, 34, 119, 11, 123, 62, 64 with the Read-write
head initially at the track 50 and the tail track being at 199 let us now discuss the
different algorithms.
1. First Come -First Serve (FCFS)
All incoming requests are placed at the end of the queue. Whatever number that
is next in the queue will be the next number served. Using this algorithm doesn't
provide the best results. To determine the number of head movements you
would simply find the number of tracks it took to move from one request to the
next. For this case it went from 50 to 95 to 180 and so on. From 50 to 95 it moved
45 tracks. If you tally up the total number of tracks you will find how many tracks
it had to go through before finishing the entire request. In this example, it had a
total head movement of 640 tracks. The disadvantage of this algorithm is noted
by the oscillation from track 50 to track 180 and then back to track 11 to 123
then to 64. As you will soon see, this is the worse algorithm that one can use.
P:F:-LTL-UG / 03 / R1 Sheet 69 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
3. Elevator (SCAN)
This approach works like an elevator does. It scans down towards the nearest
end and then when it hits the bottom it scans up servicing the requests that it
didn't get going down. If a request comes in after it has been scanned it will not
be serviced until the process comes back down or moves back up. This process
moved a total of 230 tracks. Once again this is more optimal than the previous
algorithm, but it is not the best.
Figure 3. Elevator
(SCAN)
4. Circular Scan (C-SCAN)
Circular scanning works just like the elevator to some extent. It begins its scan
toward the nearest end and works it way all the way to the end of the system.
Once it hits the bottom or top it jumps to the other end and moves in the same
direction. Keep in mind that the huge jump doesn't count as a head movement.
The total head movement for this algorithm is only 187 track, but still this isn't
the mose sufficient.
P:F:-LTL-UG / 03 / R1 Sheet 70 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Figure 4: Circular
Scan (C-SCAN)
5. C-LOOK
This is just an enhanced version of C-SCAN. In this the scanning doesn't go past
the last request in the direction that it is moving. It too jumps to the other end
but not all the way to the end. Just to the furthest request. C-SCAN had a total
movement of 187 but this scan (C-LOOK) reduced it down to 157 tracks.
From this you were able to see a scan change from 644 total head movements to
just 157. You should now have an understanding as to why your operating
system truly relies on the type of algorithm it needs when it is dealing with
multiple processes.
Figure 5: C-LOOK
Assignment:
P:F:-LTL-UG / 03 / R1 Sheet 71 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Given the following queue -- 195, 80, 134, 19, 111, 132, 162, 164 with the Read-
write head initially at the track 150 and the tail track being at 199, implement disk
scheduling to calculate head movements for SSTF, SCAN, C-LOOK
P:F:-LTL-UG / 03 / R1 Sheet 72 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
ASSIGNMENT No: 9
AIM : Implement a new system call, add this new system call in the Linux kernel
(any kernel source, any architecture and any Linux kernel distribution) and
demonstrate the use of same.
OBJECTIVE: add a new system call, swipe(), to the Linux kernel that transfers
the remaining time slice of each process in a specified set to a target process.
You will also demonstrate various uses of the system call (both advantageous
and detrimental)
THEORY:
wget https://www.kernel.org/pub/linux/kernel/v4.x/linux-4.17.4.tar.xz
tar — Tar stores and extracts files from a tape or disk archive.
Now, we’ll change the directory to where the files are extracted:
cd /usr/src/linux-4.17.4/
P:F:-LTL-UG / 03 / R1 Sheet 73 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
mkdir hello
cd hello
gedit hello.c
gedit Makefile
obj-y := hello.o
This is to ensure that the hello.c file is compiled and included in the kernel source
code.
P:F:-LTL-UG / 03 / R1 Sheet 74 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
gedit Makefile
search for core-y in the document, you’ll find this line as the second instance of
your search:
Note: There is a space between “block/” and “hello/”. (Doing such a mistake
may cause errors in further steps)
This is to tell the compiler that the source files of our new system call
(sys_hello()) are in present in the hello directory.
If you are on a 32-bit system you’ll need to change ‘syscall_32.tbl’. For 64-bit,
change ‘syscall_64.tbl’.
cd arch/x86/entry/syscalls/
gedit syscall_64.tbl
P:F:-LTL-UG / 03 / R1 Sheet 75 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Go to the last of the document and add a new line like so:
Note:
Here 548 is written because in the previous line the number entry was
547. Remember this number it will be used in the later steps.
Also, note that I’ve written 64 in my system because it is 64 bit. You may
have to write i586 or x32. For knowing what is to be written check in this
file itself in many of the lines you may find entries like so:
P:F:-LTL-UG / 03 / R1 Sheet 76 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
cd include/linux/
gedit syscalls.h
Add the following line to the end of the document before the #endif statement:
Save and exit. This defines the prototype of the function of our system call. “asm-
linkage” is a key word used to indicate that all parameters of the function would
be available on the stack.
Before starting to compile you need to install a few packages. Type the following
commands in your terminal:
to configure your kernel use the following command in your linux-4.17.4/ direc-
tory:
Once the above command is used to configure the Linux kernel, you will get a
pop up window with the list of menus and you can select the items for the new
configuration. If your unfamiliar with the configuration just check for the file sys-
tems menu and check whether “ext4” is chosen or not, if not select it and save
the configuration.
Now to compile the kernel you can use the make command:
sudo make
P:F:-LTL-UG / 03 / R1 Sheet 77 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
Pro Tip: The make command can take a lot of time in compiling, to speed up the
process you can take advantage of the multiple cores that our systems have these
days. Simply type,
where n is the number of cores that you have in your linux system. For example if
you have a Quad core(4) processor, you can write:
It will create some files under /boot/ directory and it will automatically make a
entry in your grub.cfg. To check whether it made correct entry, check the files un-
der /boot/ directory . If you have followed the steps without any error you will
find the following files in it in addition to others.
1. System.map-4.17.4
2. vmlinuz-4.17.4
3. initrd.img-4.17.4
4. config-4.17.4
Now to update the kernel in your system reboot the system . You can use the fol-
lowing command:
shutdown -r now
After rebooting you can verify the kernel version using the following command:
uname -r
4.17.4
P:F:-LTL-UG / 03 / R1 Sheet 78 of 79
Downloaded by Techno ([email protected])
lOMoARcPSD|48529975
cd ~
gedit userspace.c
Note: Remember to keep in mind the number of system call that is added in
syscalls_64.tbl? In my case the number was 548. Write that same number in
your userspace.c file as an argument in syscall() function.
gcc userspace.c
./a.out
If all the steps are done correctly you’ll get an output like below:
Now, to check the message of your kernel run the following command:
dmesg
This will display Hello world at the end of the kernel’s message.
P:F:-LTL-UG / 03 / R1 Sheet 79 of 79
Downloaded by Techno ([email protected])