0% found this document useful (0 votes)
55 views33 pages

04 Processes Slides

Uploaded by

Waqas Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views33 pages

04 Processes Slides

Uploaded by

Waqas Ahmed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Operating Systems

04. Processes

Paul Krzyzanowski

Rutgers University

Spring 2015

February 2, 2015 © 2014-2015 Paul Krzyzanowski 1


Key concepts from last week

February 2, 2015 © 2014-2015 Paul Krzyzanowski 2


Boot Loader
• Multi-stage boot loader
• Old Intel PC architecture (still used!)
– BIOS
– Master Boot Record – located at block 0
– Volume Boot Record
– OS Loader
• Current PC architecture (2005+)
– UEFI – knows how to read one or more file systems
– Loads OS loader from a boot partition
• Embedded systems (e.g., ARM-based devices)
– Custom boot firmware on the processor chip

February 2, 2015 © 2014-2015 Paul Krzyzanowski 3


Operating System vs. Kernel
• Kernel
– “nucleus” of the OS; main component
– Provides abstraction layer to underlying hardware
– Manages system resources (CPU, file systems, memory, network)
– Enforces policies
• Rest of the OS
– Utility software, windowing system, print spoolers, etc.
• Kernel mode vs. user mode execution
– Flag in the CPU
– Kernel mode = can execute privileged instructions

February 2, 2015 © 2014-2015 Paul Krzyzanowski 4


Mode switch
• Transition from user to kernel mode (and back)
• Includes a change in flow
– Cannot just execute user’s instructions in kernel mode!
– Well-defined addresses set up at initialization
• Change mode via:
– Hardware interrupt
– Software trap (or syscall)
– Violations (exceptions): illegal instruction or memory reference

February 2, 2015 © 2014-2015 Paul Krzyzanowski 5


Context Switch
• Mode switch + change executing process

February 2, 2015 © 2014-2015 Paul Krzyzanowski 6


Timer interrupts
• Crucial for:
– Preempting a running process to give someone else a chance
(force a context switch)
• Including ability to kill the process
– Giving the OS a chance to poll hardware
– OS bookkeeping

February 2, 2015 © 2014-2015 Paul Krzyzanowski 7


Timer interrupts
• Windows
– Typically 64 or 100 interrupts per second
– Apps can raise this to 1024 interrupts per second
• Linux
– Interrupts from Programmable Interval Timer (PIT) or HPET (High
Precision Event Timer) and from a local APIC timer (one per CPU)
– all at the same rate
– Interrupt frequency varies per kernel and configuration
• Linux 2.4: 100 Hz
• Linux 2.6.0 – 2.6.13: 1000 Hz
• Linux 2.6.14+ : 250 Hz
• Linux 2.6.18 and beyond: aperiodic – tickless kernel
– PIT not used for periodic interrupts; just APIC timer interrupts
– Kernel determines when the next interrupt should take place

February 2, 2015 © 2014-2015 Paul Krzyzanowski 8


Processes

February 2, 2015 © 2014-2015 Paul Krzyzanowski 9


Process
• Program: code & static data stored in a file
stack
• Process: a running program
– Each process has its own address space
(we’ll look at this later)
– Memory map
• Text: compiled program
• Data: initialized static data
• BSS: uninitialized static data
• Heap: dynamically allocated memory
• Stack: call stack heap
– System state: open files, pending signals
– Processor statte: data+bss
Text (code) & initialized
• Program counter data come from the
stored program text
• CPU registers

February 2, 2015 © 2014-2015 Paul Krzyzanowski 10


Growing memory

stack

Stack expanded automatically

Data area (heap) can grow via a system call


that requests more memory heap

data+bss

text

February 2, 2015 © 2014-2015 Paul Krzyzanowski 11


Contexts
• Entering the kernel
– Hardware interrupts
• Asynchronous events (I/O, clock, etc.)
• Do not relate to the context of the current process [kernel context]
– Violations
• Are related to the context of the current process [process context]
• Examples: illegal memory access, divide by zero, illegal instruction
– Software initiated traps (software interrupts)
• System call from the current process [process context]

• The view of memory does not change on a trap


– The currently executing process’ address space is active on a trap
• Saving state
– Kernel stack switched in upon entering kernel mode
– Kernel must save machine state before servicing event
• Registers, flags (program status word), program counter, …

