SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Processes



© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>
               All Rights Reserved.
What to Expect?
W's of a Process
Processes in Linux
  Scheduling & Preemption
  Process States & Transitions
  Process Management
  Programming the Processes




         © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   2
                        All Rights Reserved.
What is a Process?
Program in Execution
Executable/Program Loaded → Process
Program is just the Code & initial Data part
Additionally
  Value of Variables
  Stack
  Heap
  Program Counter
  Processor Registers
  And any other OS resources, needed by the Program
make it a Process
               © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   3
                              All Rights Reserved.
Why we need a Process?
To do any task or job
Moreover, to achieve multi-processing
  Really do multiple tasks at a time (in multi-processor
  systems), Or
  At least get a feel of doing multiple tasks at a time (on
  uni-processor systems)
In turn needs
  Timesharing (on same processor)
  Scheduling
  Priority
  And for all these: Process Identifier (pid)
             © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   4
                            All Rights Reserved.
Let's View
Shell Local Processes: ps
Console attached System Processes: ps a
All System Processes: ps ax
List many more details: Add l
Observe
  uid, pid, ppid, priority, nice, status, tty, time
Dynamic Process Status: top
Try pid.c
            © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   5
                           All Rights Reserved.
Processes in Linux




© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   6
               All Rights Reserved.
Linux Schedulers
Provide multi-tasking capabilities by
  Time Slicing
  Preemption
  Based on various task priorities
  Specified by its scheduling policies
Understand the following execution instances
  Kernel Thread
  User Process
  User Thread

          © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   7
                         All Rights Reserved.
Linux Schedulers ...
Linux Basic Scheduling
  Normal (SCHED_OTHER) – Fairness
  Scheduling
Other Advanced Scheduling supported
  Round Robin (SCHED_RR)
  FIFO (SCHED_FIFO)
All Schedulers are O(1)


        © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   8
                       All Rights Reserved.
Linux Kernel Preemption Levels
None (PREEMPT_NONE)
 No forced preemption
 Overall throughput, on average, is good
Voluntary (PREEMPT_VOLUNTARY)
 First stage of latency reduction
 Explicit preemption points are placed at strategic locations
Standard (PREEMPT_DESKTOP)
 Preemption enabled everywhere except within critical sections
 Good for soft real-time applications, like audio, multimedia, …
Kernel Parameter: preempt



             © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>     9
                            All Rights Reserved.
Kernel Preemption Visualization

                            Time

                                                            User Space




                                                            System Call
                                                            Interface




                                                            Kernel Space
      Process A
      Process B


        © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>                  10
                       All Rights Reserved.
Process Context Switch

                              Time



             Save State                           Save State
              into PCB A                           into PCB B
            Reload State                         Reload State
             from PCB B                           from PCB A




Interrupt or System Call             Interrupt or System Call



    Process A              Time Wasted in Context Switch
    Process B



       © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>        11
                      All Rights Reserved.
Generic Process State Diagram
                                       Time Run-Out
     New                                                        Terminated
           Admitted                      Dispatch               Exit
                            Ready                     Running          Zombie
                 Wakeup on
                                              Block on
                 I/O or event
                                              I/O or
                 completion
                                              wait event
                           Blocked                                     Stopped
                Uninterruptible or Interruptible


Ready & Blocked states have Queues
Additional States in Linux
  Defunct / Zombie (Terminated but not reaped by its parent)
  Stopped (By job control signal or because being traced)



                 © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>               12
                                All Rights Reserved.
Linux Process States
Process States as in Linux
  TASK_RUNNING (R) – ready or running
  TASK_INTERRUPTIBLE (S) – blocked (waiting for an event)
  TASK_UNINTERRUPTIBLE (D) – blocked (usually for I/O)
  TASK_ZOMBIE (Z) – terminated but not cleaned up by its
  parent
  TASK_STOPPED (T) – execution stopped
Mutually exclusive
Additional Information: Foreground (+), Threaded (l)



            © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   13
                           All Rights Reserved.
