SlideShare a Scribd company logo
1 of 24
Unit III
Processes and Signals:
Process: – Process concept, Kernel support for process, process attributes, process control-
process creation with fork (), vfork (), exec () family system calls. Waiting for a process,
process termination, zombie process, orphan process. Exit () and atexit () functions.
Signals – Introduction to signals, Signal generation and handling with
signal, sigaction, kill, raise, alarm, pause, abort, sleep functions.
A process begins its life when it is created. A process goes through different states before it gets
terminated. The first state that any process goes through is the creation of itself. Process creation
happens through the use of fork() system call, which creates a new process(child process) by
duplicating an existing one(parent process). The process that calls fork() is the parent, whereas
the new process is the child.
In most cases, we may want to execute a different program in child process than the parent. The
exec() family of function calls creates a new address space and loads a new program into it.
Finally, a process exits or terminates using the exit() system call. This function frees all the
resources held by the process(except for pcb). A parent process can enquire about the status of a
terminated child using wait() system call. When the parent process uses wait() system call, the
parent process is blocked till the child on which it is waiting terminates.
If you find reading boring, you can watch process creation videos to understand the below
concepts.
Process Control Block
While creating a process the operating system performs several operations. To
identify the processes, it assigns a process identification number (PID) to each
process. As the operating system supports multi-programming, it needs to
keep track of all the processes. For this task, the process control block (PCB)
is used to track the process’s execution status. Each block of memory contains
information about the process state, program counter, stack pointer, status of
opened files, scheduling algorithms, etc. All these information is required and
must be saved when the process is switched from one state to another. When
the process makes a transition from one state to another, the operating system
must update information in the process’s PCB.
A process control block (PCB) contains information about the process, i.e.
registers, quantum, priority, etc. The process table is an array of PCB’s, that
means logically contains a PCB for all of the current processes in the system.
 Pointer – It is a stack pointer which is required to be saved when the
process is switched from one state to another to retain the current
position of the process.
 Process state – It stores the respective state of the process.
 Process number – Every process is assigned with a unique id
known as process ID or PID which stores the process identifier.
 Program counter – It stores the counter which contains the address
of the next instruction that is to be executed for the process.
 Register – These are the CPU registers which includes: accumulator,
base, registers and general purpose registers.
 Memory limits – This field contains the information about memory
management system used by operating system. This may include the
page tables, segment tables etc.
 Open files list – This information includes the list of files opened for
a process.
Miscellaneous accounting and status data – This field includes information
about the amount of CPU used, time constraints, jobs or process number, etc.
The process control block stores the register content also known as execution
content of the processor when it was blocked from running. This execution
content architecture enables the operating system to restore a process’s
execution context when the process returns to the running state. When the
process makes a transition from one state to another, the operating system
updates its information in the process’s PCB. The operating system maintains
pointers to each process’s PCB in a process table so that it can access the
PCB quickly.
program/command when executed, a special instance is provided by the system to the process.
This instance consists of all the services/resources that may be utilized by the process under
execution.
 Whenever a command is issued in Unix/Linux, it creates/starts a new process. For
example, pwd when issued which is used to list the current directory location the
user is in, a process starts.
 Through a 5-digit ID number Unix/Linux keeps an account of the processes, this
number is call process ID or PID. Each process in the system has a unique PID.
 Used up pid’s can be used in again for a newer process since all the possible
combinations are used.
 At any point of time, no two processes with the same pid exist in the system because
it is the pid that Linux uses to track each process.
Initializing a process
A process can be run in two ways:
Method 1: Foreground Process: Every process when started runs in foreground by default,
receives input from the keyboard, and sends output to the screen. When issuing pwd command
$ ls pwd
Output:
$ /home/geeksforgeeks/root
When a command/process is running in the foreground and is taking a lot of time, no other
processes can be run or started because the prompt would not be available until the program
finishes processing and comes out.
Method 2: Background Process: It runs in the background without keyboard input and waits
till keyboard input is required. Thus, other processes can be done in parallel with the process
running in the background since they do not have to wait for the previous process to be
completed.
Adding & along with the command starts it as a background process
$ pwd &
Since pwd does not want any input from the keyboard, it goes to the stop state until moved to
the foreground and given any data input. Thus, on pressing Enter:
Output:
[1] + Done pwd
$
That first line contains information about the background process – the job number and the
process ID. It tells you that the ls command background process finishes successfully. The
second is a prompt for another command.
Tracking ongoing processes
ps (Process status) can be used to see/list all the running processes.
$ ps
PID TTY TIME CMD
19 pts/1 00:00:00 sh
24 pts/1 00:00:00 ps
For more information -f (full) can be used along with ps
$ ps –f
UID PID PPID C STIME TTY TIME CMD
52471 19 1 0 07:20 pts/1 00:00:00f sh
52471 25 19 0 08:04 pts/1 00:00:00 ps -f
For single-process information, ps along with process id is used
$ ps 19
PID TTY TIME CMD
19 pts/1 00:00:00 sh
For a running program (named process) Pidof finds the process id’s (pids)
Process Attributes
Fields described by ps are described as:
 UID: User ID that this process belongs to (the person running it)
 PID: Process ID
 PPID: Parent process ID (the ID of the process that started it)
 C: CPU utilization of process
 STIME: Process start time
 TTY: Terminal type associated with the process
 TIME: CPU time is taken by the process
 CMD: The command that started this process
There are other options which can be used along with ps command:
 -a: Shows information about all users
 -x: Shows information about processes without terminals
 -u: Shows additional information like -f option
 -e: Displays extended information