February 2, 2015 © 2014-2015 Paul Krzyzanowski 12


Processes in a Multitasking Environment
• Multiple concurrent processes
– Each process has a unique identifier: Process ID (PID)

• Asynchronous events (interrupts) may occur


– The OS will have to take care of them
• Processes may request operations that take a long time
– They have nothing to do now but wait
• Goal: always have some process running
– Context saving/switching
• Processes may be suspended and resumed
• Need to save all state about a process so we can restore it

February 2, 2015 © 2014-2015 Paul Krzyzanowski 13


Process states

Running

Preemption I/O

Scheduler

Ready Blocked
I/O complete

February 2, 2015 © 2014-2015 Paul Krzyzanowski 14


Keeping track of processes
• Process list stores a Process Control Block (PCB) per process
• A Process Control Block contains:
– Process ID
– Machine state (registers, program counter, stack pointer)
– Parent & list of children
– Process state (ready, running, blocked)
– Memory map
– Open file descriptors
– Owner (user ID) – determine access & signaling privileges
– Event descriptor if the process is blocked
– Signals that have not yet been handled
– Policy items: Scheduling parameters, memory limits
– Timers for accounting (time & resource utilization)
– (Process group)

February 2, 2015 © 2014-2015 Paul Krzyzanowski 15


System calls
Entry Return from system call or
Trap to system call handler interrupt
– Save CPU state – Check for signals to the process
• Call the appropriate handler if signal is not
– Verify parameters are in a valid
ignored
address
– Check if another process should run
– Copy them to kernel address space
• Context switch to let the other process
– Call the function that implements the run
system call • Put our process on a ready list
• If the function cannot be satisfied
– Calculate time spent in the call for
immediately then
profiling/accounting
– Put process on a blocked list
– Context switch to let another ready – Restore user process state
process run
– Return from interrupt

February 2, 2015 © 2014-2015 Paul Krzyzanowski 16


Processes in Linux
• The OS creates one task on startup:
init: the parent of all tasks
launchd: replacement for init on Mac OS X and FreeBSD
• Process state stored in struct task_struct
– Defined in linux/sched.h
• Stored as a circular, doubly linked list

struct task_struct init_task; /* static definition of the first task*/

init_task task 2 task 3 task N

February 2, 2015 © 2014-2015 Paul Krzyzanowski 17