Process Management in Linux
Needs collation of all this information
  Address Space (Code, Variables, Stack, Heap)
  Processor State (PC, Registers, …)
  OS resources in use (File descriptors, ...)
  Scheduling Info, Priority, ...
  Preemption Info, Process State, ...
for every Process
Stored in structure of type 'task_struct'
  Maintained by Linux Kernel on a per process basis
  Also called the Process Descriptor / Process Control Block

             © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   14
                            All Rights Reserved.
Process Control Block (PCB)
Listing: <kernel_source>/include/linux/sched.h
Some of its fields are
  volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */
  void *stack;
  unsigned int flags; /* per process flags */
  int prio, static_prio, normal_prio;
  unsigned int rt_priority;
  const struct sched_class *sched_class;
  unsigned int policy;
  struct mm_struct *mm, active_mm; / Pointers to Memory Regions, Descriptors */
  pid_t pid, tgid;
  struct task_struct *real_parent; /* real parent process */
  struct task_struct *parent; /* recipient of SIGCHLD, wait4() reports */
  struct list_head children /* list of its children */, sibling; /* linkage in its parent's children list */
  struct task_struct *group_leader; /* threadgroup leader */
  struct list_head thread_group;
  struct fs_struct fs; /* file system info like current directory, … */
  struct files_struct files; / file descriptors */
  struct signal_struct signal; / signal handlers */
  sigset_t blocked, real_blocked, saved_sigmask;
  struct sigpending pending; /* signals received */

                              © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>                                15
                                             All Rights Reserved.
Basic Process Management
bg - Starts a suspended process in the
background
fg - Starts a suspended process in the
foreground
jobs - Lists the jobs running
pidof - Find the process ID of a running
program
top - Display the processes that are using
the most CPU resources
        © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   16
                       All Rights Reserved.
Programming Linux Processes




   © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   17
                  All Rights Reserved.
Process Creation
From Shell
  By running a Command / Program / Script (Even by .)
  By 'exec' ing a Command / Program
By Programming
  Using system()
    Simple but Inefficient
    Security risks
  Using fork() and exec() family function
    Comparatively complex
    Greater flexibility, speed, and security

            © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   18
                           All Rights Reserved.
Using the exec family
All exec* functions do the same thing
  Just in different ways
Replaces current program by a new one
And hence never returns, unless an error
New program is immediately started
Process remains the same
  Process Id, Parent Process Id
  Current directory, ...
  Open file descriptor tables, ...
          © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   19
                         All Rights Reserved.
exec* function specifics
exec*p (execvp, execlp)
  Accepts a program name
  Searches it in the current execution path
  Others must be given the full path
execv* (execv, execvp, execve)
  Argument list should be a NULL-terminated array of pointers to strings
execl* (execl, execlp, execle)
  Argument list uses the varargs mechanism
exec*e (execve, execle)
  Accepts an additional argument: an array of environment variables
  It should be a NULL-terminated array of pointers to character strings
  Each character string should be of the form “VARIABLE=value”




                 © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>         20
                                All Rights Reserved.
Cons of using fork
Forked child process executes the copy of
parent process' program
And typically, a fork is followed by exec
  Replacing the copy by the new program
What is the point of copying?
Overhead!! What else?
Is there any way out to prevent this?
Yes. And it is ...
          © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   21
                         All Rights Reserved.
Copy On Write (COW)
Parent and Child shares the Address Space (ro)
Data & other Resources are marked COW
If written to, a duplicate is made and each
process receives a unique copy
Consequently, the duplication of resources occurs
only when they are written to
Avoids copy in cases of immediate exec
fork()'s only overheads
  Duplication of the parent's page tables
  Creation of a unique PCB for the child
           © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   22
                          All Rights Reserved.
Process Termination
Parent & Children Processes terminate as usual
  Success Exit – Normal Success
  Error Exit – Normal Failure
  Fatal Exit – Signaled from Kernel Space for a Bug
  Kill Exit – Signaled by a Process
But which one of them terminates, first?
Does it matter?
If it matters, parents can wait for their children
  Using wait family of system calls
  And can retrieve information about its child’s termination
In fact, wait does the cleanup act for the exited child
             © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   23
                            All Rights Reserved.
