0% found this document useful (0 votes)
33 views43 pages

OS Lecture-4 (Processes Concept & Operations On Process)

Operating system lecture 4 notes Thapar university Coe Process management and operation on process

Uploaded by

Nihchal Chahal
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)
33 views43 pages

OS Lecture-4 (Processes Concept & Operations On Process)

Operating system lecture 4 notes Thapar university Coe Process management and operation on process

Uploaded by

Nihchal Chahal
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/ 43

OS Lecture-4

Processes Concept
&
Operations on Process
Process Concept
• An operating system executes a variety of programs:
– Batch system: jobs
– Time-shared systems: user programs or tasks

• Many modern process concepts are still expressed in terms of jobs,


(e.g. job scheduling), and the two terms are often used
interchangeably.
The Process
• In computing, a process is an instance of a computer program that
is being executed.

• It contains the program code and its current activity.

• A program is a passive entity, such as a file containing a list of


instructions stored on disk (often called an executable file).

• In contrast, a process is an active entity, with a program counter


specifying the next instruction to execute and a set of associated
resources.

A program becomes a process when an executable file is loaded in the memory.


Process Memory
• Process memory is divided into four
sections:
1. The text section comprises the compiled
program code, read in from non-volatile storage
when the program is launched.
2. The data section stores global and static
variables, allocated and initialized prior to
executing main.
3. The heap is used for dynamic memory allocation,
and is managed via calls to new, delete, malloc,
free, etc.
4. The stack is used for local variables. Space on the
stack is reserved for local variables when they
are declared (at function entrance or elsewhere,
depending on the language), and the space is
freed up when the variables go out of scope.
Process State

1. New
2. Ready
3. Run
4. Terminate
5. Block
6. Suspend Ready
7. Suspend Block
Process State Diagram

1. New State:
– A process is said to be in new state when a program present in the
secondary memory is initiated for execution.
Process State Diagram

2. Ready State :
– A process moves from new state to ready state after it is loaded into
the main memory and is ready for execution.
– In ready state, the process waits for its execution by the processor.
– In multiprogramming environment, many processes may be present
in the ready state.
Process State Diagram

3. Run State :
– A process moves from ready state to run state after it is assigned the
CPU for execution.
Process State Diagram

4. Terminate State :
– A process moves from run state to terminate state after its execution
is completed.
Process State Diagram

5. Block or Wait State :


– A process moves from run state to block or wait state if it requires an
I/O operation or some blocked resource during its execution.
– After the I/O operation gets completed or resource becomes
available, the process moves to the ready state.
Process State Diagram

6. Suspend Ready State :


– A process moves from ready state to suspend ready state if a process
with higher priority has to be executed but the main memory is full.
– The process remains in the suspend ready state until the main memory
becomes available.
– When main memory becomes available, the process is brought back to
the ready state.
Process State Diagram

7. Suspend Wait State :


– A process moves from wait state to suspend wait state if a process with
higher priority has to be executed but the main memory is full.
– After the resource becomes available, the process is moved to the
suspend ready state.
– After main memory becomes available, the process is moved to the
ready state.
Important Points

State Present in Memory


New state Secondary Memory
Ready state Main Memory
Run state Main Memory
Wait state Main Memory
Suspend wait state Secondary Memory
Suspend ready state Secondary Memory
Terminate state –
Process Control Block (PCB)
• Each process is represented in the operating system by a process
control block (PCB)—also called a task control block.
• It contains many pieces of information associated with a specific
process.
Process Control Block (contd.)
• Process state: The state may be new, ready, running and so on.

• Program counter: It indicates the address of the next instruction to be executed


for this program.

• CPU registers: These vary in number and type based on architecture. They include
accumulators, stack pointers, general purpose registers etc.

• CPU scheduling information: This includes process priority, pointers to scheduling


queues and any scheduling parameters.

• Memory-management information: This includes information about the memory


allocated to the process.

• Accounting information: It includes amount of CPU and real time used, time limits,
etc.

• I/O status information: It includes list of I/O devices allocated to this process, a list
of open files etc.
Operations on Process
• System must provide mechanisms for:

– process creation,

– process termination,

– and so on as detailed next.


Process Creation
Process Creation
• During the course of execution, a process may create several new
processes (called spawning).

