SlideShare a Scribd company logo
1 of 115
Advanced Operating Systems
Unit 3 : Process Environment, Process
Control and Process Relationships
Vijaya Kumbhar
- Asstt. Professor ,
- Indira College of Commerce and Science,Pune
Contents
•Process states and transitions, the context of a
process, saving the context of a process, sleep,
process creation, signals, process termination,
awaiting process termination, invoking other
programs, the user id of a process
•Process termination, environment list, memory
layout of a C program, shared libraries, memory
allocation, environment variables, setjmp and
longjmp, getrlimit
and setrlimit, process identifiers, fork, vfork, exit, wait
and waitpid, waitid, wait3 and wait4, race conditions,
exec
•changing user IDs and group IDs, interpreter files,
Contents
•process times, Terminal logins, network logins,
process groups, sessions, controlling terminal,
tcgetpgrp,
tcsetpgrp, and tcgetsid functions, job control, shell
exe
cution of programs, orphaned process groups
•The Process ID, Running a New Process,
Terminating a Process, Waiting for Terminated Child
Processes, Users and Groups, Sessions and
Process Groups, Daemons, Process Scheduling,
Yielding the Processor, Process Priorities, Processor
Affinity
Process
 Program in execution
 Task
 Group of instructions
 It is created using fork() and exec().
 When you execute a program on your
Unix system, the system creates a
special environment for that program. ...
A process, in simple terms, is an
instance of a running program. The
operating system tracks processes
through a five-digit ID number known as
the pid or the process ID.
Parent Process
 Process which creates another process
 Process which is created by another process
Child Process
Orphan Process
 An orphan process is a computer process whose parent
process has finished or terminated, though it remains running
itself. In a Unix-like operating system any orphaned process
will be immediately adopted by the special init system
process.
Zombie Process
On Unix and Unix-like computer operating systems, a
zombie process or defunct process is a process that has
completed execution (via the exit system call) but still has an
entry in the process table: it is a process in the "Terminated
state".
Parent-Child Relationship
 The PPID is the PID of the process's parent. For example, if
process1 with a PID of 101 starts a process named process2,
then process2 will be given a unique PID, such as 3240, but it
will be given the PPID of 101. It's a parent-child relationship.
A daemon is a type of program on Unix-like operating systems
that runs unobtrusively in the background, rather than under the
direct control of a user, waiting to be activated by the occurrence
of a specific event or condition. ... Daemons are usually
instantiated as processes.
Daemon Process
Foreground Process
 A foreground process is any command or task you run directly and wait for it to
complete. Some foreground processes show some type of user interface that
supports ongoing user interaction, whereas others execute a task and "freeze" the
computer while it completes that task.
 e.g. $ ls
Background Process
Unlike with a foreground process, the shell does not have to wait for a background
process to end before it can run more processes.
e.g. $ ls &
Process states and transitions
Process states
 Created: The process is just created/born.
 Ready to Run(Memory): The process is in queue and can start
running if scheduled.
 Ready to Run(Swapped):The process is in queue and
swapped due to memory shortage.
 User Running : The process is executing CPU instructions.
 Kernel Running: The process is executing a system call or
interrupt.
 Preempted : The process has paused due to preemption of
higher priority process or interrupt or more eligible process.
 Asleep in Memory : The process is requiring some resource
which is not available currently, hence waiting for the resource.
 Sleep – Swapped: : The process is requiring some resource
which is not available currently and it is swapped due memory
shortage.
 Zombie : The process is dead but have not been removed from
the process table.
Unix Process Management
♦ Operating system functions executes within
user process.
♦ 2 modes of execution
– User mode and Kernel mode
♦ 2 types of processes are available
– System processes(Execute OS code)
– User processes( Execute user program code).
♦ System call is used to transfer from user
mode to system mode.
-Process 0 is a special process that is created when the
system boots. Process 1 (init process) is the child of
Process 0. All the other processes in UNIX has Process
1 as ancestor. All new processes are created under
Process 1 (init process).
Memory layout of a process
 A process can broadly be defined into following segments :
Stack
Stack contains all the data that is local to a function like
variables, pointers etc. Each function has its own stack. Stack
memory is dynamic in the sense that it grows with each
function being called.
Heap
Heap segment contains memory that is dynamically
requested by the programs for their variables.
Data
All the global and static members become part of this
segment.
Text
All the program instructions, hard-coded strings, constant
values are a part of this memory area.
Process Description/Context of
process
 Definition: “snapshot”, i.e. complete information about
a process at some point during its execution
♦ Elements of process image -- divided into 3 parts
– User level context
• Process text, Process data, User stack and Shared
memory.
– Register context
• Program counter, Process status registers, stack
pointer,
general purpose registers…
– System level context
• Process table entry, User area, Per process region
table, Kernel stack
– When a process is not running the processor status
information is stored in register context area
Unix Process Table Entry♦ Process Id
♦ Process state
♦ Pointers – to user area & process memory area (text, data, stack)
♦ Process size – enables OS to know how much space to allocate
♦ User identifier
– Real user ID -ID of user who is responsible for the process
– Effective user ID - ID used by process to gain temporary privilege,
while the program is being executed as a part of process.
– Process identifiers - ID of the process
♦ Event descriptor - valid when a process is in sleep state. When the
event occurs, the process is transferred to a ready to run state.
♦ Priority -used for scheduling
♦ Signal -enumerates signals send to process but not yet handled.
♦ Timers-Process execution time, kernel resource utilization, and user
set timer used to send alarm signal to a process.
♦ P_link - pointer to the next link in the ready queue.
♦ Memory status - indicates the process image is in main memory or
UNIX User Area(u-area)
♦ Process table pointer - Indicates entry corresponding to the user
area.
♦ User identifiers - Real & Effective user Ids, used to determine user
privileges.
♦ Timers - Record time that the process spent executing in user mode &
kernel mode.
♦ Signal handling array - For each type of signal defined in the system,
indicate how the process will react to receipt of that signal.
♦ Control terminal - Indicate login terminal for this process, if exist.
♦ Error field - Record errors encountered during system call.
♦ Return value - Contain result of s/m call
♦ I/O parameters - Describes amount of data transfer, the address of the
source data array in user space, file offset for I/O.
♦ File parameters - Current directory & current root describe the file
system environment of the process.
♦ User file descriptor table - Record the file the process has open
♦ Limit fields - Restrict the size of the process & size of the file it can
write.
System level context
♦ Two parts
– 1. Static (Process table entry, User area, Per process
region table).
– 2. Dynamic (Kernel stack)
– Process table entry contains process control information
that is accessible to the kernel to the kernel at all time. So
in VM systems all process table entries are maintained in
main memory.
– User area contains additional process control
information that is needed by the kernel when it executes
in context of a process. It is also used when swapping
process to and from the memory.
– Process reg. table is used by memory management
s/m
– Kernel stack – used when the process is executing in
kernel mode and contain information that must be saved
Types of processes in UNIX
 ♦ Mainly 3 types
– User process
– Daemon process
– Kernel process
– Daemon process
• Performs the function in a system wide basis.
The function can be of any auxiliary kind, but
they are vital in controlling the computational
environment of the system.
• Example Print spooling, Network Management.
• Once created Daemon process can exist
throughout the life time of the Operating System
Process Tree in a UNIX system
Process Creation
 Unix fork() creates a process
◦ Creates a new address space
◦ Copies text, data, & stack into new adress
space
◦ Provides child with access to open files
 Unix exec() allows a child to run a new
program
 Unix wait() allows a parent to wait for
a child to terminate
Process Creation
 Syntax: pid = fork();
pid – PID of child process (parent)
0 (child)
 Algorithm:
1. Check for available memory.
2. Check that user is not running too many processes.
3. Allocate new proc structure, assign new PID.
(PIDS start from 1 and increase by 1 until wraparound at
maximum value)
4. Copy data from parent proc structure to child.
real/effective UID, scheduling parameters, signal masks
parent process field of child is set, pointers to parent and
sibling procs
child state is set to BEING CREATED
5. Clear accounting information, timers, pending signals.
6. Connect new proc on relevant linked lists.
7. Increment reference count of inode of current directory.
Increment global file table reference count associated with
each open file of parent process.
(child inherits access rights to open files child shares global
file table entries with parent ) changes in file offset caused by
read/write in the parent are visible to child and vice versa)
8. Allocate memory and create copy of parent context (u area,
regions, page tables)
(shared regions are not copied, only ref. count is incremented)
9. Copy parent’s kernel-level context (registers + kernel
stack).
10. Parent: return PID to user Child: “saved” context is
restored, returns 0 to user
Operating
Example
int pidValue;
pidValue = fork();
/* Creates a child process */
if(pidValue == 0)
{
/*pidValue is 0 for child, nonzero for parent */
/* The child executes this code concurrently with parent */
childsPlay(...);
/* A procedure linked into a.out */
exit(0);
}
/* The parent executes this code concurrently with child
*/ parentsWork(...);
wait(...);
Termination of a process in UNIX
Syntax: exit(status);
 status – value returned to parent proc.
 may be called explicitly/implicitly (startup routine
linked with all
 C programs calls exit when program returns from
main)
 kernel may also invoke exit() when an uncaught
signal is
 received
Algorithm:
 1. Disable signal handling.
 2. Close all open files, release inode for current
directory.
 3. Release all user memory.
6. Change process state to ZOMBIE and put proc on
zombie process
list.
7. Assign parent PID of all live child processes to 1
(init);
if any child process is ZOMBIE, current process
sends init a
SIGCHLD, init deletes proc structure for the process.
8. Send SIGCHLD to parent process.
9. Jump to context switch code.
 Syntax: execve(filename, argv, envp);
 filename – name of executable file
 argv – parameters to program (char **)
 envp – environment of program (char **)
 Algorithm:
 1. Convert path name into inode for executable file.
 2. Check that file is an executable with proper
permissions for the user.
 3. Read file header to determine layout of the