Processes in Linux
Iterating through processes
for (p = &init_task; ((p = next_task(p)) != &init_task; )
{
/* whatever */
}

The current process on the current CPU is obtained from the


macro c u r r e n t
current->state = TASK_STOPPED;

init_task task 2 task 3 task N

February 2, 2015 © 2014-2015 Paul Krzyzanowski 18


Processes on Ready & Blocked Queues
The list of ready processes is
called a run queue

Ready PCB 12 PCB 31 PCB 8

Disk 1 PCB 15 PCB 43 PCB 95

Disk 2

Network 1 PCB 7 PCB 101 PCB 64

Network 2 PCB 118 PCB 39

Blocked

February 2, 2015 © 2014-2015 Paul Krzyzanowski 19


Process States: a bit more detail
User
Running [Terminated]

Sys call
or Interrupt
Return Zombie

exit
Kernel Linger until a
Created Running parent process
returns from wait()
[allows a parent to
Preempt get the exit code]
Sleep
Reschedule

I/O complete
Ready Blocked
Wake up

interrupt context: not part of any process state


February 2, 2015 © 2014-2015 Paul Krzyzanowski 20
Creating a process under POSIX
fork system call
– Clones a process into two processes
• New context is created: duplicate of parent process
– fork returns 0 to the child and the process ID to the parent
• Both processes execute at the point of the return from the fork

February 2, 2015 © 2014-2015 Paul Krzyzanowski 21


What happens in fork?
• Check for available resources
• Allocate a new PCB
• Assign a unique PID
• Check process limits for user
• Set child state to “created”
• Copy data from parent PCB slot to child
• Increment counts on current directory & open files
• Copy parent context in memory (or set copy on write)
• Set child state to “ready to run”
• Wait for the scheduler to run the process
February 2, 2015 © 2014-2015 Paul Krzyzanowski 22
Fork Example

#include <stdio.h>

main(int argc, char **argv) {


int pid;

switch (pid=fork()) {
case 0: printf("I'm the child\n");
break;
default:
printf("I'm the parent of %d\n", pid);
break;
case -1:
perror("fork");
}
}

February 2, 2015 © 2014-2015 Paul Krzyzanowski 23


Running other programs
execve: replace the current process image with a new one
– See also execl, execle, execlp, execvp, execvP
(these are just variation wrappers that take different parameters)
• New program inherits:
– Processes group ID
– Open files
– Access groups
– Working directory
– Root directory
– Resource usages & limits
– Timers
– File mode mask
– Signal mask

February 2, 2015 © 2014-2015 Paul Krzyzanowski 24


Exec Example
Execute the command: ls -al /

#include <unistd.h>

main(int argc, char **argv) {


char *av[] = { "ls", "-al", "/", 0 };

execvp("ls", av);
perror("ls failed to run!");
exit(1);
}
The perror and exit functions
run ONLY if execvp failed –
otherwise the new program
overlays the current process

February 2, 2015 © 2014-2015 Paul Krzyzanowski 25


Fork & exec combined
• UNIX runs new programs via fork followed by exec
– Step 1. Clone
– Step 2. Replace

• Windows approach
– CreateProcess system call to create a new child process
– Specify the executable file and parameters
– Identify startup properties (windows size, input/output handles)
– Specify directory, environment, and whether open files are inherited

February 2, 2015 © 2014-2015 Paul Krzyzanowski 26


Fork & exec combined
• UNIX creates processes via fork followed by exec
– Step 1. Clone
– Step 2. Replace

BOOL WINAPI CreateProcess (


• Windows approach_In_opt_ LPCTSTR lpApplicationName,
_Inout_opt_ LPTSTR lpCommandLine,
– CreateProcess
_In_opt_ system call to create a lpProcessAttributes,
LPSECURITY_ATTRIBUTES new child process
_In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes,
– Specify the
_In_ executable file and parameters
BOOL bInheritHandles,
_In_ DWORD dwCreationFlags,
– Identify startup
_In_opt_ properties (windows size, input/output handles)
LPVOID lpEnvironment,
– _In_opt_
Specify directory, LPCTSTR lpCurrentDirectory,
environment, and whether open files are inherited
_In_ LPSTARTUPINFO lpStartupInfo,
_Out_ LPPROCESS_INFORMATION lpProcessInformation
);

February 2, 2015 © 2014-2015 Paul Krzyzanowski 27


Exiting a process
exit system call

#include <stdlib.h>

main(int argc, char **argv) {


exit(0);
}

Exit status that can be


returned to the parent

February 2, 2015 © 2014-2015 Paul Krzyzanowski 28


exit: what happens?
• Ignore all signals
• If the process is associated with a controlling terminal
– Send a hang-up signal to all members of the process group
– reset process group for all members to 0
• close all open files
• release current directory
• release current changed root, if any
• free memory associated with the process
• write an accounting record (if accounting)
• make the process state zombie
• assign the parent process ID of any children to be 1 (init)
• send a “death of child” signal to parent process (SIGCHLD)
• context switch (we have to!)

February 2, 2015 © 2014-2015 Paul Krzyzanowski 29


Wait for a child process to die
wait system call
• Suspend execution until a child process exits
• wait returns the exit status of that child.

int pid, my_pid, status;

switch (my_pid=fork()) {
case 0: /* do child stuff */ break;
case -1: /* do error stuff */ break;

default: /* wait for child to exit */


pid=wait(&status);
if (pid != -1)
printf("got exit of %d\n", WEXITSTATUS(status));
break;
}

February 2, 2015 © 2014-2015 Paul Krzyzanowski 30


Parent & child processes

parent fork wait

child execv exit

February 2, 2015 © 2014-2015 Paul Krzyzanowski 31


Signals
• Inform processes of asynchronous events
– Processes may specify signal handlers
• Processes can poke each other
(if they are owned by the same user)

• Sending a signal:
– kill (int pid, int signal_number)
• Detecting a signal:
– signal (signal_number, function)

February 2, 2015 © 2014-2015 Paul Krzyzanowski 32


The End

February 2, 2015 © 2014-2015 Paul Krzyzanowski 33

You might also like