Using the wait family
Four different system calls in the wait family
  wait(): Block until one of its child processes exits
  waitpid(): Wait for a specific child to exit/stop/resume
  wait3(): Along with, return resource usage information
  about the exiting/stopping/resuming child process
  wait4(): wait3() for a specific child or children
All of these fill up a status code
  in an integer pointer argument
  about how the child process exited
  which can be decoded using ...


             © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   24
                            All Rights Reserved.
wait status macros
WIFEXITED, WEXITSTATUS
WIFSIGNALED, WTERMSIG, WCOREDUMP
WIFSTOPPED, WSTOPSIG
WIFCONTINUED




       © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   25
                      All Rights Reserved.
What if Parents Don't Wait?
If Parent dies before the Children
  Children become Orphans
  And are adopted by the Init Process
    which then does the cleanup on their exit
If a Child exits before the Parent
  That's a sad thing :)
  It will become a Ghost / Zombie
  Note that, even if the parent does a wait later
    It remains a Zombie till then
         © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   26
                        All Rights Reserved.
Who Cleans Up a Zombie?
Typically, again a Parent
  By doing a wait on it
What if the parent exits without “wait”?
Does it stay around in the system?
Not really. It gets inherited by init
  which then cleans it up, right there




         © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   27
                        All Rights Reserved.
What all have we learnt?
W's of a Process?
Process Scheduling & Preemption in Linux
Process States & Transitions (Linux specific)
Linux Process Management using PCB
Programming Linux Processes
  Creation Techniques: fork, exec* & COW
  Termination & Waiting Techniques
  Orphans & Zombies

         © 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   28
                        All Rights Reserved.
Any Queries?




© 2010 Anil Kumar Pugalia <email@sarika-pugs.com>   29
               All Rights Reserved.

Weitere ähnliche Inhalte

Was ist angesagt?

HKG15-505: Power Management interactions with OP-TEE and Trusted Firmware
HKG15-505: Power Management interactions with OP-TEE and Trusted FirmwareHKG15-505: Power Management interactions with OP-TEE and Trusted Firmware
HKG15-505: Power Management interactions with OP-TEE and Trusted Firmware
Linaro
 
Linux booting procedure
Linux booting procedureLinux booting procedure
Linux booting procedure
Dhaval Kaneria
 

Was ist angesagt? (20)

Basic Linux Internals
Basic Linux InternalsBasic Linux Internals
Basic Linux Internals
 
BusyBox for Embedded Linux
BusyBox for Embedded LinuxBusyBox for Embedded Linux
BusyBox for Embedded Linux
 
Linux-Internals-and-Networking
Linux-Internals-and-NetworkingLinux-Internals-and-Networking
Linux-Internals-and-Networking
 
Linux Internals - Part II
Linux Internals - Part IILinux Internals - Part II
Linux Internals - Part II
 
Linux Internals - Interview essentials 4.0
Linux Internals - Interview essentials 4.0Linux Internals - Interview essentials 4.0
Linux Internals - Interview essentials 4.0
 
The basic concept of Linux FIleSystem
The basic concept of Linux FIleSystemThe basic concept of Linux FIleSystem
The basic concept of Linux FIleSystem
 
U boot-boot-flow
U boot-boot-flowU boot-boot-flow
U boot-boot-flow
 
U-Boot Porting on New Hardware
U-Boot Porting on New HardwareU-Boot Porting on New Hardware
U-Boot Porting on New Hardware
 
U-Boot - An universal bootloader
U-Boot - An universal bootloader U-Boot - An universal bootloader
U-Boot - An universal bootloader
 
HKG15-505: Power Management interactions with OP-TEE and Trusted Firmware
HKG15-505: Power Management interactions with OP-TEE and Trusted FirmwareHKG15-505: Power Management interactions with OP-TEE and Trusted Firmware
HKG15-505: Power Management interactions with OP-TEE and Trusted Firmware
 
Linux device drivers
Linux device drivers Linux device drivers
Linux device drivers
 
Arm device tree and linux device drivers
Arm device tree and linux device driversArm device tree and linux device drivers
Arm device tree and linux device drivers
 