executable file.
(i) primary header – magic number (specifies type of
exec. file), no. of sections, start address for process
execution
(ii) section headers – section type, size, virtual address
Invoking a program
(iii) sections – code, data (initial contents of process
address space)
(iv) misc. sections – symbol tables, debugging info,
etc.
4. Copy parameters from old address space to kernel
space. (old address space will be freed ) params
have to be saved on:
kernel stack + additional storage (if needed))
5. Free memory occupied by the process.
6. Allocate memory for the new process’ code, data,
stack.
7. Load contents of executable file into memory
(code, initialized data).
8. Copy parameters to new user stack.
9. Clear addresses of user signal handlers from u
area.
Wait statement in UNIX
– Pi can wait for the termination of a child
– Wait(address(xyz)); // xyz - variable within the
address space of Pi.
– If process Pi has child processes & at least one of
them
has already terminated, the wait call stores the
termination status of the terminated child process into
xyz and immediately return with the id of the
terminated child process. If more child processes exists
their termination status would be made available to Pi
only when it repeats the wait call.
– Process Pi is blocked if it has children but none of
them
has terminated, it will be unblocked when one of the
child process terminates. The wait call returns a –1 if Pi
has no children
Example for wait
int main()
{
int i,saved_status;
for(i=0;i<3;i++)
{
if (fork()==0)
{
// Child Process
exit();
}
}
while(wait(&saved_status)!= -1); // Loop till all children
terminates
}
Context switch
 A context switch (also sometimes referred
to as a process switch or a task switch) is
the switching of the CPU (central
processing unit) from one process or thread
to another. A process (also sometimes
referred to as a task) is an executing (i.e.,
running) instance of a program.
 Context switching is overhead because it
is cycles (time) that the processor is being
used but no user code is executing, so no
directly productive computing is getting
done. Context switching hurts
performance: The cycles to actually perform
Reasons of context switch
When a process
1. puts itself to sleep (via sleep ())
2. exits
(conclusion of exit system call invokes context switch
code)
3. returns from kernel mode to user mode but is not the
most eligible process to run.
4. TRO(Time Run Out)
 Kernel ensures consistency before switching context
(completes necessary updates, does appropriate
locking/unlocking operation)
e.g. when a process goes to sleep waiting for I/O,
kernel locks allocated buffer so that no other process
can access/corrupt it
 link system call: releases lock of 1st inode before
 Principle:
1. Save the process context at some point.
2. Proceed to execute scheduling algorithm and
context switch code in the context of the old process.
3. When context is restored later, execution should
resume according to previously saved context.
Problem: distinguishing between 2 and 3
save_context(current);
/* scheduling algorithm */
resume_context(new);
Saving the context of process
1. Save current PC and other registers.
2. Set return value register of save_context to 0 in the
saved
register context.
3. Kernel continues to execute in the context of Pold to
select Pnew.
4. resume_context automatically switches to Pnew.
5. When Pold is scheduled, PC is set to old value (saved
in step 1).
6. Kernel resumes execution of Pold at the end of
save_context.
7. On return, execution jumps over resume_context
code.
ALT: PC may be set artificially to point to instruction
where
Interrupt handling in UNIX
♦ Will execute only one interrupt at a time ( to
avoid race condition).
♦ Each interrupt is assigned an interrupt
priority level. An interrupt priority level is
also assigned to CPU.
♦ When an interrupt at priority level ‘l’ arises,
it is handled only if l> CPU’s interrupt
priority else kept pending till CPU’s
interrupt priority level assumes a lower
value.
System calls in UNIX
– System calls accepts parameters relevant to its
functioning
– When a call occurs these parameters exists on the
user
stack of the process which issues the system call.
– The call number is expected to be in register 0
– System call handler obtain this number to determine
which system functionality being invoked.
– From its internal table it knows the address of the
handler for that function.
– Parameters of the system call exists on the user stack
of
the process making the call.
– Before passing control to the handler for a specific
call
these parameters are copied from the user stack into
some standard places in the user area.
System calls in UNIX Cont…
– A signal can be send to a process/Group of
processes using kill(<pid>,<signum>) system
call. Where pid is the id of the process signal
to
be sent.(sender must know receiver address
&
receiver must be in the same process tree).
– Pid value 0 Æ signal to be sent to all
processes
in the same group as the sender process.
– Pid value –1 Æ to reach processes outside
the
process tree of the sender.
Signals
 Signals are a limited form of inter-
process communication (IPC), typically
used in Unix, Unix-like, and other
POSIX-compliant operating systems.
 A signal is an asynchronous notification
sent to a process or to a specific thread
within the same process in order to notify
it of an event that occurred.
Signal handling in UNIX
♦ Oldfunction = signal(<signum>,<function>)
– Where signal is a function in C library which makes a signal
system call. Signum is an integer & function is the function name.
– The function should be executed on occurrence of signal
<signum>.
– User can specify 0 or 1 instead of function.
Where 0 indicates the default action defined in the Kernel is to be
executed & 1is occurrence
of signal is to be ignored.
Whenever a signal is send to a process, the bit corresponding to the
signal is set to 1 in the proc structure of the destination process.
The kernel now determines if the signal is being ignored by the
destination process. If not it will makes provision to deliver the
signal to the process. If the signal is ignored it remains pending and
is delivered when the process is ready to accept it. In UNIX signal
remains pending if the process to which it is intended is in block
state.
The signal would be delivered when the process comes out of the
blocked state. Signals are delivered when a process returns from a
Interesting signals in UNIX
♦ SIGCHLD Child process died or
suspended
♦ SIGFPE Arithmetic fault
♦ SIGILL Illegal instruction
♦ SIGINT tty interrupt (Control C)
♦ SIGKILL Kill process
♦ SIGSEGV Segmentation fault
♦ SIGSYS Invalid System call
♦ SIGXCPU Exceeds CPU limit
♦ SIGXFSZ Exceeds file size limit
Execlp demo
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
pid_t pid;
if ((pid = fork()) == -1)
perror("fork error");
else if (pid == 0)
{
execlp("newShell", "newShell", NULL);
printf("Return not expected. Must be an execlp error.n");
}
}
Environment variables in
UNIX
 An environment variable is a
dynamic-named value that can affect
the way running processes will behave
on a computer.
 The commands env, set, and
printenv display all environment
variables and their values.
 printenv can also be used to print a
single variable by giving that variable
name as the sole argument to the
command.
Environment variables in
UNIX
 PATH : a list of directory paths. ...
 HOME (Unix-like) and USERPROFILE
(Microsoft Windows): indicate where a
user's home directory is located in the
file system.
 HOME/{.AppName} (Unix-like) and
APPDATA{DeveloperNameAppName
} (Microsoft Windows): for storing
application settings.
 TERM (Unix-like): specifies the type of
computer terminal or terminal
emulator being used (e.g., vt100 or
dumb).
 PS1 (Unix-like): specifies how the
prompt is displayed in the Bourne
shell and variants.
 MAIL (Unix-like): used to indicate
where a user's mail is to be found.
 TEMP: location where processes can
store temporary files.
Setjmp and longjmp
 “Setjump” and “Longjump” are defined
in setjmp.h, a header file in C standard
library.
 setjump(jmp_buf buf) : uses buf to
remember current position and returns
0.
 longjump(jmp_buf buf, i) : Go back
