0% found this document useful (0 votes)
6 views90 pages

Module 2.1 OS Principles

This document outlines key principles of operating systems, focusing on system calls, process management, and kernel components. It discusses the structure and lifecycle of processes, including creation, termination, and the role of process control blocks. Additionally, it covers user/kernel modes, interrupts, and the relationship between system calls and application programming interfaces (APIs).

Uploaded by

anantvmanoj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views90 pages

Module 2.1 OS Principles

This document outlines key principles of operating systems, focusing on system calls, process management, and kernel components. It discusses the structure and lifecycle of processes, including creation, termination, and the role of process control blocks. Additionally, it covers user/kernel modes, interrupts, and the relationship between system calls and application programming interfaces (APIs).

Uploaded by

anantvmanoj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Operating System Principles

Module – 2

Dr. Rabindra Kumar Singh


Module – 2 – OS Principles
 System calls
 System/Application Call Interface
 Protection: User/Kernel modes
 Interrupts
 Processes
 Structures (Process Control Block, Ready List etc.)
 Process creation
 Management in Unix
 Threads:
 User level
 kernel level threads and thread models.

Dr. Rabindra Kumar Singh BCSE303L


Operating-System Principles
 System Calls
 System/Application Call Interface
 Protection User/Kernel modes
 Interrupts
 Processes and Threads
 Structures (Process Control Block, Ready List etc)

Dr. Rabindra Kumar Singh BCSE303L


Operating Systems and Kernels

 Operating system boundary?


 Kernels
 Device drivers

 Boot loader

 Command Shell or other UI

 Basic File Systems and Utilities

Dr. Rabindra Kumar Singh BCSE303L


Components of a Kernel
 Interrupt handlers
 ISRs
 Schedulers
 Memory management
 N/w and Inter-process communication

Dr. Rabindra Kumar Singh BCSE303L


Where does a kernel reside?
 Protected memory space
 Full access to the hardware resources

 This system state and memory space


collectively called – Kernel Space

 User Space – Applications


 How they access hardware resources?

Dr. Rabindra Kumar Singh BCSE303L


How user applications access hardware?

Dr. Rabindra Kumar Singh BCSE303L


System Calls
 Enables
 Abstraction
 Protection

 Fault Isolation

 Some Libraries shares one to one relation with


system calls (open)
 Some Libraries shares many to one relation
with system calls (printf)

Dr. Rabindra Kumar Singh BCSE303L


Points to Ponder
 Identify what happens when a user C program
calls printf()?

 How many other calls it make to eventually


access the display? (Hardware resource)

 Similarly you can explore for many different c


library function calls

Dr. Rabindra Kumar Singh BCSE303L


…System Calls…
 Can an application execute system call?
 How is protection ensured if applications can
execute system calls?

 Applications requests kernel to execute system


calls (executing in kernel space)
 Kernels actually execute system calls on behalf of
applications (executing in process context)

Dr. Rabindra Kumar Singh BCSE303L


API – System Call – OS Relationship

Dr. Rabindra Kumar Singh BCSE303L


Standard C Library Example
 C program invoking printf() library call, which calls write()
system call

Dr. Rabindra Kumar Singh BCSE303L


Types of System Calls
 Process control
 end, abort
 load, execute
 create process, terminate process
 get process attributes, set process attributes
 wait for time
 wait event, signal event
 allocate and free memory
 File management
 create file, delete file
 open, close file
 read, write, reposition
 get and set file attributes

Dr. Rabindra Kumar Singh BCSE303L


Types of System Calls (Cont.)
 Device management
 request device, release device
 read, write, reposition
 get device attributes, set device attributes
 logically attach or detach devices
 Information maintenance
 get time or date, set time or date
 get system data, set system data
 get and set process, file, or device attributes
 Communications
 create, delete communication connection
 send, receive messages
 transfer status information
 attach and detach remote devices

Dr. Rabindra Kumar Singh BCSE303L


Examples of Windows and Unix System Calls

Dr. Rabindra Kumar Singh BCSE303L


Interrupts

Dr. Rabindra Kumar Singh BCSE303L


How can any device talk to the processor?

Interrupts

Polling

DMA
(Devices include I/O and Disks)

Dr. Rabindra Kumar Singh BCSE303L


How OS handles interrupts?

So when a hardware interrupt occurs, will the


OS creates process?
No, Instead interrupts run in a special context
called “Interrupt Context”

Dr. Rabindra Kumar Singh BCSE303L