U Boot or Universal Bootloader
U Boot or Universal BootloaderU Boot or Universal Bootloader
U Boot or Universal Bootloader
 
BIOS, Linux and Firmware Test Suite in-between
BIOS, Linux and  Firmware Test Suite in-betweenBIOS, Linux and  Firmware Test Suite in-between
BIOS, Linux and Firmware Test Suite in-between
 
Toolchain
ToolchainToolchain
Toolchain
 
Embedded linux network device driver development
Embedded linux network device driver developmentEmbedded linux network device driver development
Embedded linux network device driver development
 
Linux booting procedure
Linux booting procedureLinux booting procedure
Linux booting procedure
 
Interrupts
InterruptsInterrupts
Interrupts
 
Linux scheduling and input and output
Linux scheduling and input and outputLinux scheduling and input and output
Linux scheduling and input and output
 
Introduction to Linux
Introduction to LinuxIntroduction to Linux
Introduction to Linux
 

Andere mochten auch

6 stages of linux boot process
6 stages of linux boot process6 stages of linux boot process
6 stages of linux boot process
Teja Bheemanapally
 
Packet Filtering Using Iptables
Packet Filtering Using IptablesPacket Filtering Using Iptables
Packet Filtering Using Iptables
Ahmed Mekkawy
 
Linux process management
Linux process managementLinux process management
Linux process management
Raghu nath
 

Andere mochten auch (20)

Iptables in linux
Iptables in linuxIptables in linux
Iptables in linux
 
Iptables
IptablesIptables
Iptables
 
6 stages of linux boot process
6 stages of linux boot process6 stages of linux boot process
6 stages of linux boot process
 
Packet Filtering Using Iptables
Packet Filtering Using IptablesPacket Filtering Using Iptables
Packet Filtering Using Iptables
 
Linux booting process!!
Linux booting process!!Linux booting process!!
Linux booting process!!
 
Iptables presentation
Iptables presentationIptables presentation
Iptables presentation
 
System and network administration network services
System and network administration network servicesSystem and network administration network services
System and network administration network services
 
Linux process management
Linux process managementLinux process management
Linux process management
 
Process management in linux
Process management in linuxProcess management in linux
Process management in linux
 
Linux File System
Linux File SystemLinux File System
Linux File System
 
Linux Memory Management
Linux Memory ManagementLinux Memory Management
Linux Memory Management
 
gcc and friends
gcc and friendsgcc and friends
gcc and friends
 
Embedded C
Embedded CEmbedded C
Embedded C
 
Signals
SignalsSignals
Signals
 
Timers
TimersTimers
Timers
 
System Calls
System CallsSystem Calls
System Calls
 
Synchronization
SynchronizationSynchronization
Synchronization
 
Threads
ThreadsThreads
Threads
 
Linux Network Management
Linux Network ManagementLinux Network Management
Linux Network Management
 
BeagleBone Black Bootloaders
BeagleBone Black BootloadersBeagleBone Black Bootloaders
BeagleBone Black Bootloaders
 

Ähnlich wie Processes

Ähnlich wie Processes (20)

Processes
ProcessesProcesses
Processes
 
Real Time Systems
Real Time SystemsReal Time Systems
Real Time Systems
 
3.5 create, monitor and kill processes v2
3.5 create, monitor and kill processes v23.5 create, monitor and kill processes v2
3.5 create, monitor and kill processes v2
 
Board Bringup
Board BringupBoard Bringup
Board Bringup
 
101 3.5 create, monitor and kill processes v2
101 3.5 create, monitor and kill processes v2101 3.5 create, monitor and kill processes v2
101 3.5 create, monitor and kill processes v2
 
101 1.3 runlevels , shutdown, and reboot
101 1.3 runlevels , shutdown, and reboot101 1.3 runlevels , shutdown, and reboot
101 1.3 runlevels , shutdown, and reboot
 
101 1.3 runlevels, shutdown, and reboot v2
101 1.3 runlevels, shutdown, and reboot v2101 1.3 runlevels, shutdown, and reboot v2
101 1.3 runlevels, shutdown, and reboot v2
 