Stopping a process:
When running in foreground, hitting Ctrl + c (interrupt character) will exit the command. For
processes running in background kill command can be used if it’s pid is known.
$ ps –f
UID PID PPID C STIME TTY TIME CMD
52471 19 1 0 07:20 pts/1 00:00:00 sh
52471 25 19 0 08:04 pts/1 00:00:00 ps –f
$ kill 19
Terminated
If a process ignores a regular kill command, you can use kill -9 followed by the process ID.
$ kill -9 19
Terminated
Other process commands:
bg: A job control command that resumes suspended jobs while keeping them running in the
background
Syntax:
bg [ job ]
For example:
bg 19
fg: It continues a stopped job by running it in the foreground.
Syntax:
fg [ %job_id ]
For example
fg 19
top: This command is used to show all the running processes within the working environment
of Linux.
Syntax:
top
nice: It starts a new process (job) and assigns it a priority (nice) value at the same time.
Syntax:
nice [-nice value]
nice value ranges from -20 to 19, where -20 is of the highest priority.
renice : To change the priority of an already running process renice is used.
Syntax:
renice [-nice value] [process id]
df: It shows the amount of available disk space being used by file systems
Syntax:
df
Output:
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/loop0 18761008 15246876 2554440 86% /
none 4 0 4 0% /sys/fs/cgroup
udev 493812 4 493808 1% /dev
tmpfs 100672 1364 99308 2% /run
none 5120 0 5120 0% /run/lock
none 503352 1764 501588 1% /run/shm
none 102400 20 102380 1% /run/user
/dev/sda3 174766076 164417964 10348112 95% /host
free: It shows the total amount of free and used physical and swap memory in the system, as
well as the buffers used by the kernel
Syntax:
free
Output:
total used free shared buffers cached
Mem: 1006708 935872 70836 0 148244 346656
-/+ buffers/cache: 440972 565736
Swap: 262140 130084 132056
Types of Processes
1. Parent and Child process: The 2nd and 3rd column of the ps –f command shows
process id and parent’s process id number. For each user process, there’s a parent
process in the system, with most of the commands having shell as their parent.
2. Zombie and Orphan process: After completing its execution a child process is
terminated or killed and SIGCHLD updates the parent process about the termination
and thus can continue the task assigned to it. But at times when the parent process
is killed before the termination of the child process, the child processes become
orphan processes, with the parent of all processes “init” process, becomes their new
pid.
A process which is killed but still shows its entry in the process status or the process
table is called a zombie process, they are dead and are not used.
3. Daemon process: They are system-related background processes that often run with
the permissions of root and services requests from other processes, they most of the
time run in the background and wait for processes it can work along with for ex print
daemon.
When ps –ef is executed, the process with ? in the tty field are daemon processes.
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.
It takes no parameters and returns an integer value. Below are different values returned by fork().
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.
Note: fork() is threading based function, to get the correct output run the program on a local
system.
Predict the Output of the following program:.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// make two process which run same
// program after this instruction
fork();
printf("Hello world!n");
return 0;
}
Output:
Hello world!
Hello world!
Calculate number of times hello is printed:
#include <stdio.h>
#include <sys/types.h>
int main()
{
fork();
fork();
fork();
printf("hellon");
return 0;
}
Output:
hello
hello
hello
hello
hello
hello
hello
hello
The number of times ‘hello’ is printed is equal to number of process created. Total Number of
Processes = 2n
, where n is number of fork system calls. So here n = 3, 23
= 8
$gedit forkprg.c
#include <stdio.h>
#include<unistd.h>
int main()
{
pid_t ret_val;
printf(“the process id is:%d”,getpid());
ret_val=fork();
if(ret_val<0)
{
//fork failure
printf(“nfork failedn”);
}
else if (ret_val==0)
{
//child process
printf(“nchild process”);
printf(“nchild process id is:%d”,getpid());
sleep(20);
}
else
{
//parent process
Wait();
printf(“nparent process”);
printf(“nparent process id is:%d”,getpid());
sleep(30);
}
return 0;
}
$gcc -o forkprg forkprg.c
$./forkprg
$ps -a1 //to check which process is running
Here, we’re starting a new process and using the variable pid to store the process identifier of the
child process created by the fork() call. We then proceed to check if the value of pid returned by
the fork() call is equal to zero. The fork() call returns the value of the child process as zero to
differentiate it from its parent. The actual value of the child process identifier is the value
returned to the parent process. Finally, we check for errors and print an error message.
After saving the changes, we use the cc command to compile fork_test.c:
$ cc fork_test.c
This creates an executable file called a.out in the working directory.
Finally, we can execute the a.out file:
$ ./a.out
This is the Parent process and pid is: 69032
This is the Child process and pid is: 69033
We can see here that the parent and child processes have different process identifiers.
In the output above, the fork() call returns the output twice, once in the parent
process and once in the child process.
We’re using the getpid() function call to get the actual PID of the parent and child
processes in the if…else block.
The exec system call is used to execute a file which is residing in an active process. When exec
is called the previous executable file is replaced and new file is executed.
More precisely, we can say that using exec system call will replace the old file or program from
the process with a new file or program. The entire content of the process is replaced with a new
program.
The user data segment which executes the exec() system call is replaced with the data file whose
name is provided in the argument while calling exec().
The new program is loaded into the same process space. The current process is just turned into a
new process and hence the process id PID is not changed, this is because we are not creating a
new process we are just replacing a process with another process in exec.
If the currently running process contains more than one thread then all the threads will be
terminated and the new process image will be loaded and then executed. There are no destructor
functions that terminate threads of current process.
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. The new process is executed from the entry
point.
Exec system call is a collection of functions and in C programming language, the standard names
for these functions are as follows:
1. execl
2. execle
3. execlp
4. execv
5. execve
6. execvp
It should be noted here that these functions have the same base exec followed by one or more
letters. These are explained below:
e: It is an array of pointers that points to environment variables and is passed explicitly to the
newly loaded process.
l: l is for the command line arguments passed a list to the function
p: p is the path environment variable which helps to find the file passed as an argument to be
loaded into process.
v: v is for the command line arguments. These are passed as an array of pointers to the function.
Why exec is used?
exec is used when the user wants to launch a new file or program in the same process.
execv()
gedit hello.c
#include<stdio.h>
#include<unistd.h>
Int main()
{
printf(“I am in hello processn”);
printf(“Process id of hello processis:%dn”,getpid());
return 0;
}
gedit execv_demo.c
#include<stdio.h>
#include<unistd.h>
Int main()
{
printf(“I am in exec processn”);
printf(“Process id of exec processis:%dn”,getpid());
char *args[]={“./hello”,NULL};
execv(args[0],args);
printf(“ncoming back to ecex processn”); // this not be executed
return 0;
}
gcc -o hello hello.c
gcc -o execv_demo ececv_demo.c
./ececv_demo
Difference between fork() and execv()
gedit hello.c
#include<stdio.h>
#include<unistd.h>
Int main()
{
printf(“I am in hello processn”);
printf(“Process id of hello processis:%dn”,getpid());
return 0;
}
gedit frok_ecec.c
#include <stdio.h>
#include<unistd.h>
int main()
{
pid_t ret_val;
printf(“the process id is:%d”,getpid());
ret_val=fork();
if(ret_val<0)
{
//fork failure
printf(“nfork failedn”);
}
else if (ret_val==0)
{
//child process
printf(“nchild process”);
printf(“nchild process id is:%d”,getpid());
printf(“ncall hello.c from child process”);
char *args[]={“./hello”,NULL};
execv(args[0],args);
printf(“ncoming back to child processn”); //
}
else
{
//parent process
printf(“nparent process”);
printf(“nparent process id is:%d”,getpid());
}
return 0;
}
gcc -o hello hello.c
gcc -o fork_exec fork_exec.c
./fork_exec
differences between fork() and exec() system calls -:
fork() exec()
1.
It is a system call in C
programming language It is a system call of operating system
2.
It is used to create a new
process exec() runs an executable file
3.
Its return value is an integer
type It does not creates new process
4.
It does not takes any
parameters. Here the Process identifier does not changes
5.
It can return three types of
integer values
In exec() the machine code, data, heap, and stack of the
process are replaced by the new program.
vfork()
Similar to the fork() system call, vfork() also creates a child process that’s identical to its
parent process. However, the child process temporarily suspends the parent process until it
terminates. This is because both processes use the same address space, which contains the stack,
stack pointer, and instruction pointer.
vfork() acts as a special case of the clone() system call. It creates new processes without copying
the address space of the parent process. This is useful in performance-oriented applications.
The parent process is always suspended once the child process is created. It remains
suspended until the child process terminates normally, abnormally, or until it executes
the exec system call starting a new process.
The child process created by the vfork() system call inherits its parent’s attributes. These include
file descriptors, current working directory, signal dispositions, and more.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
int n =10;
pid_t pid = vfork(); //creating the child process
if (pid == 0) //if this is a chile process
{
printf("Child process startedn");
}
else//parent process execution
{
printf("Now i am coming back to parent processn");
}
printf("value of n: %d n",n); //sample printing to check "n" value
return 0;
}
$gedit vforkprg.c
#include <stdio.h>
#include<unistd.h>
int main()
{
pid_t ret_val;
printf(“the process id is:%d”,getpid());
ret_val=vfork();
if(ret_val<0)
{
//fork failure
printf(“nfork failedn”);
}
else if (ret_val==0)
{
//child process
printf(“nchild process”);
printf(“nchild process id is:%d”,getpid());
sleep(20);
}
else
{
//parent process
Wait();
printf(“nparent process”);
printf(“nparent process id is:%d”,getpid());
sleep(30);
}
return 0;
}
$gcc -o vforkprg vforkprg.c
$./vforkprg
$ps -a1 //to check which process is running
Difference between fork() and vfork() system calls
fork() :
Fork() is system call which is used to create new process. New process created by fork() system
call is called child process and process that invoked fork() system call is called parent process.
Code of child process is same as code of its parent process. Once child process is created, both
parent and child processes start their execution from next statement after fork() and both
processes get executed simultaneously.
2. vfork() :
Vfork() is also system call which is used to create new process. New process created by vfork()
system call is called child process and process that invoked vfork() system call is called parent
process. Code of child process is same as code of its parent process. Child process suspends
execution of parent process until child process completes its execution as both processes share
the same address space.
Difference between fork() and vfork() :
S.No. FORK() VFORK()
1.
In fork() system call, child and parent process
have separate memory space.
While in vfork() system call, child and
parent process share same address space.
2.
The child process and parent process gets
executed simultaneously.
Once child process is executed then parent
process starts its execution.
3.
The fork() system call uses copy-on-write as
an alternative.
While vfork() system call does not use copy-
on-write.
4.
Child process does not suspend parent process
execution in fork() system call.
Child process suspends parent process
execution in vfork() system call.
5.
Page of one process is not affected by page of
other process.
Page of one process is affected by page of
other process.
S.No. FORK() VFORK()
6. fork() system call is more used. vfork() system call is less used.
7. There is wastage of address space. There is no wastage of address space.
8.
If child process alters page in address space, it
is invisible to parent process.
If child process alters page in address space,
it is visible to parent process.
Let’s create a simple C program to show how the vfork() system call works.
First, we create a file named vfork_test.c:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
pid_t pid = vfork(); //creating the child process
printf("parent process pid before if...else block: %dn", getpid());
if (pid == 0) { //checking if this is the a child process
printf("This is the child process and pid is: %dnn", getpid());
exit(0);
} else if (pid > 0) { //parent process execution
printf("This is the parent process and pid is: %dn", getpid());
} else {
printf("Error while forkingn");
exit(EXIT_FAILURE);
}
return 0;
}
Here, we’re using variable pid to store the PID of the child process created by the vfork() call.
We then check to see the value of the parent’s PID before the if…else block.
After saving the changes, let’s compile vfork_test.c:
$ cc vfork_test.c
Finally, we can execute the created a.out file:
$ ./a.out
parent process pid before if...else block: 117117
This is the child process and pid is: 117117
parent process pid before if...else block: 117116
This is the parent process and pid is: 117116
The vfork() system call returns the output twice, first in the child process and then in the parent
process.
Since both processes share the same address space, we have matching PID values in the first
output. In the if else block, the child process is run first because it blocks the parent process while
executing.
exec()
The exec() system function runs a new process in the context of an existing process and
replaces it. This is also referred to as an overlay.
The function doesn’t create a new process, so the PID doesn’t change. However, the new
process replaces the data, heap, stack, and machine code of the current process. It loads the
new process into the current process space and executes it from the entry point. Control never
returns to the original process unless there’s an exec() error.
This system function belongs to a family functions that
includes execl(), execlp(), execv(), execvp(), execle(), and execve().
Executing exec()
For a simple test, we’ll create two C programs to show how the exec() system call works. We’ll
use the exec() call to run the second program from the first program.
Let’s create the first program named exec_test1.c:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
printf("PID of exec_test1.c = %dn", getpid());
char *args[] = {"Hello", "From", "Parent", NULL};
execv("./exec_test2", args);
printf("Back to exec_test1.c");
return 0;
}
Here, we’re creating a function called main() and passing in arguments. Inside the function, we’re
printing the PID after fetching it using the getpid() function. We then declare a character array
where we pass in three strings as arguments. We’re calling the execv() system call, then passing
in the results of executing the second program as an argument.
Let’s now create the second program called exec_test2.c:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
printf("Hello from exec_test2.cn");
printf("PID of exec_test2.c process is: %dn", getpid());
return 0;
}
Here, we’re printing a message and the PID of the process launched by exec() from the first
program.
We use the cc command to compile exec_test1.c to an executable:
$ cc exec_test1.c -o exec_test1
This creates an executable file called exec_test1 in the working directory.
Then, we compile the second program:
$ cc exec_test2.c -o exec_test2
This creates an executable file called exec_test1 in the working directory.
Finally, we can execute the exec_test1 file:
$ ./exec_test1
PID of exec_test1.c = 171939
Hello from exec_test2.c
PID of exec_test2.c process is: 171939
From the output above, we can notice that the PID didn’t change in the second program’s process.
Furthermore, the last print statement from exec_test1.c file wasn’t printed. This is because
executing the execv() system call replaced the currently running process, and we haven’t included
a way of returning back to the first process.
Comparison
Let’s look at this table showing an overview and comparison of each of these system calls:
Comparison
Factor
fork() vfork() exec() clone()
Invoking
fork(), creates a
child process
of the invoking
process
vfork(), creates a
child process
that has shares
some attributes
with the parent
exec(), replaces
the
invoking
process
clone(), creates a
child
process and
offers more control
on data shared
Process ID
Parent process and
child process have
unique IDs
Parent process
and
child process have
the same ID
The process
running
and the process
that replaces it,
have the same
PID
Parent process and
child process have
unique IDs
but can share when
specified
Execution
Parent and child
processes start
simultaneously
Parent process is
temporarily
suspended while
child process runs
Parent process
is terminated
and the new
process
starts at entry
point
Parent and child
processes
start simultaneously
Zombie Processes
A zombie process is a process whose execution is completed but it still has an entry in
the process table. Zombie processes usually occur for child processes, as the parent
process still needs to read its child’s exit status. Once this is done using the wait system
call, the zombie process is eliminated from the process table. This is known as reaping
the zombie process.
A diagram that demonstrates the creation and termination of a zombie process is given
as follows
Zombie processes don't use any system resources but they do retain their process ID.
If there are a lot of zombie processes, then all the available process ID’s are
monopolized by them. This prevents other processes from running as there are no
process ID’s available.
 The child process completes its execution by using exit() system call.
 So when the child finishes it's execution ‘SIGCHLD’ signal is delivered to the parent