to place buf is pointing to and return i .
// A simple C program to demonstrate working of setjmp() and
longjmp()
#include<stdio.h>
#include<setjmp.h>
jmp_buf buf;
void func()
{ printf("Welcome n");
// Jump to the point setup by setjmp
longjmp(buf, 1);
printf(“Val2n");
}
int main()
{ // Setup jump position using buf and return 0
if (setjmp(buf))
printf(“Val3n");
else { printf(“Val4n");
func();
} return 0;
Output :
Val4
Welcome
Val3
----------------------------------------------------
 This is mainly used to implement
exception handling in C.
 setjmp can be used like try (in
languages like C++ and Java).
 The call to longjmp can be used like
throw (Note that longjmp() transfers
control to the point set by setjmp()).
getrlimit and setrlimit
 It allows a process to read and set limits on the system
resources that it can consume.
 Some of the most useful resource limits that may be
changed are listed here, with their codes:
 RLIMIT_CPU—The maximum CPU time, in seconds,
used by a program. This is the amount of time that the
program is actually executing on the CPU, which is not
necessarily the same as wall-clock time. If the program
exceeds this time limit, it is terminated with a SIGXCPU
signal.
 RLIMIT_DATA—The maximum amount of memory that a
program can allocate for its data. Additional allocation
getrlimit and setrlimit
 RLIMIT_NPROC—The maximum number of child
processes that can be running for this user. If the process
calls fork and too many processes belonging to this user
are running on the system, fork fails.
 RLIMIT_NOFILE—The maximum number of file descriptors
that the process may have open at one time.
Example
(limit-cpu.c) CPU Time Limit Demonstration
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
int main ()
{ struct rlimit rl;
/* Obtain the current limits. */
getrlimit (RLIMIT_CPU, &rl);
/* Set a CPU limit of 1 second. */
rl.rlim_cur = 1;
setrlimit (RLIMIT_CPU, &rl);
/* Do busy work. */
while (1);
return 0;
Output:
When the program is terminated by
SIGXCPU, the shell helpfully prints out
a message interpreting the signal:
$./limit_cpu
CPU time limit exceeded
process identifiers
In computing, the process identifier
(normally referred to as the process ID
or PID) is a number used by most
operating system kernels—such as
those of UNIX, macOS and Microsoft
Windows—to uniquely identify an active
process.
Process Identifiers in UNIX
 PID – Process Identification Number
 GID- Process Group Number
 PPID - Parent Process Identification Number
 RUID- Real User Identification Number
 EUID- Effective User Identification
Number
 RGID- Real Group Identification Number
 EGID- Effective Group Identification
Number
 #include <sys/types.h>
 #include <unistd.h>
 pid_t getpid(void);
 pid_t getppid(void);
 uid_t getuid(void);
 uid_t geteuid(void);
 int seteuid(pid_t pid,uid_t);
 gid_t getgid(void);
 int setpgid(pid_t pid, pid_t pgid);
 gid_t getegid(void);
Fork()
 Used to create new process.
 The code of child process is identical to the code of its parent
process.
 After the creation of child process, both process i.e. parent and
child process start their execution from the next statement after
fork() and both the processes get executed simultaneously.
 The parent process and child process do have separate address
space. Hence, when any of the processes modifies any
statement or variable in the code. It would not be reflected in
other process codes. Let’s suppose if child process modifies the
code it would not affect the parent process.
 Some child process after their creation immediately calls exec().
The exec() system call replaces the process with the program
specified in its parameter. Then the separate address space of
child process is of no use. The one alternative here is copy-on-
write.
 The copy-on-write let the parent and child process to share
same address space. If the any of the processes writes on the
Vfork()
 The modified version of fork() is vfork().
 The vfork() system call is also used to create a new
process.
 The child process code is also identical to the parent
process code. Here, the child process suspends the
execution of parent process till it completes its execution
as both the process share the same address space to use.
 As the child and parent process shares the same address
space. If any of the processes modifies the code, it is
visible to the other process sharing the same pages. Let us
suppose if the parent process alters the code; it will reflect
in the code of child process.
 As using vfork() does not create separate address spaces
for child and parent processes. Hence, it must be
implemented where the child process calls exec()
immediately after its creation. So, there will be no wastage
of address space, and it is the efficient way to create a
Fork() vfork()
Functions On Real Kernels Vicariously Functions On Real
Kernels
allows the execution of parent
and child process
simultaneously
suspends the execution of parent
process until child process
completes its execution
child process created using
fork has separate address
space as that of the parent
process
child process created using vfork
has to share the address space of
its parent process.
If the child process alters any
page in the address space, it
is invisible to the parent
process as the address space
are separate.
If child process alters any page in
the address space, it is visible to
the parent process as they share
the same address space.
COW(Copy on Write)bit is ON COW(Copy on Write) bit is OFF
Conclusion of fork and vfork()
 The vfork() system call has to be
implemented when child process call
exec() immediately after its creation
using fork(). As separate address
space for child and parent process will
be of no use here.
exit(), _exit() and _Exit()
 a computer process terminates its execution by
making an exit system call.
 When the child process terminates ("dies"),
either normally by calling exit, or abnormally due
to a fatal error or signal (e.g., SIGTERM,
SIGINT, SIGKILL), an exit status is returned to
the operating system and a SIGCHLD signal is
sent to the parent process.
 The exit status can then be retrieved by the
parent process via the wait system call.
 Most operating systems allow the terminating
process to provide a specific exit status to the
system, which is made available to the parent
process. Typically this is an integer value,
wait
A call to wait() blocks the calling process
until one of its child processes exits or a
signal is received. After child process
terminates, parent continues its execution
after wait system call instruction.
Child process may terminate due to any of
these:
 It calls exit();
 It returns (an int) from main
 It receives a signal (from the OS or
another process) whose default action is
to terminate.
 If any process has more than one
child processes, then after calling
wait(), parent process has to be in wait
state if no child terminates.
 If only one child process is terminated,
then return a wait() returns process ID
of the terminated child process.
waitid
 The waitid() system call (available
since Linux 2.6.9) provides more
precise control over which child state
changes to wait for.
 Syntax:
int waitid(idtype_t idtype, id_t id,
siginfo_t *infop, int options);
 int waitid(idtype_t idtype, id_t id,
siginfo_t *infop, int options);
 The idtype and id arguments select
the child(ren) to wait for, as follows:
 idtype == P_PID Wait for the child
whose process ID matches id. idtype
== P_PGID Wait for any child whose
process group ID matches id. idtype
== P_ALL Wait for any child; id is
ignored.
waitpid
 waitpid(-1, &status, 0);
 The waitpid() system call suspends execution of the
calling process until a child specified by pid argument
has changed state. By default, waitpid() waits only for
terminated children, but this behavior is modifiable
via the options argument, as described below.
The value of pid can be:
 < -1 meaning wait for any child process
whose process group ID is equal to the absolute value
of pid.
 -1 meaning wait for any child process.
 0 meaning wait for any child process
whose process group ID is equal to that of the calling
process.
 > 0 meaning wait for the child whose
process ID is equal to the value of pid.
Wait3 and wait4
 pid_t wait3(int *status, int options, struct
rusage *rusage);
 pid_t wait4(pid_t pid, int *status, int options,
struct rusage *rusage);
Wait for process to change state.
The wait3() and wait4() system calls are
similar to waitpid(2), but additionally return
resource usage information about the child in
the structure pointed to by rusage.
Other than the use of the rusage argument, the following
wait3() call:
wait3(status, options, rusage);
is equivalent to:
waitpid(-1, status, options);
Similarly, the following wait4() call:
wait4(pid, status, options, rusage);
is equivalent to:
waitpid(pid, status, options);
In other words, wait3() waits of any child, while wait4()
can be used to select a specific child, or children, on
atexit()
 It causes the specified function func
to be called when the program
terminates.
 The termination function can be
registered anywhere in the program,
but it will be called at the time of the
program termination.
 Syntax:
int atexit(void (*func)(void))
Example
#include <stdio.h>
#include <stdlib.h>
void functionA ()
{
printf("This is functionAn");
}
int main ()
{
atexit(functionA );
printf("Starting main program...n"); printf("Exiting
main program...n");
return(0);
}
Output
Starting main program...
Exiting main program...
This is functionA
Race conditions
 A race condition is an undesirable
situation that occurs when a device
or system attempts to perform two or
more operations at the same time, but
because of the nature of the device or
system, the operations must be done
in the proper sequence to be done
correctly.
Race Condition Example
static void charatatime(char *);
int main(void)
{ pid_t pid;
if( (pid = fork()) < 0)
{ perror("Fork error");
exit(1); }
else if( pid == 0)
{ charatatime("Output from childn"); }
else { charatatime("Output from parentn"); }
exit(0);
}
static void charatatime(char * str)
{ char * ptr; int c;
setbuf(stdout,NULL);
for(ptr = str; c = *ptr++; )
putc(c, stdout); }
Exec family of functions
 The exec family of functions replaces the current
running process with a new process.
 It can be used to run a any program by using C
program.
 It comes under the header file unistd.h.
 execl
 execlp
 execle
 execlpe
 execv
 execvp
 execve
 execvpe
 int execl( path, arg0, arg1..., argn, NULL );
 int execle( path, arg0, arg1..., argn, NULL,
envp );
 int execlp( file, arg0, arg1..., argn, NULL );
 int execlpe( file, arg0, arg1..., argn, NULL,
envp );
 int execv( path, argv );
 int execve( path, argv, envp );
 int execvp( file, argv );
 int execvpe( file, argv, envp );
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------
const char *path;
const char *file;
const char *arg0,..., *argn;
 The exec functions load and execute a
new child process, named by path or
file. If the child process is successfully
loaded, it replaces the current process
in memory. No return is made to the
original program.
gcc EXEC.c -o EXEC
 //EXEC.c

 #include<stdio.h>
 #include<unistd.h>

 int main()
 {
 int i;

 printf("I am EXEC.c called by execvp() ");
 printf("n");

 return 0;
 }
 //execDemo.c

 #include<stdio.h>
 #include<stdlib.h>
 #include<unistd.h>
 int main()
 {
 //A null terminated array of character
 //pointers
 char *args[]={"./EXEC",NULL};
 execvp(args[0],args);

 /*All statements are ignored after execvp() call as this whole
 process(execDemo.c) is replaced by another process (EXEC.c)
 */
 printf("Ending-----");

 return 0;
 }
 gcc execDemo.c -o execDemo
 Output:
I AM EXEC.c called by execvp()
changing user IDs and group
IDs
 #include <unistd.h>
 int setuid(uid_t uid);
 int setgid(gid_t gid);
interpreter files
 Unix Shell Scripts. On Unix systems, a
Shell-Script is a file (with execute
permissions) whose first two
characters are `#!‘.
 Shell scripts are short programs that
are written in a shell programming
language and interpreted by a shell
process. They are extremely useful for
automating tasks on Linux and other
Unix-like operating systems
#!/bin/sh
# This is a comment!
echo Hello World
echo Hello
echo World
-----------------------------------------------------
-
$./first.sh
system function
 system() is used to invoke an
operating system command from a
C/C++ program.
int system(const char *command);
int main()
{
system(“ls”);
system(“clear”);
system(“gcc a.c”);
system(“./a.out”);
system(“cd..”);
}
process accounting
acct: process accounting file
#include <sys/acct.h>
 If the kernel is built with the process accounting
option enabled, then calling acct(2) starts
process accounting, for example:
 acct("/var/log/pacct");
 When process accounting is enabled, the kernel
writes a record to the accounting file as each
process on the system terminates. This record
contains information about the terminated
process, and is defined in <sys/acct.h> as
follows:
struct acct
{ char ac_flag; /* Accounting flags */
u_int16_t ac_uid; /* Accounting user ID */
u_int16_t ac_gid; /* Accounting group ID */
u_int16_t ac_tty; /* Controlling terminal */
u_int32_t ac_btime; /* Process creation time (seconds since the Epoch) */
comp_t ac_utime; /* User CPU time */
comp_t ac_stime; /* System CPU time */
comp_t ac_etime; /* Elapsed time */
comp_t ac_mem; /* Average memory usage (kB) */
comp_t ac_io; /* Characters transferred (unused) */
comp_t ac_rw; /* Blocks read or written (unused) */
comp_t ac_minflt; /* Minor page faults */
comp_t ac_majflt; /* Major page faults */
comp_t ac_swaps; /* Number of swaps (unused) */
u_int32_t ac_exitcode; /* Process termination status (see wait(2)) */
char ac_comm[ACCT_COMM+1]; /* Command name (basename of last
executed command; null-terminated) */
char ac_pad[X]; /* padding bytes */ };
Effective user ID/Group ID
 The effective UID (euid) of a process
is used for most access checks.
 It is also used as the owner for files
created by that process.
 The effective GID (egid) of a process
also affects access control.
File system user ID
 Linux also has a file system user ID
(fsuid) which is used explicitly for
access control to the file system.
 It matches the euid unless explicitly
set otherwise.
 It may be root's user ID only if ruid,
suid, or euid is root.
user identification
 getuid, geteuid - get user identity
#include <unistd.h>
#include <sys/types.h> uid_t
getuid(void);
uid_t geteuid(void);
getuid() returns the real user ID of the
current process.
geteuid() returns the effective user ID of
the current process.
Saved user ID
 The saved user ID (suid) is used when a
program running with elevated privileges
needs to do some unprivileged work
temporarily; changing euid from a privileged
value (typically 0) to some unprivileged value
(anything other than the privileged value)
causes the privileged value to be stored in
suid.[3]
 Later, a program's euid can be set back to the
value stored in suid, so that elevated
privileges can be restored; an unprivileged
process may set its euid to one of only three
values: the value of ruid, the value of suid, or
the value of euid.
Real user ID/Group ID
 The real UID (ruid) and real GID (rgid)
identify the real owner of the process
and affect the permissions for sending
signals.
 A process without superuser privileges
may signal another process only if the
sender's ruid or euid matches
receiver's ruid or suid.
 Because a child process inherits its
credentials from its parent, a child and
parent may signal each other.
changing user IDs and group
IDs,
 setuid() sets the effective user ID of
the calling process.
 seteuid - sets effective user.
 setegid - sets effective group ID.
process times
 times - get process times
#include <sys/times.h>
clock_t times(struct tms *buf);
 times() stores the current process times in the
struct tms that buf points to.
The struct tms is as defined in <sys/times.h>
struct tms
{
clock_t tms_utime; /* user time */
clock_t tms_stime; /* system time */
clock_t tms_cutime; /* user time of children */ clock_t
tms_cstime; /* system time of children */
};
Terminal logins
network logins
 The connection between the terminal and the computer
isn't point-to-point. In this case, login is simply a service
available, just like any other network service, such as
FTP or SMTP.
 With the terminal logins, init knows which terminal
devices are enabled for logins and spawns a getty
process for each device.
 In the case of network logins, all the logins come
through the kernel's network interface drivers (e.g., the
Ethernet driver), and we don't know ahead of time how
many of these will occur.
 To allow the same software to process logins over both
terminal logins and network logins, a software driver
called a pseudo terminal is used to emulate the
behavior of a serial terminal and map terminal
operations to network operations, and vice versa.
Sequence of processes
involved in executing TELNET
server
process groups
 a process group denotes a collection of
one or more processes.
 Among other things, a process group is
used to control the distribution of a signal;
 when a signal is directed to a process
group, the signal is delivered to each
process that is a member of the group.
 When a process replaces its image with a
new image (by calling one of the exec
functions), the new image is subjected to
the same process group (and thus
session) membership as the old image.
Sessions
 A session denotes a collection of
one or more process groups.
 A process group is not permitted to
migrate from one session to
another, and a process may not
create a process group that belongs
to another session.
 A process is not permitted to join a
process group that is a member of
another session—that is, a process
is not permitted to migrate from one
controlling terminal
Sessions and process groups have a few
other characteristics.
 A session can have a single controlling
terminal. This is usually the terminal device
(in the case of a terminal login) or pseudo-
terminal device (in the case of a network
login) on which we log in.
 The session leader that establishes the
connection to the controlling terminal is
called the controlling process.
 The process groups within a session can be
divided into a single foreground process
group and one or more background process
 If a session has a controlling terminal, it has a
single foreground process group, and all other
process groups in the session are background
process groups.
 Whenever we type the terminal's interrupt key
(often DELETE or Control-C), this causes the
interrupt signal be sent to all processes in the
foreground process group.
 Whenever we type the terminal's quit key (often
Control-backslash), this causes the quit signal
to be sent to all processes in the foreground
process group.
 If a modem (or network) disconnect is detected
by the terminal interface, the hang-up signal is
sent to the controlling process (the session
These characteristics are :
tcgetpgrp and tcsetpgrp
 tcgetpgrp, tcsetpgrp - get and set terminal
foreground process group.
#include <unistd.h>
pid_t tcgetpgrp(int fd);
int tcsetpgrp(int fd, pid_t pgrp);
The function tcgetpgrp() returns the process
group ID of the foreground process group on the
terminal associated to fd, which must be the
controlling terminal of the calling process.
The function tcsetpgrp() makes the process group
with process group ID pgrp the foreground process
group on the terminal associated to fd, which must
be the controlling terminal of the calling process,
and still be associated with its session.
pgrp must be a (nonempty) process group
belonging to the same session as the calling
process. If tcsetpgrp() is called by a member of a
background process group in its session, and the
calling process is not blocking or ignoring
SIGTTOU, a SIGTTOU signal is sent to all
members of this background process group.
tcgetsid functions
 tcgetsid - get the process group ID for
the session leader for the controlling
terminal.
#include <termios.h>
pid_t tcgetsid(int fildes);
The tcgetsid() function shall obtain the
process group ID of the session for which
the terminal specified by fildes is the
job control commands
Command Explanation Example
&
Run the
command in the
background
% long_cmd &
Ctrl-z
Stop the
foreground
process
[Ctrl-z] Stopped
jobs
List background
processes
% jobs [1] -
Stopped vi [2] -
big_job &
%n
Refers to the
background % fg %1
job control commands
Command Explanation Example
%?str
Refers to the
background job
containing str
% fg %?ls
bg
Restart a
stopped
background
process
% bg [2] big_job
&
fg
Bring a
background
process to the
foreground
% fg %1
job control commands
Command Explanation Example
~ Ctrl-z
Suspend an
rlogin or ssh
session
host2>~[Ctrl-z]
Stopped host1>
~~ Ctrl-z
Suspend a
second level
rlogin or ssh
session
host3>~~[Ctrl-z]
Stopped host2>
shell execution of programs,
 Let's examine how the shells execute
programs and how this relates to the
concepts of process groups, controlling
terminals, and sessions.
 To do this, we'll use the ps command .
ps -o pid,ppid,pgid,sid,comm
 the output is
PID PPID PGID SID COMMAND
949 947 949 949 sh
1774 949 949 949 ps
 ps -o pid,ppid,pgid,sid,comm &
the only value that changes is the
process ID of the command:
PID PPID PGID SID
COMMAND
949 947 949 949 sh
1812 949 949 949 ps
 ps -o pid,ppid,pgid,sid,comm | cat
the output is
PID PPID PGID SID COMMAND
949 947 949 949 sh
1823 949 949 949 cat
1824 823 949 949 ps
orphaned process groups
 A process whose parent terminates is
called an orphan and is inherited by
the init process.
 All the process which has same PPID
and parent process has been
terminated, then all such processes
have one group id called as orphaned
process group.
Process Scheduling, Yielding the
Processor
 Linux provides a family of system calls
for the management of scheduler
parameters.
 These system calls allow manipulation
of process priority, scheduling policy,
and processor affinity, as well as
provide an explicit mechanism to yield
the processor to other tasks.
System Call Description
nice() Set a process's nice
value
sched_setschedul
er()
Set a process's
scheduling policy
sched_getschedul
er()
Get a process's
scheduling policy
sched_setparam() Set a process's real-
time priority
sched_getparam() Get a process's real-
time priority
System Call Description
sched_get_priority_
max()
Get the maximum real-
time priority
sched_get_priority_
min()
Get the minimum real-
time priority
sched_rr_get_interva
l()
Get a process's
timeslice value
sched_setaffinity() Get a process's
processor affinity
sched_getaffinity() Set a process's
processor affinity
sched_yield() Temporarily yield the
processor
Process Priorities
 A realtime priority thread can never be
pre-empted by timer interrupts and
runs at a higher priority than any other
thread in the system.
 As such a CPU bound realtime priority
thread can totally ruin a machine.
 Creating realtime priority threads
requires a privilege
(SeIncreaseBasePriorityPrivilege) so it
can only be done by administrative
users.
Processor Affinity
 Processor affinity, or CPU pinning,
enables the binding and unbinding of
a process or a thread to a central
processing unit (CPU) or a range of
CPUs, so that the process or thread
will execute only on the designated
CPU or CPUs rather than any CPU.
Sample Questions from SPPU
QP
 What are the components of register
context?
 The idle process is the actually a
process that gets run.Justify.
 The timeslice to each process is an
important variable in the overall
behaviour of the system.Justify
 At the Kernel Level ,support for
protected process is two fold.
Sample Questions from SPPU
QP
 Explain four basic types of user mode
processes?
 Explain different types of memory
regions found in every process?
 The process can access its u-area
when it executes in kernel mode but
not when it executes in user mode.
Justify.
 Write a program to demonstrate
atexit() system call.

More Related Content

What's hot

Operating System 3
Operating System 3Operating System 3
Operating System 3tech2click
 
Operating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - ProcessesOperating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - ProcessesPeter Tröger
 
Process management
Process managementProcess management
Process managementBirju Tank
 
Process Control Block & Threads and Their Management
Process Control Block & Threads and Their ManagementProcess Control Block & Threads and Their Management
Process Control Block & Threads and Their ManagementUjjwal Kumar
 
CHAPTER READING TASK OPERATING SYSTEM
CHAPTER READING TASK OPERATING SYSTEMCHAPTER READING TASK OPERATING SYSTEM
CHAPTER READING TASK OPERATING SYSTEMNur Atiqah Mohd Rosli
 
Processes Control Block (Operating System)
Processes Control Block (Operating System)Processes Control Block (Operating System)
Processes Control Block (Operating System)Imdad Ullah
 
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
 
Process Management in Android
Process Management in AndroidProcess Management in Android
Process Management in AndroidShrey Verma
 
Operating system - Process and its concepts
Operating system - Process and its conceptsOperating system - Process and its concepts
Operating system - Process and its conceptsKaran Thakkar
 
Process management in linux
Process management in linuxProcess management in linux
Process management in linuxMazenetsolution
 
Os presentation process
Os presentation processOs presentation process
Os presentation processNaseer Ahmad
 
Process management in os
Process management in osProcess management in os
Process management in osSumant Diwakar
 

What's hot (20)

Unix kernal
Unix kernalUnix kernal
Unix kernal
 
Unit 4
Unit  4Unit  4
Unit 4
 
Operating System 3
Operating System 3Operating System 3
Operating System 3
 
Operating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - ProcessesOperating Systems 1 (6/12) - Processes
Operating Systems 1 (6/12) - Processes
 
Process management
Process managementProcess management
Process management
 
Process Control Block & Threads and Their Management
Process Control Block & Threads and Their ManagementProcess Control Block & Threads and Their Management
Process Control Block & Threads and Their Management
 
Process
ProcessProcess
Process
 
CHAPTER READING TASK OPERATING SYSTEM
CHAPTER READING TASK OPERATING SYSTEMCHAPTER READING TASK OPERATING SYSTEM
CHAPTER READING TASK OPERATING SYSTEM
 
Processes Control Block (Operating System)
Processes Control Block (Operating System)Processes Control Block (Operating System)
Processes Control Block (Operating System)
 
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
 
水晶礦脈
水晶礦脈水晶礦脈
水晶礦脈
 
Process Management in Android
Process Management in AndroidProcess Management in Android
Process Management in Android
 
Operating system - Process and its concepts
Operating system - Process and its conceptsOperating system - Process and its concepts
Operating system - Process and its concepts
 
Process management in linux
Process management in linuxProcess management in linux
Process management in linux
 
3 process management
3 process management3 process management
3 process management
 
Completeosnotes
CompleteosnotesCompleteosnotes
Completeosnotes
 
Os notes
Os notesOs notes
Os notes
 
Os lab final
Os lab finalOs lab final
Os lab final
 
Os presentation process
Os presentation processOs presentation process
Os presentation process
 
Process management in os
Process management in osProcess management in os
Process management in os
 

Similar to Advanced Operating Systems......Process Management

Chapter 1 Introduction to Operating System Concepts
Chapter 1 Introduction to Operating System ConceptsChapter 1 Introduction to Operating System Concepts
Chapter 1 Introduction to Operating System ConceptsMeenalJabde
 
Bedtime Stories on Operating Systems.pdf
Bedtime Stories on Operating Systems.pdfBedtime Stories on Operating Systems.pdf
Bedtime Stories on Operating Systems.pdfAyushBaiswar1
 
Week 11Linux InternalsProcesses, schedulingLecture o.docx
Week 11Linux InternalsProcesses, schedulingLecture o.docxWeek 11Linux InternalsProcesses, schedulingLecture o.docx
Week 11Linux InternalsProcesses, schedulingLecture o.docxmelbruce90096
 
UNIT-2-Process-Management.pdf
UNIT-2-Process-Management.pdfUNIT-2-Process-Management.pdf
UNIT-2-Process-Management.pdfaakritii765
 
Chapter -2 operating system presentation
Chapter -2 operating system presentationChapter -2 operating system presentation
Chapter -2 operating system presentationchnrketan
 
CS9222 Advanced Operating System
CS9222 Advanced Operating SystemCS9222 Advanced Operating System
CS9222 Advanced Operating SystemKathirvel Ayyaswamy
 
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
 
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
 
opearating system notes mumbai university.pptx
opearating system notes mumbai university.pptxopearating system notes mumbai university.pptx
opearating system notes mumbai university.pptxssuser3dfcef
 
Lecture_Slide_4.pptx
Lecture_Slide_4.pptxLecture_Slide_4.pptx
Lecture_Slide_4.pptxDiptoRoy21
 
operatinndnd jdj jjrg-system-1(1) (1).pptx
operatinndnd jdj jjrg-system-1(1) (1).pptxoperatinndnd jdj jjrg-system-1(1) (1).pptx
operatinndnd jdj jjrg-system-1(1) (1).pptxkrishnajoshi70
 

Similar to Advanced Operating Systems......Process Management (20)

Operating Systems
Operating Systems Operating Systems
Operating Systems
 
Chapter 1 Introduction to Operating System Concepts
Chapter 1 Introduction to Operating System ConceptsChapter 1 Introduction to Operating System Concepts
Chapter 1 Introduction to Operating System Concepts
 
Bedtime Stories on Operating Systems.pdf
Bedtime Stories on Operating Systems.pdfBedtime Stories on Operating Systems.pdf
Bedtime Stories on Operating Systems.pdf
 
Week 11Linux InternalsProcesses, schedulingLecture o.docx
Week 11Linux InternalsProcesses, schedulingLecture o.docxWeek 11Linux InternalsProcesses, schedulingLecture o.docx
Week 11Linux InternalsProcesses, schedulingLecture o.docx
 
UNIT-2-Process-Management.pdf
UNIT-2-Process-Management.pdfUNIT-2-Process-Management.pdf
UNIT-2-Process-Management.pdf
 
Chapter -2 operating system presentation
Chapter -2 operating system presentationChapter -2 operating system presentation
Chapter -2 operating system presentation
 
OS-Process.pdf
OS-Process.pdfOS-Process.pdf
OS-Process.pdf
 
CS9222 Advanced Operating System
CS9222 Advanced Operating SystemCS9222 Advanced Operating System
CS9222 Advanced Operating System
 
OS (1).pptx
OS (1).pptxOS (1).pptx
OS (1).pptx
 
Ch3 processes
Ch3   processesCh3   processes
Ch3 processes
 
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
 
Os
OsOs
Os
 
LP-Unit3.docx
LP-Unit3.docxLP-Unit3.docx
LP-Unit3.docx
 
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
 
opearating system notes mumbai university.pptx
opearating system notes mumbai university.pptxopearating system notes mumbai university.pptx
opearating system notes mumbai university.pptx
 
Lecture_Slide_4.pptx
Lecture_Slide_4.pptxLecture_Slide_4.pptx
Lecture_Slide_4.pptx
 
operatinndnd jdj jjrg-system-1(1) (1).pptx
operatinndnd jdj jjrg-system-1(1) (1).pptxoperatinndnd jdj jjrg-system-1(1) (1).pptx
operatinndnd jdj jjrg-system-1(1) (1).pptx
 
Os
OsOs
Os
 
Os
OsOs
Os
 
Cs8493 unit 2
Cs8493 unit 2Cs8493 unit 2
Cs8493 unit 2
 

Recently uploaded

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Recently uploaded (20)

Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

Advanced Operating Systems......Process Management

  • 1. Advanced Operating Systems Unit 3 : Process Environment, Process Control and Process Relationships Vijaya Kumbhar - Asstt. Professor , - Indira College of Commerce and Science,Pune
  • 2. Contents •Process states and transitions, the context of a process, saving the context of a process, sleep, process creation, signals, process termination, awaiting process termination, invoking other programs, the user id of a process •Process termination, environment list, memory layout of a C program, shared libraries, memory allocation, environment variables, setjmp and longjmp, getrlimit and setrlimit, process identifiers, fork, vfork, exit, wait and waitpid, waitid, wait3 and wait4, race conditions, exec •changing user IDs and group IDs, interpreter files,
  • 3. Contents •process times, Terminal logins, network logins, process groups, sessions, controlling terminal, tcgetpgrp, tcsetpgrp, and tcgetsid functions, job control, shell exe cution of programs, orphaned process groups •The Process ID, Running a New Process, Terminating a Process, Waiting for Terminated Child Processes, Users and Groups, Sessions and Process Groups, Daemons, Process Scheduling, Yielding the Processor, Process Priorities, Processor Affinity
  • 4. Process  Program in execution  Task  Group of instructions  It is created using fork() and exec().  When you execute a program on your Unix system, the system creates a special environment for that program. ... A process, in simple terms, is an instance of a running program. The operating system tracks processes through a five-digit ID number known as the pid or the process ID.
  • 5. Parent Process  Process which creates another process  Process which is created by another process Child Process Orphan Process  An orphan process is a computer process whose parent process has finished or terminated, though it remains running itself. In a Unix-like operating system any orphaned process will be immediately adopted by the special init system process. Zombie Process On Unix and Unix-like computer operating systems, a zombie process or defunct process is a process that has completed execution (via the exit system call) but still has an entry in the process table: it is a process in the "Terminated state".
  • 6. Parent-Child Relationship  The PPID is the PID of the process's parent. For example, if process1 with a PID of 101 starts a process named process2, then process2 will be given a unique PID, such as 3240, but it will be given the PPID of 101. It's a parent-child relationship. A daemon is a type of program on Unix-like operating systems that runs unobtrusively in the background, rather than under the direct control of a user, waiting to be activated by the occurrence of a specific event or condition. ... Daemons are usually instantiated as processes. Daemon Process Foreground Process  A foreground process is any command or task you run directly and wait for it to complete. Some foreground processes show some type of user interface that supports ongoing user interaction, whereas others execute a task and "freeze" the computer while it completes that task.  e.g. $ ls Background Process Unlike with a foreground process, the shell does not have to wait for a background process to end before it can run more processes. e.g. $ ls &
  • 7. Process states and transitions
  • 8. Process states  Created: The process is just created/born.  Ready to Run(Memory): The process is in queue and can start running if scheduled.  Ready to Run(Swapped):The process is in queue and swapped due to memory shortage.  User Running : The process is executing CPU instructions.  Kernel Running: The process is executing a system call or interrupt.  Preempted : The process has paused due to preemption of higher priority process or interrupt or more eligible process.  Asleep in Memory : The process is requiring some resource which is not available currently, hence waiting for the resource.  Sleep – Swapped: : The process is requiring some resource which is not available currently and it is swapped due memory shortage.  Zombie : The process is dead but have not been removed from the process table.
  • 9. Unix Process Management ♦ Operating system functions executes within user process. ♦ 2 modes of execution – User mode and Kernel mode ♦ 2 types of processes are available – System processes(Execute OS code) – User processes( Execute user program code). ♦ System call is used to transfer from user mode to system mode. -Process 0 is a special process that is created when the system boots. Process 1 (init process) is the child of Process 0. All the other processes in UNIX has Process 1 as ancestor. All new processes are created under Process 1 (init process).
  • 10. Memory layout of a process  A process can broadly be defined into following segments : Stack Stack contains all the data that is local to a function like variables, pointers etc. Each function has its own stack. Stack memory is dynamic in the sense that it grows with each function being called. Heap Heap segment contains memory that is dynamically requested by the programs for their variables. Data All the global and static members become part of this segment. Text All the program instructions, hard-coded strings, constant values are a part of this memory area.
  • 11. Process Description/Context of process  Definition: “snapshot”, i.e. complete information about a process at some point during its execution ♦ Elements of process image -- divided into 3 parts – User level context • Process text, Process data, User stack and Shared memory. – Register context • Program counter, Process status registers, stack pointer, general purpose registers… – System level context • Process table entry, User area, Per process region table, Kernel stack – When a process is not running the processor status information is stored in register context area
  • 12. Unix Process Table Entry♦ Process Id ♦ Process state ♦ Pointers – to user area & process memory area (text, data, stack) ♦ Process size – enables OS to know how much space to allocate ♦ User identifier – Real user ID -ID of user who is responsible for the process – Effective user ID - ID used by process to gain temporary privilege, while the program is being executed as a part of process. – Process identifiers - ID of the process ♦ Event descriptor - valid when a process is in sleep state. When the event occurs, the process is transferred to a ready to run state. ♦ Priority -used for scheduling ♦ Signal -enumerates signals send to process but not yet handled. ♦ Timers-Process execution time, kernel resource utilization, and user set timer used to send alarm signal to a process. ♦ P_link - pointer to the next link in the ready queue. ♦ Memory status - indicates the process image is in main memory or
  • 13. UNIX User Area(u-area) ♦ Process table pointer - Indicates entry corresponding to the user area. ♦ User identifiers - Real & Effective user Ids, used to determine user privileges. ♦ Timers - Record time that the process spent executing in user mode & kernel mode. ♦ Signal handling array - For each type of signal defined in the system, indicate how the process will react to receipt of that signal. ♦ Control terminal - Indicate login terminal for this process, if exist. ♦ Error field - Record errors encountered during system call. ♦ Return value - Contain result of s/m call ♦ I/O parameters - Describes amount of data transfer, the address of the source data array in user space, file offset for I/O. ♦ File parameters - Current directory & current root describe the file system environment of the process. ♦ User file descriptor table - Record the file the process has open ♦ Limit fields - Restrict the size of the process & size of the file it can write.
  • 14. System level context ♦ Two parts – 1. Static (Process table entry, User area, Per process region table). – 2. Dynamic (Kernel stack) – Process table entry contains process control information that is accessible to the kernel to the kernel at all time. So in VM systems all process table entries are maintained in main memory. – User area contains additional process control information that is needed by the kernel when it executes in context of a process. It is also used when swapping process to and from the memory. – Process reg. table is used by memory management s/m – Kernel stack – used when the process is executing in kernel mode and contain information that must be saved
  • 15. Types of processes in UNIX  ♦ Mainly 3 types – User process – Daemon process – Kernel process – Daemon process • Performs the function in a system wide basis. The function can be of any auxiliary kind, but they are vital in controlling the computational environment of the system. • Example Print spooling, Network Management. • Once created Daemon process can exist throughout the life time of the Operating System
  • 16. Process Tree in a UNIX system
  • 17. Process Creation  Unix fork() creates a process ◦ Creates a new address space ◦ Copies text, data, & stack into new adress space ◦ Provides child with access to open files  Unix exec() allows a child to run a new program  Unix wait() allows a parent to wait for a child to terminate
  • 18. Process Creation  Syntax: pid = fork(); pid – PID of child process (parent) 0 (child)  Algorithm: 1. Check for available memory. 2. Check that user is not running too many processes. 3. Allocate new proc structure, assign new PID. (PIDS start from 1 and increase by 1 until wraparound at maximum value) 4. Copy data from parent proc structure to child. real/effective UID, scheduling parameters, signal masks parent process field of child is set, pointers to parent and sibling procs child state is set to BEING CREATED
  • 19. 5. Clear accounting information, timers, pending signals. 6. Connect new proc on relevant linked lists. 7. Increment reference count of inode of current directory. Increment global file table reference count associated with each open file of parent process. (child inherits access rights to open files child shares global file table entries with parent ) changes in file offset caused by read/write in the parent are visible to child and vice versa) 8. Allocate memory and create copy of parent context (u area, regions, page tables) (shared regions are not copied, only ref. count is incremented) 9. Copy parent’s kernel-level context (registers + kernel stack). 10. Parent: return PID to user Child: “saved” context is restored, returns 0 to user Operating
  • 20. Example int pidValue; pidValue = fork(); /* Creates a child process */ if(pidValue == 0) { /*pidValue is 0 for child, nonzero for parent */ /* The child executes this code concurrently with parent */ childsPlay(...); /* A procedure linked into a.out */ exit(0); } /* The parent executes this code concurrently with child */ parentsWork(...); wait(...);
  • 21. Termination of a process in UNIX Syntax: exit(status);  status – value returned to parent proc.  may be called explicitly/implicitly (startup routine linked with all  C programs calls exit when program returns from main)  kernel may also invoke exit() when an uncaught signal is  received Algorithm:  1. Disable signal handling.  2. Close all open files, release inode for current directory.  3. Release all user memory.
  • 22. 6. Change process state to ZOMBIE and put proc on zombie process list. 7. Assign parent PID of all live child processes to 1 (init); if any child process is ZOMBIE, current process sends init a SIGCHLD, init deletes proc structure for the process. 8. Send SIGCHLD to parent process. 9. Jump to context switch code.
  • 23.  Syntax: execve(filename, argv, envp);  filename – name of executable file  argv – parameters to program (char **)  envp – environment of program (char **)  Algorithm:  1. Convert path name into inode for executable file.  2. Check that file is an executable with proper permissions for the user.  3. Read file header to determine layout of the executable file. (i) primary header – magic number (specifies type of exec. file), no. of sections, start address for process execution (ii) section headers – section type, size, virtual address Invoking a program
  • 24. (iii) sections – code, data (initial contents of process address space) (iv) misc. sections – symbol tables, debugging info, etc. 4. Copy parameters from old address space to kernel space. (old address space will be freed ) params have to be saved on: kernel stack + additional storage (if needed)) 5. Free memory occupied by the process. 6. Allocate memory for the new process’ code, data, stack. 7. Load contents of executable file into memory (code, initialized data). 8. Copy parameters to new user stack. 9. Clear addresses of user signal handlers from u area.
  • 25. Wait statement in UNIX – Pi can wait for the termination of a child – Wait(address(xyz)); // xyz - variable within the address space of Pi. – If process Pi has child processes & at least one of them has already terminated, the wait call stores the termination status of the terminated child process into xyz and immediately return with the id of the terminated child process. If more child processes exists their termination status would be made available to Pi only when it repeats the wait call. – Process Pi is blocked if it has children but none of them has terminated, it will be unblocked when one of the child process terminates. The wait call returns a –1 if Pi has no children
  • 26. Example for wait int main() { int i,saved_status; for(i=0;i<3;i++) { if (fork()==0) { // Child Process exit(); } } while(wait(&saved_status)!= -1); // Loop till all children terminates }
  • 27. Context switch  A context switch (also sometimes referred to as a process switch or a task switch) is the switching of the CPU (central processing unit) from one process or thread to another. A process (also sometimes referred to as a task) is an executing (i.e., running) instance of a program.  Context switching is overhead because it is cycles (time) that the processor is being used but no user code is executing, so no directly productive computing is getting done. Context switching hurts performance: The cycles to actually perform
  • 28. Reasons of context switch When a process 1. puts itself to sleep (via sleep ()) 2. exits (conclusion of exit system call invokes context switch code) 3. returns from kernel mode to user mode but is not the most eligible process to run. 4. TRO(Time Run Out)  Kernel ensures consistency before switching context (completes necessary updates, does appropriate locking/unlocking operation) e.g. when a process goes to sleep waiting for I/O, kernel locks allocated buffer so that no other process can access/corrupt it  link system call: releases lock of 1st inode before
  • 29.  Principle: 1. Save the process context at some point. 2. Proceed to execute scheduling algorithm and context switch code in the context of the old process. 3. When context is restored later, execution should resume according to previously saved context. Problem: distinguishing between 2 and 3 save_context(current); /* scheduling algorithm */ resume_context(new);
  • 30. Saving the context of process 1. Save current PC and other registers. 2. Set return value register of save_context to 0 in the saved register context. 3. Kernel continues to execute in the context of Pold to select Pnew. 4. resume_context automatically switches to Pnew. 5. When Pold is scheduled, PC is set to old value (saved in step 1). 6. Kernel resumes execution of Pold at the end of save_context. 7. On return, execution jumps over resume_context code. ALT: PC may be set artificially to point to instruction where
  • 31. Interrupt handling in UNIX ♦ Will execute only one interrupt at a time ( to avoid race condition). ♦ Each interrupt is assigned an interrupt priority level. An interrupt priority level is also assigned to CPU. ♦ When an interrupt at priority level ‘l’ arises, it is handled only if l> CPU’s interrupt priority else kept pending till CPU’s interrupt priority level assumes a lower value.
  • 32. System calls in UNIX – System calls accepts parameters relevant to its functioning – When a call occurs these parameters exists on the user stack of the process which issues the system call. – The call number is expected to be in register 0 – System call handler obtain this number to determine which system functionality being invoked. – From its internal table it knows the address of the handler for that function. – Parameters of the system call exists on the user stack of the process making the call. – Before passing control to the handler for a specific call these parameters are copied from the user stack into some standard places in the user area.
  • 33. System calls in UNIX Cont… – A signal can be send to a process/Group of processes using kill(<pid>,<signum>) system call. Where pid is the id of the process signal to be sent.(sender must know receiver address & receiver must be in the same process tree). – Pid value 0 Æ signal to be sent to all processes in the same group as the sender process. – Pid value –1 Æ to reach processes outside the process tree of the sender.
  • 34. Signals  Signals are a limited form of inter- process communication (IPC), typically used in Unix, Unix-like, and other POSIX-compliant operating systems.  A signal is an asynchronous notification sent to a process or to a specific thread within the same process in order to notify it of an event that occurred.
  • 35. Signal handling in UNIX ♦ Oldfunction = signal(<signum>,<function>) – Where signal is a function in C library which makes a signal system call. Signum is an integer & function is the function name. – The function should be executed on occurrence of signal <signum>. – User can specify 0 or 1 instead of function. Where 0 indicates the default action defined in the Kernel is to be executed & 1is occurrence of signal is to be ignored. Whenever a signal is send to a process, the bit corresponding to the signal is set to 1 in the proc structure of the destination process. The kernel now determines if the signal is being ignored by the destination process. If not it will makes provision to deliver the signal to the process. If the signal is ignored it remains pending and is delivered when the process is ready to accept it. In UNIX signal remains pending if the process to which it is intended is in block state. The signal would be delivered when the process comes out of the blocked state. Signals are delivered when a process returns from a
  • 36. Interesting signals in UNIX ♦ SIGCHLD Child process died or suspended ♦ SIGFPE Arithmetic fault ♦ SIGILL Illegal instruction ♦ SIGINT tty interrupt (Control C) ♦ SIGKILL Kill process ♦ SIGSEGV Segmentation fault ♦ SIGSYS Invalid System call ♦ SIGXCPU Exceeds CPU limit ♦ SIGXFSZ Exceeds file size limit
  • 37. Execlp demo #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> main() { pid_t pid; if ((pid = fork()) == -1) perror("fork error"); else if (pid == 0) { execlp("newShell", "newShell", NULL); printf("Return not expected. Must be an execlp error.n"); } }
  • 38. Environment variables in UNIX  An environment variable is a dynamic-named value that can affect the way running processes will behave on a computer.  The commands env, set, and printenv display all environment variables and their values.  printenv can also be used to print a single variable by giving that variable name as the sole argument to the command.
  • 39. Environment variables in UNIX  PATH : a list of directory paths. ...  HOME (Unix-like) and USERPROFILE (Microsoft Windows): indicate where a user's home directory is located in the file system.  HOME/{.AppName} (Unix-like) and APPDATA{DeveloperNameAppName } (Microsoft Windows): for storing application settings.
  • 40.  TERM (Unix-like): specifies the type of computer terminal or terminal emulator being used (e.g., vt100 or dumb).  PS1 (Unix-like): specifies how the prompt is displayed in the Bourne shell and variants.  MAIL (Unix-like): used to indicate where a user's mail is to be found.  TEMP: location where processes can store temporary files.
  • 41. Setjmp and longjmp  “Setjump” and “Longjump” are defined in setjmp.h, a header file in C standard library.  setjump(jmp_buf buf) : uses buf to remember current position and returns 0.  longjump(jmp_buf buf, i) : Go back to place buf is pointing to and return i .
  • 42. // A simple C program to demonstrate working of setjmp() and longjmp() #include<stdio.h> #include<setjmp.h> jmp_buf buf; void func() { printf("Welcome n"); // Jump to the point setup by setjmp longjmp(buf, 1); printf(“Val2n"); } int main() { // Setup jump position using buf and return 0 if (setjmp(buf)) printf(“Val3n"); else { printf(“Val4n"); func(); } return 0;
  • 43. Output : Val4 Welcome Val3 ----------------------------------------------------  This is mainly used to implement exception handling in C.  setjmp can be used like try (in languages like C++ and Java).  The call to longjmp can be used like throw (Note that longjmp() transfers control to the point set by setjmp()).
  • 44. getrlimit and setrlimit  It allows a process to read and set limits on the system resources that it can consume.  Some of the most useful resource limits that may be changed are listed here, with their codes:  RLIMIT_CPU—The maximum CPU time, in seconds, used by a program. This is the amount of time that the program is actually executing on the CPU, which is not necessarily the same as wall-clock time. If the program exceeds this time limit, it is terminated with a SIGXCPU signal.  RLIMIT_DATA—The maximum amount of memory that a program can allocate for its data. Additional allocation
  • 45. getrlimit and setrlimit  RLIMIT_NPROC—The maximum number of child processes that can be running for this user. If the process calls fork and too many processes belonging to this user are running on the system, fork fails.  RLIMIT_NOFILE—The maximum number of file descriptors that the process may have open at one time.
  • 46. Example (limit-cpu.c) CPU Time Limit Demonstration #include <sys/resource.h> #include <sys/time.h> #include <unistd.h> int main () { struct rlimit rl; /* Obtain the current limits. */ getrlimit (RLIMIT_CPU, &rl); /* Set a CPU limit of 1 second. */ rl.rlim_cur = 1; setrlimit (RLIMIT_CPU, &rl); /* Do busy work. */ while (1); return 0;
  • 47. Output: When the program is terminated by SIGXCPU, the shell helpfully prints out a message interpreting the signal: $./limit_cpu CPU time limit exceeded
  • 48. process identifiers In computing, the process identifier (normally referred to as the process ID or PID) is a number used by most operating system kernels—such as those of UNIX, macOS and Microsoft Windows—to uniquely identify an active process.
  • 49. Process Identifiers in UNIX  PID – Process Identification Number  GID- Process Group Number  PPID - Parent Process Identification Number  RUID- Real User Identification Number  EUID- Effective User Identification Number  RGID- Real Group Identification Number  EGID- Effective Group Identification Number
  • 50.  #include <sys/types.h>  #include <unistd.h>  pid_t getpid(void);  pid_t getppid(void);  uid_t getuid(void);  uid_t geteuid(void);  int seteuid(pid_t pid,uid_t);  gid_t getgid(void);  int setpgid(pid_t pid, pid_t pgid);  gid_t getegid(void);
  • 51. Fork()  Used to create new process.  The code of child process is identical to the code of its parent process.  After the creation of child process, both process i.e. parent and child process start their execution from the next statement after fork() and both the processes get executed simultaneously.  The parent process and child process do have separate address space. Hence, when any of the processes modifies any statement or variable in the code. It would not be reflected in other process codes. Let’s suppose if child process modifies the code it would not affect the parent process.  Some child process after their creation immediately calls exec(). The exec() system call replaces the process with the program specified in its parameter. Then the separate address space of child process is of no use. The one alternative here is copy-on- write.  The copy-on-write let the parent and child process to share same address space. If the any of the processes writes on the
  • 52. Vfork()  The modified version of fork() is vfork().  The vfork() system call is also used to create a new process.  The child process code is also identical to the parent process code. Here, the child process suspends the execution of parent process till it completes its execution as both the process share the same address space to use.  As the child and parent process shares the same address space. If any of the processes modifies the code, it is visible to the other process sharing the same pages. Let us suppose if the parent process alters the code; it will reflect in the code of child process.  As using vfork() does not create separate address spaces for child and parent processes. Hence, it must be implemented where the child process calls exec() immediately after its creation. So, there will be no wastage of address space, and it is the efficient way to create a
  • 53. Fork() vfork() Functions On Real Kernels Vicariously Functions On Real Kernels allows the execution of parent and child process simultaneously suspends the execution of parent process until child process completes its execution child process created using fork has separate address space as that of the parent process child process created using vfork has to share the address space of its parent process. If the child process alters any page in the address space, it is invisible to the parent process as the address space are separate. If child process alters any page in the address space, it is visible to the parent process as they share the same address space. COW(Copy on Write)bit is ON COW(Copy on Write) bit is OFF
  • 54. Conclusion of fork and vfork()  The vfork() system call has to be implemented when child process call exec() immediately after its creation using fork(). As separate address space for child and parent process will be of no use here.
  • 55. exit(), _exit() and _Exit()  a computer process terminates its execution by making an exit system call.  When the child process terminates ("dies"), either normally by calling exit, or abnormally due to a fatal error or signal (e.g., SIGTERM, SIGINT, SIGKILL), an exit status is returned to the operating system and a SIGCHLD signal is sent to the parent process.  The exit status can then be retrieved by the parent process via the wait system call.  Most operating systems allow the terminating process to provide a specific exit status to the system, which is made available to the parent process. Typically this is an integer value,
  • 56. wait A call to wait() blocks the calling process until one of its child processes exits or a signal is received. After child process terminates, parent continues its execution after wait system call instruction. Child process may terminate due to any of these:  It calls exit();  It returns (an int) from main  It receives a signal (from the OS or another process) whose default action is to terminate.
  • 57.  If any process has more than one child processes, then after calling wait(), parent process has to be in wait state if no child terminates.  If only one child process is terminated, then return a wait() returns process ID of the terminated child process.
  • 58. waitid  The waitid() system call (available since Linux 2.6.9) provides more precise control over which child state changes to wait for.  Syntax: int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);
  • 59.  int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);  The idtype and id arguments select the child(ren) to wait for, as follows:  idtype == P_PID Wait for the child whose process ID matches id. idtype == P_PGID Wait for any child whose process group ID matches id. idtype == P_ALL Wait for any child; id is ignored.
  • 60. waitpid  waitpid(-1, &status, 0);  The waitpid() system call suspends execution of the calling process until a child specified by pid argument has changed state. By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument, as described below. The value of pid can be:  < -1 meaning wait for any child process whose process group ID is equal to the absolute value of pid.  -1 meaning wait for any child process.  0 meaning wait for any child process whose process group ID is equal to that of the calling process.  > 0 meaning wait for the child whose process ID is equal to the value of pid.
  • 61. Wait3 and wait4  pid_t wait3(int *status, int options, struct rusage *rusage);  pid_t wait4(pid_t pid, int *status, int options, struct rusage *rusage); Wait for process to change state. The wait3() and wait4() system calls are similar to waitpid(2), but additionally return resource usage information about the child in the structure pointed to by rusage.
  • 62. Other than the use of the rusage argument, the following wait3() call: wait3(status, options, rusage); is equivalent to: waitpid(-1, status, options); Similarly, the following wait4() call: wait4(pid, status, options, rusage); is equivalent to: waitpid(pid, status, options); In other words, wait3() waits of any child, while wait4() can be used to select a specific child, or children, on
  • 63. atexit()  It causes the specified function func to be called when the program terminates.  The termination function can be registered anywhere in the program, but it will be called at the time of the program termination.  Syntax: int atexit(void (*func)(void))
  • 64. Example #include <stdio.h> #include <stdlib.h> void functionA () { printf("This is functionAn"); } int main () { atexit(functionA ); printf("Starting main program...n"); printf("Exiting main program...n"); return(0); }
  • 65. Output Starting main program... Exiting main program... This is functionA
  • 66. Race conditions  A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence to be done correctly.
  • 67. Race Condition Example static void charatatime(char *); int main(void) { pid_t pid; if( (pid = fork()) < 0) { perror("Fork error"); exit(1); } else if( pid == 0) { charatatime("Output from childn"); } else { charatatime("Output from parentn"); } exit(0); } static void charatatime(char * str) { char * ptr; int c; setbuf(stdout,NULL); for(ptr = str; c = *ptr++; ) putc(c, stdout); }
  • 68. Exec family of functions  The exec family of functions replaces the current running process with a new process.  It can be used to run a any program by using C program.  It comes under the header file unistd.h.  execl  execlp  execle  execlpe  execv  execvp  execve  execvpe
  • 69.  int execl( path, arg0, arg1..., argn, NULL );  int execle( path, arg0, arg1..., argn, NULL, envp );  int execlp( file, arg0, arg1..., argn, NULL );  int execlpe( file, arg0, arg1..., argn, NULL, envp );  int execv( path, argv );  int execve( path, argv, envp );  int execvp( file, argv );  int execvpe( file, argv, envp ); ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ -------------------------------------------- const char *path; const char *file; const char *arg0,..., *argn;
  • 70.  The exec functions load and execute a new child process, named by path or file. If the child process is successfully loaded, it replaces the current process in memory. No return is made to the original program.
  • 71. gcc EXEC.c -o EXEC  //EXEC.c   #include<stdio.h>  #include<unistd.h>   int main()  {  int i;   printf("I am EXEC.c called by execvp() ");  printf("n");   return 0;  }
  • 72.  //execDemo.c   #include<stdio.h>  #include<stdlib.h>  #include<unistd.h>  int main()  {  //A null terminated array of character  //pointers  char *args[]={"./EXEC",NULL};  execvp(args[0],args);   /*All statements are ignored after execvp() call as this whole  process(execDemo.c) is replaced by another process (EXEC.c)  */  printf("Ending-----");   return 0;  }
  • 73.  gcc execDemo.c -o execDemo  Output: I AM EXEC.c called by execvp()
  • 74. changing user IDs and group IDs  #include <unistd.h>  int setuid(uid_t uid);  int setgid(gid_t gid);
  • 75. interpreter files  Unix Shell Scripts. On Unix systems, a Shell-Script is a file (with execute permissions) whose first two characters are `#!‘.  Shell scripts are short programs that are written in a shell programming language and interpreted by a shell process. They are extremely useful for automating tasks on Linux and other Unix-like operating systems
  • 76. #!/bin/sh # This is a comment! echo Hello World echo Hello echo World ----------------------------------------------------- - $./first.sh
  • 77. system function  system() is used to invoke an operating system command from a C/C++ program. int system(const char *command);
  • 79. process accounting acct: process accounting file #include <sys/acct.h>  If the kernel is built with the process accounting option enabled, then calling acct(2) starts process accounting, for example:  acct("/var/log/pacct");  When process accounting is enabled, the kernel writes a record to the accounting file as each process on the system terminates. This record contains information about the terminated process, and is defined in <sys/acct.h> as follows:
  • 80. struct acct { char ac_flag; /* Accounting flags */ u_int16_t ac_uid; /* Accounting user ID */ u_int16_t ac_gid; /* Accounting group ID */ u_int16_t ac_tty; /* Controlling terminal */ u_int32_t ac_btime; /* Process creation time (seconds since the Epoch) */ comp_t ac_utime; /* User CPU time */ comp_t ac_stime; /* System CPU time */ comp_t ac_etime; /* Elapsed time */ comp_t ac_mem; /* Average memory usage (kB) */ comp_t ac_io; /* Characters transferred (unused) */ comp_t ac_rw; /* Blocks read or written (unused) */ comp_t ac_minflt; /* Minor page faults */ comp_t ac_majflt; /* Major page faults */ comp_t ac_swaps; /* Number of swaps (unused) */ u_int32_t ac_exitcode; /* Process termination status (see wait(2)) */ char ac_comm[ACCT_COMM+1]; /* Command name (basename of last executed command; null-terminated) */ char ac_pad[X]; /* padding bytes */ };
  • 81. Effective user ID/Group ID  The effective UID (euid) of a process is used for most access checks.  It is also used as the owner for files created by that process.  The effective GID (egid) of a process also affects access control.
  • 82. File system user ID  Linux also has a file system user ID (fsuid) which is used explicitly for access control to the file system.  It matches the euid unless explicitly set otherwise.  It may be root's user ID only if ruid, suid, or euid is root.
  • 83. user identification  getuid, geteuid - get user identity #include <unistd.h> #include <sys/types.h> uid_t getuid(void); uid_t geteuid(void); getuid() returns the real user ID of the current process. geteuid() returns the effective user ID of the current process.
  • 84. Saved user ID  The saved user ID (suid) is used when a program running with elevated privileges needs to do some unprivileged work temporarily; changing euid from a privileged value (typically 0) to some unprivileged value (anything other than the privileged value) causes the privileged value to be stored in suid.[3]  Later, a program's euid can be set back to the value stored in suid, so that elevated privileges can be restored; an unprivileged process may set its euid to one of only three values: the value of ruid, the value of suid, or the value of euid.
  • 85. Real user ID/Group ID  The real UID (ruid) and real GID (rgid) identify the real owner of the process and affect the permissions for sending signals.  A process without superuser privileges may signal another process only if the sender's ruid or euid matches receiver's ruid or suid.  Because a child process inherits its credentials from its parent, a child and parent may signal each other.
  • 86. changing user IDs and group IDs,  setuid() sets the effective user ID of the calling process.  seteuid - sets effective user.  setegid - sets effective group ID.
  • 87. process times  times - get process times #include <sys/times.h> clock_t times(struct tms *buf);  times() stores the current process times in the struct tms that buf points to. The struct tms is as defined in <sys/times.h> struct tms { clock_t tms_utime; /* user time */ clock_t tms_stime; /* system time */ clock_t tms_cutime; /* user time of children */ clock_t tms_cstime; /* system time of children */ };
  • 89.
  • 90. network logins  The connection between the terminal and the computer isn't point-to-point. In this case, login is simply a service available, just like any other network service, such as FTP or SMTP.  With the terminal logins, init knows which terminal devices are enabled for logins and spawns a getty process for each device.  In the case of network logins, all the logins come through the kernel's network interface drivers (e.g., the Ethernet driver), and we don't know ahead of time how many of these will occur.  To allow the same software to process logins over both terminal logins and network logins, a software driver called a pseudo terminal is used to emulate the behavior of a serial terminal and map terminal operations to network operations, and vice versa.
  • 91. Sequence of processes involved in executing TELNET server
  • 92. process groups  a process group denotes a collection of one or more processes.  Among other things, a process group is used to control the distribution of a signal;  when a signal is directed to a process group, the signal is delivered to each process that is a member of the group.  When a process replaces its image with a new image (by calling one of the exec functions), the new image is subjected to the same process group (and thus session) membership as the old image.
  • 93. Sessions  A session denotes a collection of one or more process groups.  A process group is not permitted to migrate from one session to another, and a process may not create a process group that belongs to another session.  A process is not permitted to join a process group that is a member of another session—that is, a process is not permitted to migrate from one
  • 94. controlling terminal Sessions and process groups have a few other characteristics.  A session can have a single controlling terminal. This is usually the terminal device (in the case of a terminal login) or pseudo- terminal device (in the case of a network login) on which we log in.  The session leader that establishes the connection to the controlling terminal is called the controlling process.  The process groups within a session can be divided into a single foreground process group and one or more background process
  • 95.  If a session has a controlling terminal, it has a single foreground process group, and all other process groups in the session are background process groups.  Whenever we type the terminal's interrupt key (often DELETE or Control-C), this causes the interrupt signal be sent to all processes in the foreground process group.  Whenever we type the terminal's quit key (often Control-backslash), this causes the quit signal to be sent to all processes in the foreground process group.  If a modem (or network) disconnect is detected by the terminal interface, the hang-up signal is sent to the controlling process (the session
  • 97. tcgetpgrp and tcsetpgrp  tcgetpgrp, tcsetpgrp - get and set terminal foreground process group. #include <unistd.h> pid_t tcgetpgrp(int fd); int tcsetpgrp(int fd, pid_t pgrp); The function tcgetpgrp() returns the process group ID of the foreground process group on the terminal associated to fd, which must be the controlling terminal of the calling process.
  • 98. The function tcsetpgrp() makes the process group with process group ID pgrp the foreground process group on the terminal associated to fd, which must be the controlling terminal of the calling process, and still be associated with its session. pgrp must be a (nonempty) process group belonging to the same session as the calling process. If tcsetpgrp() is called by a member of a background process group in its session, and the calling process is not blocking or ignoring SIGTTOU, a SIGTTOU signal is sent to all members of this background process group.
  • 99. tcgetsid functions  tcgetsid - get the process group ID for the session leader for the controlling terminal. #include <termios.h> pid_t tcgetsid(int fildes); The tcgetsid() function shall obtain the process group ID of the session for which the terminal specified by fildes is the
  • 100. job control commands Command Explanation Example & Run the command in the background % long_cmd & Ctrl-z Stop the foreground process [Ctrl-z] Stopped jobs List background processes % jobs [1] - Stopped vi [2] - big_job & %n Refers to the background % fg %1
  • 101. job control commands Command Explanation Example %?str Refers to the background job containing str % fg %?ls bg Restart a stopped background process % bg [2] big_job & fg Bring a background process to the foreground % fg %1
  • 102. job control commands Command Explanation Example ~ Ctrl-z Suspend an rlogin or ssh session host2>~[Ctrl-z] Stopped host1> ~~ Ctrl-z Suspend a second level rlogin or ssh session host3>~~[Ctrl-z] Stopped host2>
  • 103. shell execution of programs,  Let's examine how the shells execute programs and how this relates to the concepts of process groups, controlling terminals, and sessions.  To do this, we'll use the ps command . ps -o pid,ppid,pgid,sid,comm  the output is PID PPID PGID SID COMMAND 949 947 949 949 sh 1774 949 949 949 ps
  • 104.  ps -o pid,ppid,pgid,sid,comm & the only value that changes is the process ID of the command: PID PPID PGID SID COMMAND 949 947 949 949 sh 1812 949 949 949 ps
  • 105.  ps -o pid,ppid,pgid,sid,comm | cat the output is PID PPID PGID SID COMMAND 949 947 949 949 sh 1823 949 949 949 cat 1824 823 949 949 ps
  • 106.
  • 107. orphaned process groups  A process whose parent terminates is called an orphan and is inherited by the init process.  All the process which has same PPID and parent process has been terminated, then all such processes have one group id called as orphaned process group.
  • 108.
  • 109. Process Scheduling, Yielding the Processor  Linux provides a family of system calls for the management of scheduler parameters.  These system calls allow manipulation of process priority, scheduling policy, and processor affinity, as well as provide an explicit mechanism to yield the processor to other tasks.
  • 110. System Call Description nice() Set a process's nice value sched_setschedul er() Set a process's scheduling policy sched_getschedul er() Get a process's scheduling policy sched_setparam() Set a process's real- time priority sched_getparam() Get a process's real- time priority
  • 111. System Call Description sched_get_priority_ max() Get the maximum real- time priority sched_get_priority_ min() Get the minimum real- time priority sched_rr_get_interva l() Get a process's timeslice value sched_setaffinity() Get a process's processor affinity sched_getaffinity() Set a process's processor affinity sched_yield() Temporarily yield the processor
  • 112. Process Priorities  A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system.  As such a CPU bound realtime priority thread can totally ruin a machine.  Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.
  • 113. Processor Affinity  Processor affinity, or CPU pinning, enables the binding and unbinding of a process or a thread to a central processing unit (CPU) or a range of CPUs, so that the process or thread will execute only on the designated CPU or CPUs rather than any CPU.
  • 114. Sample Questions from SPPU QP  What are the components of register context?  The idle process is the actually a process that gets run.Justify.  The timeslice to each process is an important variable in the overall behaviour of the system.Justify  At the Kernel Level ,support for protected process is two fold.
  • 115. Sample Questions from SPPU QP  Explain four basic types of user mode processes?  Explain different types of memory regions found in every process?  The process can access its u-area when it executes in kernel mode but not when it executes in user mode. Justify.  Write a program to demonstrate atexit() system call.