You are on page 1of 59

OPERATING SYSTEMS

BY MS. NIDA E RUB


A process is a
program in
execution.

PROCESS
quantum = 2 unit
PROCESS CREATION AND DELETION,
Within the domain of operating systems, the emergence
and removal of processes assume vital functions in the
management and control of system resources.
There are two basic operations that can be performed on
a process:
Creation
Deletion.
PROCESS CREATION AND DELETION,
PROCESS CREATION AND DELETION,

Process Creation
1. When a new process is created, the operating system
assigns a unique Process Identifier (PID) to it and
inserts a new entry in the primary process table.
2. Then required memory space for all the elements of the
process such as program, data, and stack is allocated
including space for its Process Control Block (PCB).
PROCESS CREATION AND DELETION,

Process Deletion:
 Processes are terminated by themselves when they finish executing their last statement,
then operating system USES exit( ) system call to delete its context.
 Then all the resources held by that process like physical and virtual memory, 1/0 buffers, open
files, etc., are taken back by the operating system. A process P can be terminated either by the
operating system or by the parent process of P.
 A parent may terminate a process due to one of the following reasons:
 When task given to the child is not required now.
 When the child has taken more resources than its limit.
 The parent of the process is exiting, as a result, all its children are deleted. This is called
cascaded termination.
PROCESS CREATION: FORK() AND EXEC()

Every application(program) comes into execution through


means of process, process is a running instance of a
program.
Processes are created through different system calls, most
popular are fork() and exec()
FORK() AND EXEC()

 The Fork system call is used for creating a new process in Linux, and
Unix systems, which is called the child process, which runs concurrently
with the process that makes the fork() call (parent process).
 After a new child process is created, both processes will execute the next
instruction following the fork() system call.
 The child process uses the same pc(program counter), same CPU
registers, and same open files which use in the parent process. It takes no
parameters and returns an integer value.
FORK() AND EXEC()
fork() pid_t pid = fork();

 fork() creates a new process by duplicating the calling process, The new process, referred
to as child, is an exact duplicate of the calling process, referred to as parent, except for the
following :
 The child has its own unique process ID, and this PID does not match the ID of any
existing process group.
 The child’s parent process ID is the same as the parent’s process ID.
 Return value of fork() On success, the PID of the child process is returned in the
parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child
process is created, and errno is set appropriately.
If fork() is called once, hence the output is
printed twice (2 power 1). If fork() is called,
say 3 times, then the output would be printed
8 times (2 power 3). If it is called 5 times,
then it prints 32 times and so on and so forth.
#include <unistd.h>
#include <stdio.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
// Fork failed
perror("fork");
return 1; }
else if (pid == 0) { // Child process
printf("Hello from the child process! (PID: %d)\n", getpid());
}
else {// Parent process
printf("Hello from the parent process! (PID: %d)\n", getpid());
}
return 0;
}
FORK() AND EXEC()
exec()
 Each of the functions in the exec family replaces the current process
image with a new process image.
 The new image is constructed from a regular, executable file called the
new process image file.
 This file is either an executable object file or a file of data for an
interpreter.
 There is no return from a successful call to one of these functions
because the calling process image is overlaid by the new process image.
Syntax: file: points to the file name
associated with the file being
int execvp (const char *file, char *const argv[]); executed.
argv: is a null terminated array
of character pointers.
• Create two .C files EXEC.c and execDemo.c
• and we will replace the execDemo.c with EXEC.c
by calling execvp() function in execDemo.c.

//EXEC.c