State of processor with respect to OS

One of the three


Executing user code in user space (process
context)
Executing system calls in kernel space (process
context)
Executing system call in kernel space (interrupt
context)

Dr. Rabindra Kumar Singh BCSE303L


Process

Dr. Rabindra Kumar Singh BCSE303L


Process
A program in execution

Process is an entity
A thing with distinct and independent existence

Each process has its own address space


Text region
Data region
Stack region

Dr. Rabindra Kumar Singh BCSE303L


Continued…
Text Region
Stores the code that the processor executes.

Data Region
Stores variables and dynamically allocated memory that
the process uses during execution.

Stack Region
Stores instruction and local variables for active procedure
calls

Dr. Rabindra Kumar Singh BCSE303L


Program Vs Process

Program is an inanimate entity

Process is a program in execution

Dr. Rabindra Kumar Singh BCSE303L


Question for Thought

Why is a process’s address space divided into


multiple regions?

Dr. Rabindra Kumar Singh BCSE303L


Process States: Life cycle of a process

OS must ensure that each process receives a


sufficient amount of processor time

During its lifetime, process moves through a


series of discrete process states

Various events can cause a process to change


state

Dr. Rabindra Kumar Singh BCSE303L


continued…
Running
If a process is executing in the processor
Ready
I If a process could execute on a processor if it is
available
Blocked
If its waiting for some event to happen before it
can proceed

Dr. Rabindra Kumar Singh BCSE303L


Continued….
When a user runs a program, processes are created
and inserted in the ready list

A process moves towards the head of the list as


other processes complete their turns using a
processor

When a processor reaches the head of the list and


when a processor becomes available, that process is
given the processor

Dr. Rabindra Kumar Singh BCSE303L


Continued….
It is said to make the state transition from
ready to running

Dispatching: The act of assigning the


processor to the first process in the list

Dispatching is done by an entity called


dispatchers

Dr. Rabindra Kumar Singh BCSE303L


Continued….
To prevent process to monopolize the
hardware, interrupting clocks are used
(also called interval timer)

A process can voluntarily relinquish its


resource and the process goes into Blocked
states

Dr. Rabindra Kumar Singh BCSE303L


Process State

Dr. Rabindra Kumar Singh BCSE303L


Process control blocks(PCB)
The operating system performs several operation
when it creates the process

To identify each process, PID numbers are


assigned

OS creates a PCB also called process descriptor


which maintains information that the OS needs to
manage the process

Dr. Rabindra Kumar Singh BCSE303L


Continued…
The information in PCB are
PID
Process state
Program Counter
Scheduling priority
Credentials(the data that determines the resources
this process can access)
A pointer to the parent process
Pointers to the child processes
Pointers to allocated resources(like files)

Dr. Rabindra Kumar Singh BCSE303L


Continued…
PCB also contains the register contents called
the execution context of the processor on
which the process was last running

Process Table:
Pointer to per-user process table to access PCB
quickly

Dr. Rabindra Kumar Singh BCSE303L


Dr. Rabindra Kumar Singh BCSE303L
Question

At any given time, only one process can be


executing instructions on a computer.-
True/False?

Name some events that might cause a process


to enter the blocked state

Dr. Rabindra Kumar Singh BCSE303L


Process management
Creating process

Destroying process

Suspending process

Resuming process

Changing a process’s priority

Enable IPC

Dr. Rabindra Kumar Singh BCSE303L


Process creation

A process may spawn a new process

The creating process is called :Parent

The created process/processes : Child

Each child process is created exactly by one


parent( Hierarchical)

Dr. Rabindra Kumar Singh BCSE303L


Process creation in unix
Many processes are spawned from the init
process
Init process is created when the kernel loads

INIT

Kswapd khubd pdflush login xfs Klogd

bash

vi mypgm

Dr. Rabindra Kumar Singh BCSE303L


Printing process id

Int main(void)
{
printf("hello world from process ID %d\n",
getpid());
exit(0);
}

Dr. Rabindra Kumar Singh BCSE303L


In unix - fork()

We call fork to create a new process, which is


a copy of the caller
The caller is the parent and that the newly
created process is the child.
fork returns the non-negative process ID of
the new child process to the parent, and
returns 0 to the child
fork is called once by the parent but returns
twice in the parent and in the child

Dr. Rabindra Kumar Singh BCSE303L


What will the child do?
The Child and the Parent will have separate
PIDs
The child will inherit all of the open
descriptors from the Parent
Internally the pages i.e. the stack regions
which can be modified unlike the text region,
will be shared until one of them tries to
modify the contents.