1.3 runlevels, shutdown, and reboot v3
1.3 runlevels, shutdown, and reboot v31.3 runlevels, shutdown, and reboot v3
1.3 runlevels, shutdown, and reboot v3
 
Dan Norris: Exadata security
Dan Norris: Exadata securityDan Norris: Exadata security
Dan Norris: Exadata security
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Inter Process Communication
Inter Process CommunicationInter Process Communication
Inter Process Communication
 
Process management
Process managementProcess management
Process management
 
Kernel Timing Management
Kernel Timing ManagementKernel Timing Management
Kernel Timing Management
 
Module 3-cpu-scheduling
Module 3-cpu-schedulingModule 3-cpu-scheduling
Module 3-cpu-scheduling
 
Process
ProcessProcess
Process
 
Creating Real-Time Data Streaming powered by SQL on Kubernetes - Albert Lewan...
Creating Real-Time Data Streaming powered by SQL on Kubernetes - Albert Lewan...Creating Real-Time Data Streaming powered by SQL on Kubernetes - Albert Lewan...
Creating Real-Time Data Streaming powered by SQL on Kubernetes - Albert Lewan...
 
ch3.ppt
ch3.pptch3.ppt
ch3.ppt
 
Linux System Monitoring
Linux System Monitoring Linux System Monitoring
Linux System Monitoring
 
NTTドコモ様 導入事例 OpenStack Summit 2015 Tokyo 講演「After One year of OpenStack Cloud...
NTTドコモ様 導入事例 OpenStack Summit 2015 Tokyo 講演「After One year of OpenStack Cloud...NTTドコモ様 導入事例 OpenStack Summit 2015 Tokyo 講演「After One year of OpenStack Cloud...
NTTドコモ様 導入事例 OpenStack Summit 2015 Tokyo 講演「After One year of OpenStack Cloud...
 
Kernel Debugging & Profiling
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & Profiling
 

Mehr von Anil Kumar Pugalia (16)

File System Modules
File System ModulesFile System Modules
File System Modules
 
Kernel Debugging & Profiling
Kernel Debugging & ProfilingKernel Debugging & Profiling
Kernel Debugging & Profiling
 
System Calls
System CallsSystem Calls
System Calls
 
Introduction to Linux
Introduction to LinuxIntroduction to Linux
Introduction to Linux
 
Playing with R L C Circuits
Playing with R L C CircuitsPlaying with R L C Circuits
Playing with R L C Circuits
 
Audio Drivers
Audio DriversAudio Drivers
Audio Drivers
 
Video Drivers
Video DriversVideo Drivers
Video Drivers
 
Mobile Hacking using Linux Drivers
Mobile Hacking using Linux DriversMobile Hacking using Linux Drivers
Mobile Hacking using Linux Drivers
 
Shell Scripting
Shell ScriptingShell Scripting
Shell Scripting
 
References
ReferencesReferences
References
 
Functional Programming with LISP
Functional Programming with LISPFunctional Programming with LISP
Functional Programming with LISP
 
Power of vi
Power of viPower of vi
Power of vi
 
"make" system
"make" system"make" system
"make" system
 
Hardware Design for Software Hackers
Hardware Design for Software HackersHardware Design for Software Hackers
Hardware Design for Software Hackers
 
RPM Building
RPM BuildingRPM Building
RPM Building
 