#include<stdio.h>
#include<unistd.h> •Now,create an
int main() executable file of
{ int i; EXEC.c using command
printf("I am EXEC.c called by execvp() "); gcc EXEC.c -o EXEC
printf("\n");
return 0;
}
//execDemo.c

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h> Now, create an executable
int main() file of execDemo.c using
{//A null terminated array of character pointers command
char *args[]={"./EXEC",NULL}; gcc execDemo.c -o
execvp(args[0],args); execDemo
/*All statements are ignored after execvp() call as this whole
process(execDemo.c) is replaced by another process (EXEC.c) */

printf("Ending-----");

return 0;}
•After running the executable file of
execDemo.c by using command ./excDemo, we
get the following output:
I AM EXEC.c called by execvp()
fork vs exec
1. In a UNIX operating system, the fork is a command that allows a
process to copy itself. However, in a UNIX operating system, exec is a
command that creates a new process by replacing the existing one.
2. The fork() makes a child's process equal to the parent's process. On the
other hand, the exec() makes a child process and replaces it with the
parent process.
3. After invoking the fork(), there is a child process and a parent process.
In contrast, there is only a child process after invoking the exec().
4. The parent and child processes are in separate address spaces in
the fork(). On the other hand, the child address space replaces the
parent address space in the exec().
Features Fork() Exec()
Definition It is a command that allows a It is a command that makes a
process to copy itself. new process by replacing the
existing process.
Address Space The parent and child The child address space replaces
processes are in separate the parent address space in the
address spaces in the fork(). exec().
Parent Process There is a child process and a There is only a child process
parent process after calling after calling the exec().
the fork() function.
Result The fork() makes a child's The exec() makes a child
process equal to the parent's process and replaces it with the
process. parent process.
Process Termination
■ Process executes last statement and asks the operating system to
decide it (exit).
■ Output data from child to parent (via wait).
■ Process’ resources are deallocated by operating system.
■ Parent may terminate execution of children processes (abort).
■ Child has exceeded allocated resources.
■ Task assigned to child is no longer required.
■ Parent is exiting.
■ Operating system does not allow child to continue if its parent terminates.
■ Cascading termination.
Interrupts
■ Signal generated by IO Devices to get the attention of CPU
Instruction Cycle + Interrupts
Multiple Interrupts
Multiple Interrupts - Priority
THREAD IN OPERATING SYSTEM
THREAD
Within a program, a Thread is a separate execution path. It is a
lightweight process that the operating system can schedule and
run concurrently with other threads.
The operating system creates and manages threads, and they
share the same memory and resources as the program that
created them.
This enables multiple threads to collaborate and work efficiently
within a single program.
THREAD
Threads are also called lightweight processes as they
possess some of the properties of processes.
Each thread belongs to exactly one process.
In an operating system that supports multithreading, the
process can consist of many threads. But threads can be
effective only if CPU is more than 1 otherwise two
threads have to context switch for that single CPU.
WHY DO WE NEED THREAD?
 Threads run in parallel improving the application performance.
 Each such thread has its own CPU state and stack, but they share the address space of the
process and the environment.
 Threads can share common data so they do not need to use inter-process communication.
Like the processes, threads also have states like ready, executing, blocked, etc.
 Priority can be assigned to the threads just like the process, and the highest priority thread
is scheduled first.
 Each thread has its own Thread Control Block (TCB).
 Like the process, a context switch occurs for the thread, and register contents are saved in
(TCB). As threads share the same address space and resources, synchronization is also required
for the various activities of the thread.
DIFFERENCE BETWEEN PROCESS AND
THREAD

 The primary difference is that threads within the


same process run in a shared memory space,
while processes run in separate memory spaces.
 Threads are not independent of one another like
processes are, and as a result, threads share with
other threads their code section, data section,
and OS resources (like open files and signals).
But, like a process, a thread has its own program
counter (PC), register set, and stack space.
TYPES OF THREADS

Threads are of two types.


User Level Thread
Kernel Level Thread
USER LEVEL THREADS
Is implemented in the user level library
User Level Thread is a type of thread that is not created using
system calls.
The kernel has no work in the management of user-level
threads.
User-level threads can be easily implemented by the user.
 Thread switching does not need to call OS and to cause
interrupt to Kernel.
KERNEL LEVEL THREADS
A kernel Level Thread is a type of thread that can recognize the
Operating system easily.
Kernel Level Threads has its own thread table where it keeps
track of the system.
The operating System Kernel helps in managing threads.
Kernel Threads have somehow longer context switching time.
Kernel helps in the management of threads.
MULTI-THREADING
MULTITHREADING IN OPERATING SYSTEM
 Lets say, for example a program is not capable of reading keystrokes while making drawings.
These tasks cannot be executed by the program at the same time. This problem can be solved
through multitasking so that two or more tasks can be executed simultaneously.
 Multitasking is of two types: Processor based and thread based.
 Processor based multitasking is totally managed by the OS, however multitasking through multithreading can be
controlled by the programmer to some extent.
 The concept of multi-threading needs proper understanding of these two terms – a process
and a thread.
 A process is a program being executed.
 A process can be further divided into independent units known as threads.
 A thread is like a small light-weight process within a process. Or we can say a collection of threads
is what is known as a process.
MULTI-THREADING

Multithreading is the ability of a


program or an operating system to
enable more than one user at a time
without requiring multiple copies of
the program running on the computer.
Multithreading can also handle
multiple requests from the same user.
WHY MULTI-THREADING?
 The idea is to achieve parallelism by dividing a process into multiple
threads.
 For example, in a browser, multiple tabs can be different threads.
 MS Word uses multiple threads: one thread to format the text, another thread
to process inputs, etc.
 Multithreading is a technique used in operating systems to improve the
performance and responsiveness of computer systems.
 Multithreading allows multiple threads (i.e., lightweight processes) to share
the same resources of a single process, such as the CPU, memory, and I/O
devices.
MULTITHREADED SERVER ARCHITECTURE