• The creating process is called a parent process, and the new


processes are called the children processes.

• Each of these new processes may in turn create other processes,


forming a tree of processes.

• Most operating systems including UNIX, Linux, and Windows


identify processes according to a unique process identifier (or pid).
− used as an index to access various attributes of a process within the
kernel.
A Tree of Processes in Linux
A Tree of Processes in Linux (cont.)
• The init process (which always has a pid of 1) serves as the root parent process for
all user processes.
• Once the system has booted, the init process can also create various user
processes, such as a web or print server, an ssh server, and the like.
• The kthreadd process is responsible for creating additional processes that perform
tasks on behalf of the kernel (in this situation, khelper and pdflush).
• The sshd process is responsible for managing clients that connect to the system by
using ssh (which is short for secure shell).
• The login process is responsible for managing clients that directly log onto the
system.
• In this example, a client has logged on and is using the bash shell, which has been
assigned pid 8416.
• Using the bash command-line interface, this user has created the process ps as
well as the emacs editor.
• On UNIX and Linux systems, we can obtain a listing of processes by using the ps
command. For example, the command ps -el
Process Creation: Execution & Address Space
• After process creation, two possibilities exist in terms of
execution:
1. Parent continues to execute with its children.

2. Parent waits until some or all of its children have terminated.

• After process creation, two possibilities exist in terms of


address space:
1. Child process is a duplicate of the parent process (it has the
same program and data as the parent).

2. Child process has a new program loaded into it.


Process Creation in UNIX
• Three types of system calls are used:

1.fork(): Creates a child process that has the same


environment as its parent but only the PID is different. This
procedure is known as forking.

2.exec(): After forking the process, the address space of the


child process is overwritten by the new process data. No new
process is created over here. The PID & PPID remains
unchanged.

3.wait(): The parent executes wait system call to wait for


the child process to complete its execution.
fork() System Call
• Fork system call is used for creating a new process, which is called 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.

• A child process uses the same pc (program counter), same CPU registers,
same open files which use in the parent process.
Example-1
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
fork();
printf("Hello world!\n");
return 0;
}
Output:
Hello world!
Hello world!
Example-2
Calculate number of times hello is printed:
int main()
{ Output:
fork(); hello
hello
fork();
hello
fork();
hello
printf("hello\n"); hello
return 0; hello
} hello
hello

Total number of child processes created = 2n -1


where n is the number of calls to fork()
Syntax of fork()
• Syntax: pid_t fork(void); //defined in <unistd.h>

• The pid_t data type is a signed integer type which is capable of


representing a process ID:

− Negative Value: creation of a child process was unsuccessful.


− Zero: Returned to the newly created child process.
− Positive value: Returned to parent or caller. The value contains process ID
of newly created child process.

fork()
Parent Child

Returns PID of child Returns 0


Example-1
Predict the Output of the following program:

void fork_example()
{
if (fork() == 0)
printf("Hello from Child!\n");
else
printf("Hello from Parent!\n");
}

int main()
{
fork_example();
return 0;
}
Example-1
Predict the Output of the following program:

void fork_example()
{
if (fork() == 0)
printf("Hello from Child!\n");
else
printf("Hello from Parent!\n");
}
Output:
int main() Hello from Parent!
{ Hello from Child!
fork_example(); OR
return 0; Hello from Child!
} Hello from Parent!
Example-2
Predict the Output of the following program:
int main()
{
int x = 1;
pid_t pid = fork();
if (pid == 0)
printf("Child has x = %d\n", ++x);
else
printf("Parent has x = %d\n", --x);
printf("Bye from process %d with x = %d\n", getpid(), x);
return 0; Output:
}
Parent has x = 0
Bye from process 1234 with x = 0
Child has x = 2
Bye from process 1235 with x = 2
Example-3
How many child processes will be created in the following code:

int main()
{
if(!fork())
{
if(!fork())
fork();
}
fork();
}
}
Ans: 7 child processes will be created.
exec() System Call
• When an exec() system call is invoked, the program specified in
the perimeter to exec() will replace the entire process.

• The new program is loaded into the same process space.

• PID of the process is not changed.


– but the data, code, stack, heap, etc. of the process are changed and are
replaced with those of newly loaded process.