Linux User Space Debugging & Profiling
Linux User Space Debugging & ProfilingLinux User Space Debugging & Profiling
Linux User Space Debugging & Profiling
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Processes

  • 1. Processes © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> All Rights Reserved.
  • 2. What to Expect? W's of a Process Processes in Linux Scheduling & Preemption Process States & Transitions Process Management Programming the Processes © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 2 All Rights Reserved.
  • 3. What is a Process? Program in Execution Executable/Program Loaded → Process Program is just the Code & initial Data part Additionally Value of Variables Stack Heap Program Counter Processor Registers And any other OS resources, needed by the Program make it a Process © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 3 All Rights Reserved.
  • 4. Why we need a Process? To do any task or job Moreover, to achieve multi-processing Really do multiple tasks at a time (in multi-processor systems), Or At least get a feel of doing multiple tasks at a time (on uni-processor systems) In turn needs Timesharing (on same processor) Scheduling Priority And for all these: Process Identifier (pid) © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 4 All Rights Reserved.
  • 5. Let's View Shell Local Processes: ps Console attached System Processes: ps a All System Processes: ps ax List many more details: Add l Observe uid, pid, ppid, priority, nice, status, tty, time Dynamic Process Status: top Try pid.c © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 5 All Rights Reserved.
  • 6. Processes in Linux © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 6 All Rights Reserved.
  • 7. Linux Schedulers Provide multi-tasking capabilities by Time Slicing Preemption Based on various task priorities Specified by its scheduling policies Understand the following execution instances Kernel Thread User Process User Thread © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 7 All Rights Reserved.
  • 8. Linux Schedulers ... Linux Basic Scheduling Normal (SCHED_OTHER) – Fairness Scheduling Other Advanced Scheduling supported Round Robin (SCHED_RR) FIFO (SCHED_FIFO) All Schedulers are O(1) © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 8 All Rights Reserved.
  • 9. Linux Kernel Preemption Levels None (PREEMPT_NONE) No forced preemption Overall throughput, on average, is good Voluntary (PREEMPT_VOLUNTARY) First stage of latency reduction Explicit preemption points are placed at strategic locations Standard (PREEMPT_DESKTOP) Preemption enabled everywhere except within critical sections Good for soft real-time applications, like audio, multimedia, … Kernel Parameter: preempt © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 9 All Rights Reserved.
  • 10. Kernel Preemption Visualization Time User Space System Call Interface Kernel Space Process A Process B © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 10 All Rights Reserved.
  • 11. Process Context Switch Time Save State Save State into PCB A into PCB B Reload State Reload State from PCB B from PCB A Interrupt or System Call Interrupt or System Call Process A Time Wasted in Context Switch Process B © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 11 All Rights Reserved.
  • 12. Generic Process State Diagram Time Run-Out New Terminated Admitted Dispatch Exit Ready Running Zombie Wakeup on Block on I/O or event I/O or completion wait event Blocked Stopped Uninterruptible or Interruptible Ready & Blocked states have Queues Additional States in Linux Defunct / Zombie (Terminated but not reaped by its parent) Stopped (By job control signal or because being traced) © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 12 All Rights Reserved.
  • 13. Linux Process States Process States as in Linux TASK_RUNNING (R) – ready or running TASK_INTERRUPTIBLE (S) – blocked (waiting for an event) TASK_UNINTERRUPTIBLE (D) – blocked (usually for I/O) TASK_ZOMBIE (Z) – terminated but not cleaned up by its parent TASK_STOPPED (T) – execution stopped Mutually exclusive Additional Information: Foreground (+), Threaded (l) © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 13 All Rights Reserved.
  • 14. Process Management in Linux Needs collation of all this information Address Space (Code, Variables, Stack, Heap) Processor State (PC, Registers, …) OS resources in use (File descriptors, ...) Scheduling Info, Priority, ... Preemption Info, Process State, ... for every Process Stored in structure of type 'task_struct' Maintained by Linux Kernel on a per process basis Also called the Process Descriptor / Process Control Block © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 14 All Rights Reserved.
  • 15. Process Control Block (PCB) Listing: <kernel_source>/include/linux/sched.h Some of its fields are volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */ void *stack; unsigned int flags; /* per process flags */ int prio, static_prio, normal_prio; unsigned int rt_priority; const struct sched_class *sched_class; unsigned int policy; struct mm_struct *mm, active_mm; / Pointers to Memory Regions, Descriptors */ pid_t pid, tgid; struct task_struct *real_parent; /* real parent process */ struct task_struct *parent; /* recipient of SIGCHLD, wait4() reports */ struct list_head children /* list of its children */, sibling; /* linkage in its parent's children list */ struct task_struct *group_leader; /* threadgroup leader */ struct list_head thread_group; struct fs_struct fs; /* file system info like current directory, … */ struct files_struct files; / file descriptors */ struct signal_struct signal; / signal handlers */ sigset_t blocked, real_blocked, saved_sigmask; struct sigpending pending; /* signals received */ © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 15 All Rights Reserved.
  • 16. Basic Process Management bg - Starts a suspended process in the background fg - Starts a suspended process in the foreground jobs - Lists the jobs running pidof - Find the process ID of a running program top - Display the processes that are using the most CPU resources © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 16 All Rights Reserved.
  • 17. Programming Linux Processes © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 17 All Rights Reserved.
  • 18. Process Creation From Shell By running a Command / Program / Script (Even by .) By 'exec' ing a Command / Program By Programming Using system() Simple but Inefficient Security risks Using fork() and exec() family function Comparatively complex Greater flexibility, speed, and security © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 18 All Rights Reserved.
  • 19. Using the exec family All exec* functions do the same thing Just in different ways Replaces current program by a new one And hence never returns, unless an error New program is immediately started Process remains the same Process Id, Parent Process Id Current directory, ... Open file descriptor tables, ... © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 19 All Rights Reserved.
  • 20. exec* function specifics exec*p (execvp, execlp) Accepts a program name Searches it in the current execution path Others must be given the full path execv* (execv, execvp, execve) Argument list should be a NULL-terminated array of pointers to strings execl* (execl, execlp, execle) Argument list uses the varargs mechanism exec*e (execve, execle) Accepts an additional argument: an array of environment variables It should be a NULL-terminated array of pointers to character strings Each character string should be of the form “VARIABLE=value” © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 20 All Rights Reserved.
  • 21. Cons of using fork Forked child process executes the copy of parent process' program And typically, a fork is followed by exec Replacing the copy by the new program What is the point of copying? Overhead!! What else? Is there any way out to prevent this? Yes. And it is ... © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 21 All Rights Reserved.
  • 22. Copy On Write (COW) Parent and Child shares the Address Space (ro) Data & other Resources are marked COW If written to, a duplicate is made and each process receives a unique copy Consequently, the duplication of resources occurs only when they are written to Avoids copy in cases of immediate exec fork()'s only overheads Duplication of the parent's page tables Creation of a unique PCB for the child © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 22 All Rights Reserved.
  • 23. Process Termination Parent & Children Processes terminate as usual Success Exit – Normal Success Error Exit – Normal Failure Fatal Exit – Signaled from Kernel Space for a Bug Kill Exit – Signaled by a Process But which one of them terminates, first? Does it matter? If it matters, parents can wait for their children Using wait family of system calls And can retrieve information about its child’s termination In fact, wait does the cleanup act for the exited child © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 23 All Rights Reserved.
  • 24. Using the wait family Four different system calls in the wait family wait(): Block until one of its child processes exits waitpid(): Wait for a specific child to exit/stop/resume wait3(): Along with, return resource usage information about the exiting/stopping/resuming child process wait4(): wait3() for a specific child or children All of these fill up a status code in an integer pointer argument about how the child process exited which can be decoded using ... © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 24 All Rights Reserved.
  • 25. wait status macros WIFEXITED, WEXITSTATUS WIFSIGNALED, WTERMSIG, WCOREDUMP WIFSTOPPED, WSTOPSIG WIFCONTINUED © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 25 All Rights Reserved.
  • 26. What if Parents Don't Wait? If Parent dies before the Children Children become Orphans And are adopted by the Init Process which then does the cleanup on their exit If a Child exits before the Parent That's a sad thing :) It will become a Ghost / Zombie Note that, even if the parent does a wait later It remains a Zombie till then © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 26 All Rights Reserved.
  • 27. Who Cleans Up a Zombie? Typically, again a Parent By doing a wait on it What if the parent exits without “wait”? Does it stay around in the system? Not really. It gets inherited by init which then cleans it up, right there © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 27 All Rights Reserved.
  • 28. What all have we learnt? W's of a Process? Process Scheduling & Preemption in Linux Process States & Transitions (Linux specific) Linux Process Management using PCB Programming Linux Processes Creation Techniques: fork, exec* & COW Termination & Waiting Techniques Orphans & Zombies © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 28 All Rights Reserved.
  • 29. Any Queries? © 2010 Anil Kumar Pugalia <email@sarika-pugs.com> 29 All Rights Reserved.