Responsiveness – may allow continued execution if part of process is blocked, especially important for
user interfaces
Resource Sharing – threads share resources of process, easier than shared memory or message passing
Economy – cheaper than process creation, thread switching lower overhead than context switching
Scalability – process can take advantage of multiprocessor architectures
MULTICORE PROGRAMMING
 Multicore or multiprocessor systems putting pressure on programmers, challenges
include:
 Dividing activities
 Balance
 Data splitting
 Data dependency
 Testing and debugging

 Parallelism implies a system can perform more than one task simultaneously
 Concurrency supports more than one task making progress
 Single processor / core, scheduler providing concurrency
MULTICORE PROGRAMMING (CONT.)

 Types of parallelism
 Data parallelism – distributes subsets of the same data across multiple cores,
same operation on each
 Task parallelism – distributing threads across cores, each thread performing
unique operation
 As # of threads grows, so does architectural support for threading
 CPUs have cores as well as hardware threads
 Consider Oracle SPARC T4 with 8 cores, and 8 hardware threads per core
CONCURRENCY VS. PARALLELISM

 Concurrent execution on single-core system:

 Parallelism on a multi-core system:


SINGLE AND MULTITHREADED PROCESSES
MULTITHREADING MODELS

 Many to one multithreading model


 One to one multithreading model
 Many to Many multithreading models
MANY-TO-ONE
 Many user-level threads mapped to single
kernel thread
 One thread blocking causes all to block
 Multiple threads may not run in parallel on
muticore system because only one may be in
kernel at a time
 Few systems currently use this model
 Examples:
 Solaris Green Threads
 GNU Portable Threads
ONE-TO-ONE
 Each user-level thread maps to kernel thread
 Creating a user-level thread creates a kernel thread
 More concurrency than many-to-one
 Number of threads per process sometimes restricted
due to overhead
 Examples
 Windows
 Linux
 Solaris 9 and later
MANY-TO-MANY MODEL

 Allows many user level threads to be


mapped to many kernel threads
 Allows the operating system to
create a sufficient number of kernel
threads
 Solaris prior to version 9
 Windows with the ThreadFiber
package
THREAD LIBRARIES

Thread library provides programmer with API for


creating and managing threads
Two primary ways of implementing
Library entirely in user space
Kernel-level library supported by the OS
THREAD PROGRAMMING USING PTHREADS
PTHREADS
 In a Unix/Linux operating system, the C/C++ languages provide the POSIX thread(
pthread) standard API(Application program Interface) for all thread related functions.
 It allows us to create multiple threads for parallel process flow.
 It is most effective on multiprocessor or multi-core systems where threads can be
implemented on a kernel-level for achieving the speed of execution.
 The POSIX threading interface
 Portable Operating System Interface for UNIX. A POSIX standard (IEEE 1003.1c)
API for thread creation and synchronization
 Common in UNIX operating systems (Solaris, Linux, Mac OS X)
THREAD PROGRAMMING USING PTHREADS
We must include the pthread.h header file at the
beginning of the script to use all the functions of the
pthreads library.
To execute the c file, we have to use the -pthread or -
lpthread in the command line while compiling the file.
cc -pthread file.c
cc -lpthread file.c
This function has the following arguments:

1. Thread identifier: The location where the ID of the newly created thread will
be stored, &thread.
2. Thread attributes: The thread attribute object specifying the attributes for
the thread that is being created. If attributes are NULL, it creates the thread
using default settings.
3. Function to run: This is the location of the function or in simple terms, the
function name the thread is to run, FunctionName.
4. Function arguments: These are the function arguments for the function the
thread is running, NULL.
• We create the thread.
#include <pthread.h> • Here, the first argument is the location of the thread
#include <stdio.h> identifier.
• The second argument is the thread attributes which are
ThreadFunction(void *arguments) NULL here.
{ • The third argument is the function name this thread will
printf("Thread Running\n"); execute and the last argument is the parameters we pass to
this function, which in this case are NULL.
return NULL;
• pthread_create(&thread1, NULL, ThreadFunction
} , NULL);

int main()
{
// Creating the Location where the ID of the newly created thread will be stored
pthread_t thread1;
printf("Calling Thread \n");
// Creating the thread
pthread_create(&thread1, NULL, ThreadFunction, NULL);
return 0;
} // Output: Calling Thread
PTHREADS EXAMPLE
PTHREADS EXAMPLE (CONT.)
Pthreads Example (Cont.)
Pthreads Code for Joining 10 Threads
PTHREADS CODE FOR JOINING 10
THREADS
READING ASSIGNMENT

Read Chapter 4
Operating Systems Internals and Design Principles
Ninth Edition
Global Edition
William Stallings

You might also like