process by the kernel. Parents should,ideally, read the child's status from the process
table and then delete the child's entry.
 But here the parent does not wait for the child to terminate, rather it does its own
subsequent job, i.e. here sleeping for 60 seconds.
 So the child's exit status is never read by the parent and the child's entry continues to
remain there in the process table even when the child has died.
Note: Kernel sends a SIGCHLD signal to the parent process to indicate that the child process
has ended ·
// A C program to demonstrate Zombie Process.
#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(60);
// Child process
else
exit(0);
return 0;
}
Why are lots of zombie processes harmful to the system ?
A lot of zombie processes in os are harmful as
 The OS has one process table of finite size , so lots of zombie processes will results in a
full process table.
 A full process table means that OS cannot create a new process when required and
Zombie processes in os are of no use as the process has died but it's entry is occupying
the space in memory
An extreme case - Fork bomb The program below creates an infinitely many zombie
processes because the parent does not wait for it's child process.
#include <unistd.h>
int main()
{
while(1)
fork();
return 0;
}
 PIDs in os are finite, when all the PIDs have been consumed by Zombie Process, no
new process can be created.
 Solution: Reboot the system
Zombie Process Program
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main (int argc, char * argv[])
{
unsigned int pid;
int ret,i,j;
pid = getpid();
printf("My process id is : %un", pid );
printf("About to create child processs ....n");
//sleep(10);
ret =fork();
if ( ret < 0)
{
perror("fork");
}
if ( ret == 0 ) /* child process*/
{
printf("I am child process. mypid = %dn", getpid() );
printf(" I am child fork returned me : %dn", ret );
for(i=0;i<5;i++){
sleep(1);
printf("Child: i=%dn",i);
} exit(EXIT_SUCCESS);
}
else if ( ret > 0 ) /* parent process */
{
printf(" I am parent process my pid = %dn", getpid() );
printf(" I am parent and fork returned me : %dn", ret );
for(j=0;j<10;j++){
sleep(1);
printf("Parent: j=%dn",j);
} exit(EXIT_SUCCES);
}
printf("Commoncode");
exit(EXIT_SUCCESS);
}
Output:
Zombie Avoidance Program
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
int main (int argc, char *
argv[]){unsigned int pid ;
int ret,i,j;
pid = getpid();
printf("My process id is : %un", pid );
printf("About to create child processs ....n");
ret =fork();
if ( ret < 0)
{
perror("fork");
}
if ( ret == 0 ) /* child process*/{
printf("I am child process. mypid = %dn", getpid() );
printf(" I am child fork returned me : %dn", ret );
for(i=0;i<10;i++){
printf("Child: i=%dn",i);
} exit(EXIT_SUCCES);
}
else if ( ret > 0 ) /* parent process
*/ {int status;
printf(" I am parent process my pid = %dn", getpid() );
printf(" I am parent and fork returned me : %dn", ret );wait(&status);
if(WIFEXITED(status)){
printf("Child pid=%d terminated",ret);
printf("Child's exit status is %dn",WEXITSTATUS(status));
}
for(j=0;j<20;j++){
printf("Parent:
j=%dn",j);
}
exit(EXIT_SUCCESS
);
}
printf("Common
code");
exit(EXIT_SUCCESS);
}
Output:
Orphan Processes
Orphan processes are those processes that are still running even though their parent process
has terminated or finished. A process can be orphaned intentionally or unintentionally.
A process whose parent process no more exists i.e. either finished or terminated without
waiting for its child process to terminate is called an orphan process.
An intentionally orphaned process runs in the background without any manual support. This
is usually done to start an indefinitely running service or to complete a long-running job
without user attention.
An unintentionally orphaned process is created when its parent process crashes or terminates.
Unintentional orphan processes can be avoided using the process group mechanism.
 In the real world orphans are adopted by guardians who look after them.
 Similarly,the orphan process in linux is adopted by a new process , which is
mostly init process (pid=1) . This is called re-parenting.
 Reparenting is done by the kernel,when the kernel detects an orphan process in os,
and assigns a new parent process.
 New parent process asks the kernel for cleaning of the PCB of the orphan process and
the new parent waits till the child completes its execution.
Orphan Process Code Example
In the example,the parent process sleeps for 20 seconds while the child process sleeps for 30
seconds.
1. So, after sleeping for 20 seconds the parent completes its execution while the child
process is still there at least till 30 seconds.
2. When the child process becomes an orphan process, the kernel reassigns the parent
process to the child process.
3. As a result, the parent process id of the child process before and after sleep () will be
different.
Note: Kernel is central component of an operating system that manages operations of
computer and hardware.
// C program to demonstrate Orphan process
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int pid;
pid = fork();
if(pid == 0)
{
printf("I am the child, my process ID is %dn",getpid());
printf("My parent's process ID is %dn",getppid());
sleep(30);
printf("nAfter sleepnI am the child, my process ID is %dn",getpid());
printf("My parent's process ID is %dn",getppid());
exit(0);
}
else
{
sleep(20);
printf("I am the parent, my process ID is %dn",getpid());
printf("The parent's parent, process ID is %dn",getppid());
printf("Parent terminatesn");
}
return 0;
}
Output
My parent's process ID is 32005
I am the parent, my process ID is 32005
The parent's parent, process ID is 31998
Parent terminates
After sleep
I am the child, my process ID is 32006
My parent's process ID is 1
Why are too many Orphan processes harmful to the system?
 Orphan processes in OS hold resources when present the system.
 Orphan processes in a large number can overload the init process and hang-up a
system.
Conclusion
 A zombie process in OS is one that has completed its execution but its entry in the
process table.
 wait () system call is used to deal with zombie processes.
 An orphan process in OS is one which is executing but its parent process has
terminated is called an orphan process.
 Kernel allocates a new process as parent process to orphan process. Mostly the new
parent is the init process (pid=1).
 Too many zombie processes and orphan processes are harmful.

More Related Content

Similar to LP-Unit3.docx

Process management
Process managementProcess management
Process managementBirju Tank
 
System Calls - Introduction
System Calls - IntroductionSystem Calls - Introduction
System Calls - IntroductionTo Sum It Up
 
UNIT-2-Process-Management.pdf
UNIT-2-Process-Management.pdfUNIT-2-Process-Management.pdf
UNIT-2-Process-Management.pdfaakritii765
 
Operating System Practice : Meeting 5- process and manajemen proces-a-slide
Operating System Practice : Meeting 5- process and manajemen proces-a-slideOperating System Practice : Meeting 5- process and manajemen proces-a-slide
Operating System Practice : Meeting 5- process and manajemen proces-a-slideSyaiful Ahdan
 
Ch2_Processes_and_process_management_1.ppt
Ch2_Processes_and_process_management_1.pptCh2_Processes_and_process_management_1.ppt
Ch2_Processes_and_process_management_1.pptMohammad Almuiet
 
My ppt @ bec doms on process management
My ppt @ bec doms on process managementMy ppt @ bec doms on process management
My ppt @ bec doms on process managementBabasab Patil
 
My ppt @ bec doms on process management
My ppt @ bec doms on process managementMy ppt @ bec doms on process management
My ppt @ bec doms on process managementBabasab Patil
 
Operating Systems Unit Two - Fourth Semester - Engineering
Operating Systems Unit Two - Fourth Semester - EngineeringOperating Systems Unit Two - Fourth Semester - Engineering
Operating Systems Unit Two - Fourth Semester - EngineeringYogesh Santhan
 
Week 11Linux InternalsProcesses, schedulingLecture o.docx
Week 11Linux InternalsProcesses, schedulingLecture o.docxWeek 11Linux InternalsProcesses, schedulingLecture o.docx
Week 11Linux InternalsProcesses, schedulingLecture o.docxmelbruce90096
 
Tarea - 3 Actividad intermedia trabajo colaborativo 2
Tarea - 3 Actividad intermedia trabajo colaborativo 2Tarea - 3 Actividad intermedia trabajo colaborativo 2
Tarea - 3 Actividad intermedia trabajo colaborativo 2HectorFabianPintoOsp
 
13 process management
13 process management13 process management
13 process managementShay Cohen
 

Similar to LP-Unit3.docx (20)

Process management
Process managementProcess management
Process management
 
OS (1).pptx
OS (1).pptxOS (1).pptx
OS (1).pptx
 
System Calls - Introduction
System Calls - IntroductionSystem Calls - Introduction
System Calls - Introduction
 
UNIT-2-Process-Management.pdf
UNIT-2-Process-Management.pdfUNIT-2-Process-Management.pdf
UNIT-2-Process-Management.pdf
 
Os lab final
Os lab finalOs lab final
Os lab final
 
Process managment
Process  managmentProcess  managment
Process managment
 
Ch03- PROCESSES.ppt
Ch03- PROCESSES.pptCh03- PROCESSES.ppt
Ch03- PROCESSES.ppt
 
Operating System Practice : Meeting 5- process and manajemen proces-a-slide
Operating System Practice : Meeting 5- process and manajemen proces-a-slideOperating System Practice : Meeting 5- process and manajemen proces-a-slide
Operating System Practice : Meeting 5- process and manajemen proces-a-slide
 
Lecture 5 process concept
Lecture 5   process conceptLecture 5   process concept
Lecture 5 process concept
 
CH03.pdf
CH03.pdfCH03.pdf
CH03.pdf
 
Ch2_Processes_and_process_management_1.ppt
Ch2_Processes_and_process_management_1.pptCh2_Processes_and_process_management_1.ppt
Ch2_Processes_and_process_management_1.ppt
 
My ppt @ bec doms on process management
My ppt @ bec doms on process managementMy ppt @ bec doms on process management
My ppt @ bec doms on process management
 
My ppt @ bec doms on process management
My ppt @ bec doms on process managementMy ppt @ bec doms on process management
My ppt @ bec doms on process management
 
Unix kernal
Unix kernalUnix kernal
Unix kernal
 
Operating Systems
Operating Systems Operating Systems
Operating Systems
 
Operating Systems Unit Two - Fourth Semester - Engineering
Operating Systems Unit Two - Fourth Semester - EngineeringOperating Systems Unit Two - Fourth Semester - Engineering
Operating Systems Unit Two - Fourth Semester - Engineering
 
Cs8493 unit 2
Cs8493 unit 2Cs8493 unit 2
Cs8493 unit 2
 
Week 11Linux InternalsProcesses, schedulingLecture o.docx
Week 11Linux InternalsProcesses, schedulingLecture o.docxWeek 11Linux InternalsProcesses, schedulingLecture o.docx
Week 11Linux InternalsProcesses, schedulingLecture o.docx
 
Tarea - 3 Actividad intermedia trabajo colaborativo 2
Tarea - 3 Actividad intermedia trabajo colaborativo 2Tarea - 3 Actividad intermedia trabajo colaborativo 2
Tarea - 3 Actividad intermedia trabajo colaborativo 2
 
13 process management
13 process management13 process management
13 process management
 

Recently uploaded

IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).pptssuser5c9d4b1
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 