Dr. Rabindra Kumar Singh BCSE303L


#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
int main( )
{ pid_t child_pid;
child_pid = fork (); // Create a new child process;
if (child_pid < 0) { printf("fork failed"); return 1; }
else
if (child_pid == 0)
{ printf ("child process successfully created!\n");
printf ("child_PID = %d,parent_PID = %d\n", getpid(), getppid( ) ); } else
{
wait(NULL);
printf ("parent process successfully created!\n");
printf ("child_PID = %d, parent_PID = %d", getpid( ), getppid( ) );
}
return 0;
}
Output
child process successfully created! child_PID = 31497,
parent_PID = 31496 parent process successfully created!
child_PID = 31496, parent_PID = 31491

Dr. Rabindra Kumar Singh BCSE303L


void main(void)
{
fork();
pid = getpid();
for (i = 1; i <= 100; i++) {
printf("This line is from pid %d, value = %d\n", pid, i);
}}

Dr. Rabindra Kumar Singh BCSE303L


Continued…

Dr. Rabindra Kumar Singh BCSE303L


Continued…

Dr. Rabindra Kumar Singh BCSE303L


Continued…
These processes are run concurrently, their
output lines are intermixed in a rather
unpredictable way

The order of these lines are determined by the


CPU scheduler.

Dr. Rabindra Kumar Singh BCSE303L


Dr. Rabindra Kumar Singh BCSE303L
Process control functions in Unix

fork()

exec()

waitpid()

Dr. Rabindra Kumar Singh BCSE303L


exec()

exec is a functionality of an operating system


that runs an executable file in the context of
an already existing process, replacing the
previous executable.

The current process is overlaid with the new


function

Dr. Rabindra Kumar Singh BCSE303L


Sample code
if ((pid = fork()) < 0) {
err_sys("fork error");
}
else if (pid == 0)
{ /* child */
execlp(buf, buf, (char *)0);
err_ret("couldn't execute: %s", buf);
exit();
}

Dr. Rabindra Kumar Singh BCSE303L


Six variants of exec()

execl
execle
execlp
execv
execvp
execve

Dr. Rabindra Kumar Singh BCSE303L


execve
int execve(char *path, char **argv, char **envp);
path is the name of an executable file

Execve() overwrites the current process so


that it executes the file in path with the
arguments in argv, and the environment
variables in envp.

Dr. Rabindra Kumar Singh BCSE303L


Continued…
main(int argc, char **argv, char **envp)
{
char *newargv[3];
int i;
newargv[0] = "cat";
newargv[1] = "exec2.c";
newargv[2] = NULL;
i = execve("/bin/cat", newargv, envp);
perror("exec2: execve() failed");
exit(1);
}

Dr. Rabindra Kumar Singh BCSE303L


Process Termination

There are eight ways for a process to


terminate

Normal termination occurs in five ways:


1. Return from main
2. Calling exit
3. Calling _exit or _Exit
4. Return of the last thread from its start routine
5. Calling pthread_exit

Dr. Rabindra Kumar Singh BCSE303L


Continued…

Abnormal termination occurs in three ways:


Calling abort
Receipt of a signal
Response of the last thread to a cancellation
request

Dr. Rabindra Kumar Singh BCSE303L


Exit() in unix

Three functions terminate a program normally


#include <stdlib.h>
void exit(int status);
void _Exit(int status);
#include <unistd.h>
void _exit(int status);
_exit and _Exit return to the kernel immediately
exit performs certain clean up processing and
then returns to the kernel

Dr. Rabindra Kumar Singh BCSE303L


Continued…

exit and _Exit are specified by ISO C

_exit is specified by POSIX.1

exit()
Performs a clean shutdown of the standard I/O
library
fclose function is called for all open streams
This causes all buffered output data to be flushed

Dr. Rabindra Kumar Singh BCSE303L


Continued…
All three exit functions expect a single integer
argument, which we call the exit status

Both the following functions are equal


exit(0);
return(0); (From the main function)

Dr. Rabindra Kumar Singh BCSE303L


How a program in C starts and how it terminates?

Dr. Rabindra Kumar Singh BCSE303L


Exit Handler in C
Every process can register for exit handlers

There can be at the most 32 exit handlers for the process

Exit handlers are functions written to perform something

The exit handlers are executed in the same order as they


are registered

Exit Handler  atexit()