• In C language, exec() system call is a collection of functions:


– execl()
– execle()
– execlp()
– execv()
– execve()
– execvp()
Example
#include <stdio.h> #include<stdio.h>
#include <unistd.h> #include<unistd.h>
#include <stdlib.h> #include<stdlib.h>
int main(int argc, char *argv[])
{ int main()
printf("PID of example.c = {
%d\n", getpid()); printf("We are in hello.c\n");
char *args[] = {"Hello", “World", printf("PID of hello.c is %d",
NULL}; getpid());
execv("./hello", args); return 0;
printf("Back to example.c"); }
return 0;
}

example.c hello.c

Output:
PID of example.c = 4733
We are in hello.c
PID of hello.c = 4733
fork() vs exec()

Features fork() exec()


Definition It is a command that allows a It is a command that makes
process to copy itself. a new process by replacing
the existing process.
Address The parent and child processes The child address space
Space are in separate address spaces replaces the parent address
in the fork(). space in the exec().
Parent There is a child process and a There is only a child process
Process parent process after calling the after calling the exec().
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
process. the parent process.
wait() System Call
• The wait() system call suspends execution of the current
process until one of its children terminates.

• Parent moves itself to the ready queue while child completes.

• Syntax:
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *wstatus);

➢ Returns the process ID (PID) of the child that terminated.

➢ int *wstatus: A pointer to an integer where the exit status of


the terminated child will be stored. You can pass NULL if you don't
care about the status.
Example
#include<unistd.h>
#include<sys/types.h>
#include<stdio.h>
#include<sys/wait.h>
int main()
{
pid_t p;
printf("before fork\n");
p=fork();
if(p==0)//child
{
printf("I am child having id %d\n",getpid());
printf("My parent's id is %d\n",getppid());
}
else//parent
{
wait(NULL);
printf("My child's id is %d\n",p);
printf("I am parent having id %d\n",getpid());
}
printf("Common\n");
}
Process Termination
Process Termination
• A process terminates when it finishes its final statement and asks the
operating system to delete it by using the exit() system call.

• The terminating process may return a status value (typically an integer) to


its parent process via the wait() system call.
pid = wait(&status);

• All the resources of the terminated process including:


– physical and virtual memory
– open files
– I/O buffers
are deallocated by the operating system.

• A parent needs to know the identities of its children. Thus, when one
process creates a new process, the identity of the newly created process is
passes to the parent.
Process Termination (cont.)
• A process may terminate the execution of one of its children
for a variety of reasons:

1. The child has exceeded its usage of some of the resources that
it has been allocated.

2. The task assigned to the child is no longer required.

3. The parent is exiting, and the operating system does not allow
a child to continue if its parent terminates.
− Cascading termination: All children, grandchildren, etc. are
terminated.
exit() System Call
• We can terminate a process by using exit() system call.

• Its parent process may wait for the termination of a child process by
using the wait() system call.

• The wait() system call returns the process identifier of a


terminated child so that the parent can tell which of its children has
terminated.

• In UNIX, if the parent terminates, then all its children are assigned
init process as their new parent process.

• The children still have a parent to collect their status and execution
statistics.
Zombie Process
• When a child exits, some process must wait on it to get its exit
code. That exit code is stored in the process table until this
happens. The act of reading that exit code is called “reaping” the
child.

• Between the time a child exits and is reaped, it is called a zombie.

• Zombies only occupy space in the process table. They take no


memory or CPU.
Example
/* A C program to demonstrate Zombie Process. Child becomes Zombie as
parent is sleeping when child process exits.*/
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// Fork returns process id in parent process
pid_t child_pid = fork();

// Parent process
if (child_pid > 0)
sleep(50);

// Child process
else
exit(0);

return 0;
}
Orphan Process
• If a process exits with children still running, those children are
orphans.

• Orphaned children are immediately “adopted” by init.

• If parent terminates without invoking wait(), process is an


orphan.
Example
/* A C program to demonstrate Orphan Process. Parent process finishes
execution while the child process is running. The child process
becomes orphan.*/
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// Create a child process
int pid = fork();

if (pid > 0)
printf("in parent process");

else if (pid == 0)
{
sleep(30);
printf("in child process");
}

return 0;
}

You might also like