Recently uploaded (20)

IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
247267395-1-Symmetric-and-distributed-shared-memory-architectures-ppt (1).ppt
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 

LP-Unit3.docx

  • 1. Unit III Processes and Signals: Process: – Process concept, Kernel support for process, process attributes, process control- process creation with fork (), vfork (), exec () family system calls. Waiting for a process, process termination, zombie process, orphan process. Exit () and atexit () functions. Signals – Introduction to signals, Signal generation and handling with signal, sigaction, kill, raise, alarm, pause, abort, sleep functions. A process begins its life when it is created. A process goes through different states before it gets terminated. The first state that any process goes through is the creation of itself. Process creation happens through the use of fork() system call, which creates a new process(child process) by duplicating an existing one(parent process). The process that calls fork() is the parent, whereas the new process is the child. In most cases, we may want to execute a different program in child process than the parent. The exec() family of function calls creates a new address space and loads a new program into it. Finally, a process exits or terminates using the exit() system call. This function frees all the resources held by the process(except for pcb). A parent process can enquire about the status of a terminated child using wait() system call. When the parent process uses wait() system call, the parent process is blocked till the child on which it is waiting terminates. If you find reading boring, you can watch process creation videos to understand the below concepts. Process Control Block While creating a process the operating system performs several operations. To identify the processes, it assigns a process identification number (PID) to each process. As the operating system supports multi-programming, it needs to keep track of all the processes. For this task, the process control block (PCB) is used to track the process’s execution status. Each block of memory contains information about the process state, program counter, stack pointer, status of opened files, scheduling algorithms, etc. All these information is required and must be saved when the process is switched from one state to another. When
  • 2. the process makes a transition from one state to another, the operating system must update information in the process’s PCB. A process control block (PCB) contains information about the process, i.e. registers, quantum, priority, etc. The process table is an array of PCB’s, that means logically contains a PCB for all of the current processes in the system.  Pointer – It is a stack pointer which is required to be saved when the process is switched from one state to another to retain the current position of the process.  Process state – It stores the respective state of the process.  Process number – Every process is assigned with a unique id known as process ID or PID which stores the process identifier.  Program counter – It stores the counter which contains the address of the next instruction that is to be executed for the process.  Register – These are the CPU registers which includes: accumulator, base, registers and general purpose registers.  Memory limits – This field contains the information about memory management system used by operating system. This may include the page tables, segment tables etc.  Open files list – This information includes the list of files opened for a process. Miscellaneous accounting and status data – This field includes information about the amount of CPU used, time constraints, jobs or process number, etc. The process control block stores the register content also known as execution content of the processor when it was blocked from running. This execution content architecture enables the operating system to restore a process’s execution context when the process returns to the running state. When the process makes a transition from one state to another, the operating system updates its information in the process’s PCB. The operating system maintains pointers to each process’s PCB in a process table so that it can access the PCB quickly.
  • 3. program/command when executed, a special instance is provided by the system to the process. This instance consists of all the services/resources that may be utilized by the process under execution.  Whenever a command is issued in Unix/Linux, it creates/starts a new process. For example, pwd when issued which is used to list the current directory location the user is in, a process starts.  Through a 5-digit ID number Unix/Linux keeps an account of the processes, this number is call process ID or PID. Each process in the system has a unique PID.  Used up pid’s can be used in again for a newer process since all the possible combinations are used.  At any point of time, no two processes with the same pid exist in the system because it is the pid that Linux uses to track each process. Initializing a process A process can be run in two ways: Method 1: Foreground Process: Every process when started runs in foreground by default, receives input from the keyboard, and sends output to the screen. When issuing pwd command $ ls pwd Output: $ /home/geeksforgeeks/root When a command/process is running in the foreground and is taking a lot of time, no other processes can be run or started because the prompt would not be available until the program finishes processing and comes out. Method 2: Background Process: It runs in the background without keyboard input and waits till keyboard input is required. Thus, other processes can be done in parallel with the process running in the background since they do not have to wait for the previous process to be completed. Adding & along with the command starts it as a background process $ pwd & Since pwd does not want any input from the keyboard, it goes to the stop state until moved to the foreground and given any data input. Thus, on pressing Enter: Output: [1] + Done pwd $
  • 4. That first line contains information about the background process – the job number and the process ID. It tells you that the ls command background process finishes successfully. The second is a prompt for another command. Tracking ongoing processes ps (Process status) can be used to see/list all the running processes. $ ps PID TTY TIME CMD 19 pts/1 00:00:00 sh 24 pts/1 00:00:00 ps For more information -f (full) can be used along with ps $ ps –f UID PID PPID C STIME TTY TIME CMD 52471 19 1 0 07:20 pts/1 00:00:00f sh 52471 25 19 0 08:04 pts/1 00:00:00 ps -f For single-process information, ps along with process id is used $ ps 19 PID TTY TIME CMD 19 pts/1 00:00:00 sh For a running program (named process) Pidof finds the process id’s (pids) Process Attributes Fields described by ps are described as:  UID: User ID that this process belongs to (the person running it)  PID: Process ID  PPID: Parent process ID (the ID of the process that started it)  C: CPU utilization of process  STIME: Process start time  TTY: Terminal type associated with the process  TIME: CPU time is taken by the process  CMD: The command that started this process There are other options which can be used along with ps command:  -a: Shows information about all users  -x: Shows information about processes without terminals  -u: Shows additional information like -f option  -e: Displays extended information Stopping a process: When running in foreground, hitting Ctrl + c (interrupt character) will exit the command. For processes running in background kill command can be used if it’s pid is known. $ ps –f UID PID PPID C STIME TTY TIME CMD 52471 19 1 0 07:20 pts/1 00:00:00 sh 52471 25 19 0 08:04 pts/1 00:00:00 ps –f $ kill 19 Terminated If a process ignores a regular kill command, you can use kill -9 followed by the process ID. $ kill -9 19 Terminated
  • 5. Other process commands: bg: A job control command that resumes suspended jobs while keeping them running in the background Syntax: bg [ job ] For example: bg 19 fg: It continues a stopped job by running it in the foreground. Syntax: fg [ %job_id ] For example fg 19 top: This command is used to show all the running processes within the working environment of Linux. Syntax: top nice: It starts a new process (job) and assigns it a priority (nice) value at the same time. Syntax: nice [-nice value] nice value ranges from -20 to 19, where -20 is of the highest priority. renice : To change the priority of an already running process renice is used. Syntax: renice [-nice value] [process id] df: It shows the amount of available disk space being used by file systems Syntax: df Output: Filesystem 1K-blocks Used Available Use% Mounted on /dev/loop0 18761008 15246876 2554440 86% / none 4 0 4 0% /sys/fs/cgroup udev 493812 4 493808 1% /dev tmpfs 100672 1364 99308 2% /run none 5120 0 5120 0% /run/lock none 503352 1764 501588 1% /run/shm none 102400 20 102380 1% /run/user /dev/sda3 174766076 164417964 10348112 95% /host free: It shows the total amount of free and used physical and swap memory in the system, as well as the buffers used by the kernel Syntax: free Output: total used free shared buffers cached
  • 6. Mem: 1006708 935872 70836 0 148244 346656 -/+ buffers/cache: 440972 565736 Swap: 262140 130084 132056 Types of Processes 1. Parent and Child process: The 2nd and 3rd column of the ps –f command shows process id and parent’s process id number. For each user process, there’s a parent process in the system, with most of the commands having shell as their parent. 2. Zombie and Orphan process: After completing its execution a child process is terminated or killed and SIGCHLD updates the parent process about the termination and thus can continue the task assigned to it. But at times when the parent process is killed before the termination of the child process, the child processes become orphan processes, with the parent of all processes “init” process, becomes their new pid. A process which is killed but still shows its entry in the process status or the process table is called a zombie process, they are dead and are not used. 3. Daemon process: They are system-related background processes that often run with the permissions of root and services requests from other processes, they most of the time run in the background and wait for processes it can work along with for ex print daemon. When ps –ef is executed, the process with ? in the tty field are daemon processes. 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. It takes no parameters and returns an integer value. Below are different values returned by fork(). 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. Note: fork() is threading based function, to get the correct output run the program on a local system.
  • 7. Predict the Output of the following program:. #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { // make two process which run same // program after this instruction fork(); printf("Hello world!n"); return 0; } Output: Hello world! Hello world! Calculate number of times hello is printed: #include <stdio.h> #include <sys/types.h> int main() { fork(); fork(); fork(); printf("hellon"); return 0; } Output: hello hello hello hello hello hello hello hello The number of times ‘hello’ is printed is equal to number of process created. Total Number of Processes = 2n , where n is number of fork system calls. So here n = 3, 23 = 8
  • 8. $gedit forkprg.c #include <stdio.h> #include<unistd.h> int main() { pid_t ret_val; printf(“the process id is:%d”,getpid()); ret_val=fork(); if(ret_val<0) { //fork failure printf(“nfork failedn”); } else if (ret_val==0) { //child process printf(“nchild process”); printf(“nchild process id is:%d”,getpid()); sleep(20); } else { //parent process Wait(); printf(“nparent process”); printf(“nparent process id is:%d”,getpid()); sleep(30); } return 0; } $gcc -o forkprg forkprg.c $./forkprg $ps -a1 //to check which process is running Here, we’re starting a new process and using the variable pid to store the process identifier of the child process created by the fork() call. We then proceed to check if the value of pid returned by the fork() call is equal to zero. The fork() call returns the value of the child process as zero to differentiate it from its parent. The actual value of the child process identifier is the value returned to the parent process. Finally, we check for errors and print an error message. After saving the changes, we use the cc command to compile fork_test.c: $ cc fork_test.c This creates an executable file called a.out in the working directory. Finally, we can execute the a.out file: $ ./a.out This is the Parent process and pid is: 69032 This is the Child process and pid is: 69033 We can see here that the parent and child processes have different process identifiers. In the output above, the fork() call returns the output twice, once in the parent process and once in the child process. We’re using the getpid() function call to get the actual PID of the parent and child processes in the if…else block.
  • 9. The exec system call is used to execute a file which is residing in an active process. When exec is called the previous executable file is replaced and new file is executed. More precisely, we can say that using exec system call will replace the old file or program from the process with a new file or program. The entire content of the process is replaced with a new program. The user data segment which executes the exec() system call is replaced with the data file whose name is provided in the argument while calling exec(). The new program is loaded into the same process space. The current process is just turned into a new process and hence the process id PID is not changed, this is because we are not creating a new process we are just replacing a process with another process in exec. If the currently running process contains more than one thread then all the threads will be terminated and the new process image will be loaded and then executed. There are no destructor functions that terminate threads of current process. 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. The new process is executed from the entry point. Exec system call is a collection of functions and in C programming language, the standard names for these functions are as follows: 1. execl 2. execle 3. execlp 4. execv 5. execve 6. execvp It should be noted here that these functions have the same base exec followed by one or more letters. These are explained below: e: It is an array of pointers that points to environment variables and is passed explicitly to the newly loaded process. l: l is for the command line arguments passed a list to the function p: p is the path environment variable which helps to find the file passed as an argument to be loaded into process. v: v is for the command line arguments. These are passed as an array of pointers to the function. Why exec is used? exec is used when the user wants to launch a new file or program in the same process. execv() gedit hello.c #include<stdio.h> #include<unistd.h> Int main() { printf(“I am in hello processn”); printf(“Process id of hello processis:%dn”,getpid()); return 0; } gedit execv_demo.c #include<stdio.h>
  • 10. #include<unistd.h> Int main() { printf(“I am in exec processn”); printf(“Process id of exec processis:%dn”,getpid()); char *args[]={“./hello”,NULL}; execv(args[0],args); printf(“ncoming back to ecex processn”); // this not be executed return 0; } gcc -o hello hello.c gcc -o execv_demo ececv_demo.c ./ececv_demo Difference between fork() and execv() gedit hello.c #include<stdio.h> #include<unistd.h> Int main() { printf(“I am in hello processn”); printf(“Process id of hello processis:%dn”,getpid()); return 0; } gedit frok_ecec.c #include <stdio.h> #include<unistd.h> int main() { pid_t ret_val; printf(“the process id is:%d”,getpid()); ret_val=fork(); if(ret_val<0) { //fork failure printf(“nfork failedn”); } else if (ret_val==0) { //child process printf(“nchild process”); printf(“nchild process id is:%d”,getpid()); printf(“ncall hello.c from child process”); char *args[]={“./hello”,NULL}; execv(args[0],args); printf(“ncoming back to child processn”); // } else
  • 11. { //parent process printf(“nparent process”); printf(“nparent process id is:%d”,getpid()); } return 0; } gcc -o hello hello.c gcc -o fork_exec fork_exec.c ./fork_exec differences between fork() and exec() system calls -: fork() exec() 1. It is a system call in C programming language It is a system call of operating system 2. It is used to create a new process exec() runs an executable file 3. Its return value is an integer type It does not creates new process 4. It does not takes any parameters. Here the Process identifier does not changes 5. It can return three types of integer values In exec() the machine code, data, heap, and stack of the process are replaced by the new program. vfork() Similar to the fork() system call, vfork() also creates a child process that’s identical to its parent process. However, the child process temporarily suspends the parent process until it terminates. This is because both processes use the same address space, which contains the stack, stack pointer, and instruction pointer. vfork() acts as a special case of the clone() system call. It creates new processes without copying the address space of the parent process. This is useful in performance-oriented applications.
  • 12. The parent process is always suspended once the child process is created. It remains suspended until the child process terminates normally, abnormally, or until it executes the exec system call starting a new process. The child process created by the vfork() system call inherits its parent’s attributes. These include file descriptors, current working directory, signal dispositions, and more. #include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { int n =10; pid_t pid = vfork(); //creating the child process if (pid == 0) //if this is a chile process { printf("Child process startedn"); } else//parent process execution { printf("Now i am coming back to parent processn"); } printf("value of n: %d n",n); //sample printing to check "n" value return 0; } $gedit vforkprg.c #include <stdio.h> #include<unistd.h> int main() { pid_t ret_val; printf(“the process id is:%d”,getpid()); ret_val=vfork(); if(ret_val<0) { //fork failure printf(“nfork failedn”); } else if (ret_val==0) { //child process printf(“nchild process”); printf(“nchild process id is:%d”,getpid()); sleep(20); } else { //parent process Wait();
  • 13. printf(“nparent process”); printf(“nparent process id is:%d”,getpid()); sleep(30); } return 0; } $gcc -o vforkprg vforkprg.c $./vforkprg $ps -a1 //to check which process is running Difference between fork() and vfork() system calls fork() : Fork() is system call which is used to create new process. New process created by fork() system call is called child process and process that invoked fork() system call is called parent process. Code of child process is same as code of its parent process. Once child process is created, both parent and child processes start their execution from next statement after fork() and both processes get executed simultaneously. 2. vfork() : Vfork() is also system call which is used to create new process. New process created by vfork() system call is called child process and process that invoked vfork() system call is called parent process. Code of child process is same as code of its parent process. Child process suspends execution of parent process until child process completes its execution as both processes share the same address space. Difference between fork() and vfork() : S.No. FORK() VFORK() 1. In fork() system call, child and parent process have separate memory space. While in vfork() system call, child and parent process share same address space. 2. The child process and parent process gets executed simultaneously. Once child process is executed then parent process starts its execution. 3. The fork() system call uses copy-on-write as an alternative. While vfork() system call does not use copy- on-write. 4. Child process does not suspend parent process execution in fork() system call. Child process suspends parent process execution in vfork() system call. 5. Page of one process is not affected by page of other process. Page of one process is affected by page of other process.
  • 14. S.No. FORK() VFORK() 6. fork() system call is more used. vfork() system call is less used. 7. There is wastage of address space. There is no wastage of address space. 8. If child process alters page in address space, it is invisible to parent process. If child process alters page in address space, it is visible to parent process. Let’s create a simple C program to show how the vfork() system call works. First, we create a file named vfork_test.c: #include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main() { pid_t pid = vfork(); //creating the child process printf("parent process pid before if...else block: %dn", getpid()); if (pid == 0) { //checking if this is the a child process printf("This is the child process and pid is: %dnn", getpid()); exit(0); } else if (pid > 0) { //parent process execution printf("This is the parent process and pid is: %dn", getpid()); } else { printf("Error while forkingn"); exit(EXIT_FAILURE); } return 0; } Here, we’re using variable pid to store the PID of the child process created by the vfork() call. We then check to see the value of the parent’s PID before the if…else block. After saving the changes, let’s compile vfork_test.c: $ cc vfork_test.c Finally, we can execute the created a.out file: $ ./a.out parent process pid before if...else block: 117117 This is the child process and pid is: 117117 parent process pid before if...else block: 117116 This is the parent process and pid is: 117116
  • 15. The vfork() system call returns the output twice, first in the child process and then in the parent process. Since both processes share the same address space, we have matching PID values in the first output. In the if else block, the child process is run first because it blocks the parent process while executing. exec() The exec() system function runs a new process in the context of an existing process and replaces it. This is also referred to as an overlay. The function doesn’t create a new process, so the PID doesn’t change. However, the new process replaces the data, heap, stack, and machine code of the current process. It loads the new process into the current process space and executes it from the entry point. Control never returns to the original process unless there’s an exec() error. This system function belongs to a family functions that includes execl(), execlp(), execv(), execvp(), execle(), and execve(). Executing exec() For a simple test, we’ll create two C programs to show how the exec() system call works. We’ll use the exec() call to run the second program from the first program. Let’s create the first program named exec_test1.c: #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char *argv[]) { printf("PID of exec_test1.c = %dn", getpid()); char *args[] = {"Hello", "From", "Parent", NULL}; execv("./exec_test2", args); printf("Back to exec_test1.c"); return 0; } Here, we’re creating a function called main() and passing in arguments. Inside the function, we’re printing the PID after fetching it using the getpid() function. We then declare a character array where we pass in three strings as arguments. We’re calling the execv() system call, then passing in the results of executing the second program as an argument. Let’s now create the second program called exec_test2.c: #include <stdio.h> #include <unistd.h> #include <stdlib.h> int main(int argc, char *argv[]) { printf("Hello from exec_test2.cn"); printf("PID of exec_test2.c process is: %dn", getpid()); return 0; } Here, we’re printing a message and the PID of the process launched by exec() from the first program.
  • 16. We use the cc command to compile exec_test1.c to an executable: $ cc exec_test1.c -o exec_test1 This creates an executable file called exec_test1 in the working directory. Then, we compile the second program: $ cc exec_test2.c -o exec_test2 This creates an executable file called exec_test1 in the working directory. Finally, we can execute the exec_test1 file: $ ./exec_test1 PID of exec_test1.c = 171939 Hello from exec_test2.c PID of exec_test2.c process is: 171939 From the output above, we can notice that the PID didn’t change in the second program’s process. Furthermore, the last print statement from exec_test1.c file wasn’t printed. This is because executing the execv() system call replaced the currently running process, and we haven’t included a way of returning back to the first process. Comparison Let’s look at this table showing an overview and comparison of each of these system calls: Comparison Factor fork() vfork() exec() clone() Invoking fork(), creates a child process of the invoking process vfork(), creates a child process that has shares some attributes with the parent exec(), replaces the invoking process clone(), creates a child process and offers more control on data shared Process ID Parent process and child process have unique IDs Parent process and child process have the same ID The process running and the process that replaces it, have the same PID Parent process and child process have unique IDs but can share when specified Execution Parent and child processes start simultaneously Parent process is temporarily suspended while child process runs Parent process is terminated and the new process starts at entry point Parent and child processes start simultaneously Zombie Processes A zombie process is a process whose execution is completed but it still has an entry in the process table. Zombie processes usually occur for child processes, as the parent process still needs to read its child’s exit status. Once this is done using the wait system
  • 17. call, the zombie process is eliminated from the process table. This is known as reaping the zombie process. A diagram that demonstrates the creation and termination of a zombie process is given as follows Zombie processes don't use any system resources but they do retain their process ID. If there are a lot of zombie processes, then all the available process ID’s are monopolized by them. This prevents other processes from running as there are no process ID’s available.  The child process completes its execution by using exit() system call.  So when the child finishes it's execution ‘SIGCHLD’ signal is delivered to the parent process by the kernel. Parents should,ideally, read the child's status from the process table and then delete the child's entry.  But here the parent does not wait for the child to terminate, rather it does its own subsequent job, i.e. here sleeping for 60 seconds.  So the child's exit status is never read by the parent and the child's entry continues to remain there in the process table even when the child has died. Note: Kernel sends a SIGCHLD signal to the parent process to indicate that the child process has ended · // A C program to demonstrate Zombie Process. #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)
  • 18. sleep(60); // Child process else exit(0); return 0; } Why are lots of zombie processes harmful to the system ? A lot of zombie processes in os are harmful as  The OS has one process table of finite size , so lots of zombie processes will results in a full process table.  A full process table means that OS cannot create a new process when required and Zombie processes in os are of no use as the process has died but it's entry is occupying the space in memory An extreme case - Fork bomb The program below creates an infinitely many zombie processes because the parent does not wait for it's child process. #include <unistd.h> int main() { while(1) fork(); return 0; }  PIDs in os are finite, when all the PIDs have been consumed by Zombie Process, no new process can be created.  Solution: Reboot the system Zombie Process Program #include<stdio.h> #include<stdlib.h> #include<unistd.h> int main (int argc, char * argv[]) { unsigned int pid; int ret,i,j; pid = getpid(); printf("My process id is : %un", pid ); printf("About to create child processs ....n"); //sleep(10); ret =fork(); if ( ret < 0)
  • 19. { perror("fork"); } if ( ret == 0 ) /* child process*/ { printf("I am child process. mypid = %dn", getpid() ); printf(" I am child fork returned me : %dn", ret ); for(i=0;i<5;i++){ sleep(1); printf("Child: i=%dn",i); } exit(EXIT_SUCCESS); } else if ( ret > 0 ) /* parent process */ { printf(" I am parent process my pid = %dn", getpid() );
  • 20. printf(" I am parent and fork returned me : %dn", ret ); for(j=0;j<10;j++){ sleep(1); printf("Parent: j=%dn",j); } exit(EXIT_SUCCES); } printf("Commoncode"); exit(EXIT_SUCCESS); } Output:
  • 21. Zombie Avoidance Program #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/wait.h> int main (int argc, char * argv[]){unsigned int pid ; int ret,i,j; pid = getpid(); printf("My process id is : %un", pid ); printf("About to create child processs ....n"); ret =fork(); if ( ret < 0) { perror("fork"); } if ( ret == 0 ) /* child process*/{ printf("I am child process. mypid = %dn", getpid() ); printf(" I am child fork returned me : %dn", ret ); for(i=0;i<10;i++){ printf("Child: i=%dn",i); } exit(EXIT_SUCCES); } else if ( ret > 0 ) /* parent process */ {int status; printf(" I am parent process my pid = %dn", getpid() ); printf(" I am parent and fork returned me : %dn", ret );wait(&status); if(WIFEXITED(status)){ printf("Child pid=%d terminated",ret);
  • 22. printf("Child's exit status is %dn",WEXITSTATUS(status)); } for(j=0;j<20;j++){ printf("Parent: j=%dn",j); } exit(EXIT_SUCCESS ); } printf("Common code"); exit(EXIT_SUCCESS); } Output:
  • 23. Orphan Processes Orphan processes are those processes that are still running even though their parent process has terminated or finished. A process can be orphaned intentionally or unintentionally. A process whose parent process no more exists i.e. either finished or terminated without waiting for its child process to terminate is called an orphan process. An intentionally orphaned process runs in the background without any manual support. This is usually done to start an indefinitely running service or to complete a long-running job without user attention. An unintentionally orphaned process is created when its parent process crashes or terminates. Unintentional orphan processes can be avoided using the process group mechanism.  In the real world orphans are adopted by guardians who look after them.  Similarly,the orphan process in linux is adopted by a new process , which is mostly init process (pid=1) . This is called re-parenting.  Reparenting is done by the kernel,when the kernel detects an orphan process in os, and assigns a new parent process.  New parent process asks the kernel for cleaning of the PCB of the orphan process and the new parent waits till the child completes its execution. Orphan Process Code Example In the example,the parent process sleeps for 20 seconds while the child process sleeps for 30 seconds. 1. So, after sleeping for 20 seconds the parent completes its execution while the child process is still there at least till 30 seconds. 2. When the child process becomes an orphan process, the kernel reassigns the parent process to the child process. 3. As a result, the parent process id of the child process before and after sleep () will be different. Note: Kernel is central component of an operating system that manages operations of computer and hardware. // C program to demonstrate Orphan process #include<stdio.h> #include <sys/types.h> #include <unistd.h> int main() { int pid; pid = fork(); if(pid == 0) { printf("I am the child, my process ID is %dn",getpid()); printf("My parent's process ID is %dn",getppid()); sleep(30);
  • 24. printf("nAfter sleepnI am the child, my process ID is %dn",getpid()); printf("My parent's process ID is %dn",getppid()); exit(0); } else { sleep(20); printf("I am the parent, my process ID is %dn",getpid()); printf("The parent's parent, process ID is %dn",getppid()); printf("Parent terminatesn"); } return 0; } Output My parent's process ID is 32005 I am the parent, my process ID is 32005 The parent's parent, process ID is 31998 Parent terminates After sleep I am the child, my process ID is 32006 My parent's process ID is 1 Why are too many Orphan processes harmful to the system?  Orphan processes in OS hold resources when present the system.  Orphan processes in a large number can overload the init process and hang-up a system. Conclusion  A zombie process in OS is one that has completed its execution but its entry in the process table.  wait () system call is used to deal with zombie processes.  An orphan process in OS is one which is executing but its parent process has terminated is called an orphan process.  Kernel allocates a new process as parent process to orphan process. Mostly the new parent is the init process (pid=1).  Too many zombie processes and orphan processes are harmful.