Dr. Rabindra Kumar Singh BCSE303L


Sample Exit Program
#include "apue.h"
static void my_exit1(void);
static void my_exit2(void);
int main(void)
{
if (atexit(my_exit2) != 0)
err_sys("can't register my_exit2");

if (atexit(my_exit1) != 0)
err_sys("can't register my_exit1");

if (atexit(my_exit1) != 0)
err_sys("can't register my_exit1");

printf("main is done\n");
return(0);
}

Dr. Rabindra Kumar Singh BCSE303L


Continued…
static void my_exit1(void)
{
printf("first exit handler\n");
}

static void my_exit2(void)


{
printf("second exit handler\n");
}

Dr. Rabindra Kumar Singh BCSE303L


Exit Status
For any of the exit cases, we want the terminating
process to be able to notify its parent how it
terminated
For the three exit functions (exit, _exit, and
_Exit), this is done by passing an exit status as the
argument to the function
In the case of an abnormal termination, however,
the kernel, not the process, generates a
termination status to indicate the reason for the
abnormal termination

Dr. Rabindra Kumar Singh BCSE303L


Continued…

The parent of the process can obtain the


termination status from either the wait or the
waitpid function

Dr. Rabindra Kumar Singh BCSE303L


What happens if parent terminates before?

init process becomes the parent process of any


process whose parent terminates

whenever a process terminates, the kernel goes


through all active processes to see whether the
terminating process is the parent of any process
that still exists
If so, the parent process ID of the surviving
process is changed to be 1 (the process ID of init).

Dr. Rabindra Kumar Singh BCSE303L


When a child disappeared

The parent wouldn't be able to fetch its termination


status
The kernel keeps a small amount of information for
every terminating process, so that the information is
available when the parent of the terminating process
calls wait or waitpid
Minimally, this information consists of the process ID,
the termination status of the process, and the
amount of CPU time taken by the process

Dr. Rabindra Kumar Singh BCSE303L


Continued…

The kernel can discard all the memory used by


the process and close its open files

In UNIX System terminology, a process that


has terminated, but whose parent has not yet
waited for it, is called a zombie

Dr. Rabindra Kumar Singh BCSE303L


Wait()

When a process terminates, either normally or


abnormally, the kernel notifies the parent by
sending the SIGCHLD signal to the parent.

Because the termination of a child is an


asynchronous event.

It can happen at any time while the parent is


running

Dr. Rabindra Kumar Singh BCSE303L


Continued…

This signal is the asynchronous notification


from the kernel to the parent

The parent can choose to ignore this signal, or


it can provide a function that is called when
the signal occurs: a signal handler

The default action for this signal is to be


ignored.

Dr. Rabindra Kumar Singh BCSE303L


Continued…
A process that calls wait or waitpid can
Block, if all of its children are still running
Return immediately with the termination status of
a child, if a child has terminated and is waiting for
its termination status to be fetched
Return immediately with an error, if it doesn't
have any child processes

Dr. Rabindra Kumar Singh BCSE303L


Continued…
If the process is calling wait because it
received the SIGCHLD signal, we expect wait
to return immediately

But if we call it at any random point in time, it


can block

Dr. Rabindra Kumar Singh BCSE303L


Continued…
#include <sys/wait.h>
pid_t wait(int *statloc);
pid_t waitpid(pid_t pid, int *statloc, int options);

Returns process ID if OK or 1 on error

statloc is a pointer to an integer

Dr. Rabindra Kumar Singh BCSE303L


Continued…
If this argument is not a null pointer, the
termination status of the terminated process
is stored in the location pointed to by the
argument
If a child has already terminated and is a
zombie, wait returns immediately with that
child's status
Otherwise, it blocks the caller until a child
terminates

Dr. Rabindra Kumar Singh BCSE303L


Continued…
If the caller blocks and has multiple children,
wait returns when one terminates

We can always tell which child terminated,


because the process ID is returned by the
function

Dr. Rabindra Kumar Singh BCSE303L


Wait Vs waitpid

The wait function can block the caller until a


child process terminates, whereas waitpid has
an option that prevents it from blocking.

The waitpid function doesn't wait for the child


that terminates first; it has a number of
options that control which process it waits for.

Dr. Rabindra Kumar Singh BCSE303L


Example

Void pr_exit(int status)


{
if (WIFEXITED(status))
printf("normal termination:%d”,WEXITSTATUS(status));
else if (WIFSIGNALED(status))
{printf("abnormal termination:%d”, WTERMSIG(status));
else if (WIFSTOPPED(status))
printf("child stopped:%d\n", WSTOPSIG(status));
}

Dr. Rabindra Kumar Singh BCSE303L


Continued…
#include <sys/wait.h>
Int main(void)
{
pid_t pid;
int status;
if ((pid = fork()) < 0)
printf("fork error");
else if (pid == 0) /* child */
exit(0);
Dr. Rabindra Kumar Singh BCSE303L
Continued…
if (wait(&status) != pid)
printf("wait error");
pr_exit(status);
if ((pid = fork()) < 0)
printf("fork error");
else if (pid == 0)
abort(); //Generates SIGABRT

Dr. Rabindra Kumar Singh BCSE303L


Continued…
if (wait(&status) != pid)
printf("wait error");
pr_exit(status);
}

Dr. Rabindra Kumar Singh BCSE303L


Macro Description
WIFEXITED(status) True if status was returned for a child that terminated normally. In this case, we can
execute
WEXITSTATUS (status)
to fetch the low-order 8 bits of the argument that the child passed to exit, _exit,or _Exit.
WIFSIGNALED (status) True if status was returned for a child that terminated abnormally, by receipt of a signal
that it didn't catch. In this case, we can execute
WTERMSIG (status)
to fetch the signal number that caused the termination.
Additionally, some implementations (but not the Single UNIX Specification) define the
macro
WCOREDUMP (status)
that returns true if a core file of the terminated process was generated.
WIFSTOPPED (status) True if status was returned for a child that is currently stopped. In this case, we can
execute
WSTOPSIG (status)
to fetch the signal number that caused the child to stop.
WIFCONTINUED (status) True if status was returned for a child that has been continued after a job control stop
(XSI extension to POSIX.1; waitpid only).

Dr. Rabindra Kumar Singh BCSE303L


Waitpid

Waits for a specific process


pid == 1
Waits for any child process. In this respect, waitpid
is equivalent to wait.
pid > 0
Waits for the child whose process ID equals pid
pid == 0
Waits for any child whose process group ID equals
that of the calling process

Dr. Rabindra Kumar Singh BCSE303L


Self Suspension
A process must obtain its process ID and then
pass the ID as an argument to suspend itself.
Pause function
int pause(void);
Causes the invoking process (or thread) to sleep
until a signal is received that either terminates it
or causes it to call a signal-catching function.
Since pause() suspends thread execution
indefinitely unless interrupted by a signal, there is
no successful completion return value.

Dr. Rabindra Kumar Singh BCSE303L


Continued…
Kill
int kill(pid_t pid, int sig);
If pid is greater than 0, sig shall be sent to the process
whose process ID is equal to pid.
If pid is 0, sig shall be sent to all processes (excluding
an unspecified set of system processes)
If pid is -1, sig shall be sent to all processes (excluding
an unspecified set of system processes) for which the
process has permission to send that signal.

Dr. Rabindra Kumar Singh BCSE303L


Continued…
Sigaction()
#include <signal.h>
int sigaction(int sig, const struct sigaction
*restrict act, struct sigaction *restrict oact);
The sigaction() function allows the calling
process to examine and/or specify the action
to be associated with a specific signal.

Dr. Rabindra Kumar Singh BCSE303L


Continued…
Alarm Function:
The alarm function allows us to set a timer that
will expire at a specified time in the future
When the timer expires, the SIGALRM signal is
generated
If we ignore or don't catch this signal, its default
action is to terminate the process.

Dr. Rabindra Kumar Singh BCSE303L


Continued…
#include <unistd.h>
unsigned int alarm(unsigned int seconds);
The seconds value is the number of clock
seconds in the future when the signal should
be generated.
There is only one of these alarm clocks per
process

Dr. Rabindra Kumar Singh BCSE303L


Continued…
If, when we call alarm, a previously registered
alarm clock for the process has not yet
expired, the number of seconds left for that
alarm clock is returned as the value of this
function.
That previously registered alarm clock is
replaced by the new value.

Dr. Rabindra Kumar Singh BCSE303L


Information Hiding

Implementation details are not generally


revealed

Hiding such details makes it possible to


change the implementation of a function
without rewriting code that uses the function.

Dr. Rabindra Kumar Singh BCSE303L


References

Silberschatz, Gagne, Galvin: Operating System Concepts, 6th Edition

Dr. Rabindra Kumar Singh BCSE303L


Dr. Rabindra Kumar Singh BCSE303L

You might also like