Sie sind auf Seite 1von 91

Chapter 2: Process Management

2. Process Management

Process Management
2.1 Process Concept 2.2 Process Control Block 2.3 Process operations : Create Kill suspend resume wakeup, 2.4 Interprocess Communication IPC types 2.5 IPC in Client-Server RTOS (Real Time Operating System)

2. Process Management

Process Concept
An operating system executes a variety of programs: Batch system jobs Time-shared systems user programs or tasks Textbook uses the terms job and process almost interchangeably Process a program in execution; A process includes:
Heap: Dynamic Storage allocation.

program counter :Next instruction to execute Stack: Temporary data( Function, Parameters, local variables) data sect (Global variable) Text: Process is more than program code which called as text 2. Process Management

Process in Memory

2. Process Management

Diagram of Process State

2. Process Management

Process State
As a process executes, it changes state New: The process is being created Ready: The process is waiting to be assigned to a processor Running: Instructions are being executed Waiting: The process is waiting for some event to occur Terminated: The process has finished execution At one time only one process can be runnning on a single processor

2. Process Management

The dynamic state of a process. Example process life cycle PROCESS

2. Process Management

Five-State Process Model

2. Process Management

Process Scheduling Queues


A. Job queue set of all processes in the system
B. Ready queue set of all processes residing in main memory, ready and waiting to execute C. Device queues set of processes waiting for an I/O device Processes migrate among the various queues

Ready Queue And Various I/O Device Queues

Representation of Process Scheduling

Schedulers
Long-term scheduler (or job scheduler) selects which processes should be brought into the ready queue
Short-term scheduler (or CPU scheduler) selects which process should be executed next and allocates CPU

Addition of Medium Term Scheduling

Addition of Medium Term Scheduling

Suspend

Execute

Wait for i/o

Frequency of calling Schedulers (Cont.)


Short-term scheduler is invoked very frequently (milliseconds) (must be fast) Long-term scheduler is invoked very infrequently (seconds, minutes) (may be slow) The long-term scheduler controls the degree of multiprogramming Processes can be described as either: I/O-bound process spends more time doing I/O than computations, many short CPU bursts CPU-bound process spends more time doing computations; few very long CPU bursts

Context Switch
When CPU switches to another process, the system must save the state of the old process and load the saved state for the new process via a context switch Context of a process represented in the PCB Context-switch time is overhead; the system does no useful work while switching Time dependent on hardware support

CPU Switch From Process to Process

Process Control Block


Identifier State Priority Program counter Memory pointers Context data I/O status information Accounting information

Figure 3.1 Simplified Process Control Block

2. Process Management

Process Control Block (PCB)


Information associated with each process Process state: New, Ready, Running waiting Program counter: Address of next instruction to execute CPU registers: accumulators, index registers, stack pointers and general purpose register plus condition code information. In case of interrupt Process start continuously correct from last state CPU scheduling information: Process priority pointers to scheduling queues and any other scheduling information Memory-management information: value of base and limit registers, page table or segment table. Accounting information:CPUused time, used time limit, account numbers, job or process numbers and so on. I/O status information: list of I/O devices allocated to the processes, a list of open files and so on.
Process Management 2. Process Management

Process Scheduling Queues


Job queue set of all processes in the system Ready queue set of all processes residing in main memory, ready and waiting to execute Device queues set of processes waiting for an I/O device Processes migrate among the various queues

2. Process Management

Ready Queue And Various I/O Device Queues

2. Process Management

Representation of Process Scheduling

2. Process Management

Process Operations
Process operations : Create(New) Kill(Terminate) Suspend(When blocked process swapped out from main memory) resume: Restart from previous wait state wakeup: Give signal that process has to make alive which is stopped previously(Notify and Notify all)

2. Process Management

Process Creation
Parent process create children processes, which, in turn create other processes, forming a tree of processes Generally, process identified and managed via a process identifier (pid) Resource sharing Parent and children share all resources Children share subset of parents resources Parent and child share no resources(directly taking from o.s.) Restricting a child process to a subset of the parentsresources

Execution Parent and children execute concurrently Parent waits until children terminate
2. Process Management

Aand flsflush: Memory tree of processes on a typical Solaris Pageout


Management Init: Parent process for all child process inetd and : Networking services such as t e l n e t and ftp; Dtlogin:login screen. Xsession :- Creating user session sdt_shel : command-line shell the C-shell or commandline Interface invokes various child processes, such as the I s and cat commands.

2. Process Management

Process Creation (Cont.)


Address space Child duplicate of parent Child has a program loaded into it UNIX examples fork system call creates new process exec system call used after a fork to replace the process memory space with a new program

2. Process Management

Process Creation

Fork(): Create new process parent/child Return value: Null to child and return pid of child to parent Exec () : system call loads a binary file into memory and starts its execution. Wait(): parent calls wait if it has not any operation and wait for child to terminate When the child process completes the parent process resumes from the call to wait (), e x i t () :completes using the system call.

2. Process Management

C Program Forking Separate Process


int main() { pid_t pid; /* fork another process */ pid = fork(); if (pid < 0) { /* error occurred */ fprintf(stderr, "Fork Failed"); exit(-1); } else if (pid == 0) { /* child process */ execlp("/bin/ls", "ls", NULL); } else { /* parent process */ /* parent will wait for the child to complete */ wait (NULL); printf ("Child Complete"); exit(0); } }

2. Process Management

Process Creation in Java

2. Process Management

Kill(Process Termination)
Process executes last statement and asks the operating system to delete it Unix: exit() TerminateProcess() in Win32 Output data from child to parent (via wait) Process resources are deallocated by operating system Only Parent may terminate execution of children processes (abort) Child has exceeded allocated resources Task assigned to child is no longer required If parent is exiting Some operating system do not allow child to continue if its parent terminates All children terminated - cascading termination(Defining on delete cascade)
2. Process Management

If parent terminates child how child will resume further: The wait () system call returns the process identifier of a terminated child Assigned as new parent to terminate process defined in the init process. Thus, the children still have a parent to collect their status and execution statistics

2. Process Management

Process Termination

O.S. Area Read only

2. Process Management

Process Termination
Cursoponding s/w not available

User Mode and kernel mode

Not responding End now

2. Process Management

Suspended Processes
Swap processes to disk to free up more memory Blocked or Wait state becomes suspend state when swapped to disk again Activating into ready state and go on, Two new states Blocked/Suspend Ready/Suspend

2. Process Management

Ready-suspended for those suspended process whose restarting condition has occurred. Blocked-suspended for those who must still wait instead.

2. Process Management

Reasons for Process Suspension

If resource unavailable

Alarm ,Burst time

2. Process Management

Suspending, Resuming, and Stopping Threads Display the time of day. If the user doesnt want a clock, then its thread can be suspended. Once suspended, restarting the thread is also a simple matter.

2. Process Management

Resume, Wakeup
wait( ) tells the calling thread to give up the monitor and go to sleep by giving sleeep() until some other process enters the same monitor and calls notify( ). notify( ) wakes up the first process that called wait( ) on the same object. notifyAll( ) wakes up all the processes that called wait( ) on the same object. Notifications affect only threads that have been waiting ahead of the notification The highest priority process will run first.

2. Process Management

The run( ) method contains a block that checks suspendFlag. If suspendFlag. is true, the wait( ) method is invoked to suspend the execution of the process. sets suspendFlag to false and invokes notify( ) to wake up the thread. Sleep() : Pausing Execution with Sleep() Thread.sleep causes the current thread to suspend execution for a specified period Suspend(): causes any execution to be suspend

2. Process Management

The notification methods :(Telling wait process to resume operation) notify(): and notifyAll() notifyAll(): wake up all waitin process notify() : picks one of the waiting process wakes up.

2. Process Management

Interprocess Communication(IPC)
Processes within a system may be independent or cooperating Cooperating process can affect or be affected by other processes, including sharing data Reasons for cooperating processes: Information sharing Computation speedup Modularity Convenience Cooperating processes need interprocess communication (IPC) Two models of IPC Shared Memory Message Passing System

2. Process Management

Cooperating Processes
Independent process cannot affect or be affected by the execution of another process. Cooperating process can affect or be affected by the execution of another process. Advantages of process cooperation Information sharing (share resource) Computation speed-up: Process divide into sub -processes(pipelining) Modularity(Problem in one sub process will not or less affect on the processes) Convenience( User can perform more than one operations open file, edit file, print file, Check grammar)

2. Process Management

Communications Models

A:Message Passing B: Shared Memory


2. Process Management

Shared Memory in Java

2. Process Management

Shared memory approach Producer-Consumer Problem


Allow producer and consumer processes to run concurrently Paradigm for cooperating processes, producer process produces information that is consumed by a consumer process The producer and consumer must be synchronized, unbounded-buffer places no practical limit on the size of the buffer bounded-buffer assumes that there is a fixed buffer size

2. Process Management

Bounded-Buffer Shared-Memory Solution


Shared data #define BUFFER_SIZE 10 typedef struct { ... } item; item buffer[BUFFER_SIZE]; int in = 0; int out = 0; Solution is correct, but can only use BUFFER_SIZE-1 elements

2. Process Management

Bounded-Buffer Producer
The buffer is full when ((in + 1) % BUFFER_SIZE) == out. while (true) { /* Produce an item */ while (((in = (in + 1) % BUFFER SIZE count) == out) ; /* do nothing -- no free buffers */ buffer[in] = item; in = (in + 1) % BUFFER SIZE; } Throuout: Out=0 First in=0 Last before in=8 Last in=9 which makes condition false so no add item in buffer

2. Process Management

Bounded Buffer Consumer


The buffer is empty when in == out; while (true) { while (in == out) ; // do nothing -- nothing to consume // remove an item from the buffer item = buffer[out]; out = (out + 1) % BUFFER SIZE; return item; } Throuout: Out=9 First out=0 Last before out=8 Last out=9 which makes condition false so no retreival of items. Management 2. Process

Interprocess Communication Message Passing


Without sharing address space provide Mechanism for processes to communicate and to synchronize their actions Message system processes communicate with each other without resorting to shared variables IPC facility provides two operations: send(message) message size fixed or variable receive(message) If P and Q wish to communicate, they need to: establish a communication link between them exchange messages via send/receive Implementation of communication link physical (e.g., shared memory, hardware bus) logical (e.g., logical properties)

Direct communication
Indirect Communication Synchronization Buffering
2. Process Management

Implementation Questions
How are links established?

Can a link be associated with more than two processes?


How many links can there be between every pair of communicating processes?

What is the capacity of a link?


Is the size of a message that the link can accommodate fixed or variable? Is a link unidirectional or bi-directional?

2. Process Management

Direct Communication
Symmetric direct communication: both the sender process and the receiver process must name the other to communicate. Processes must name each other explicitly: send (P, message) send a message to process P(P Is receiver) receive(Q, message) receive a message from process Q(Q is sender) ASymmetric direct communication: only the sender names the recipient; the recipient is not required to name the sender send(P, message)Send a message to process P. receive(id, message)-Receive a message from any process; the variable Properties of communication link Links are established automatically A link is associated with exactly one pair of communicating processes Between each pair there exists exactly one link The link may be unidirectional, but is usually bi-directional Disavantage: In general, any such hard-coding techniques, where identifiers must be explicitly stated, are less desirable than techniques involving indirection, as described next.(indirect communication)
2. Process Management

Indirect Communication
Instead of sending message to receiver send message to mailbox Messages are directed and received from mailboxes (also referred to as ports) Each mailbox has a unique id Processes can communicate only if they share a mailbox Properties of communication link Link established only if processes share a common mailbox A link may be associated with many processes Each pair of processes may share several communication links Link may be unidirectional or bi-directional

2. Process Management

Indirect Communication
Operations create a new mailbox send and receive messages through mailbox destroy a mailbox Primitives are defined as: send(A, message) send a message to mailbox A receive(A, message) receive a message from mailbox A

2. Process Management

Indirect Communication
Mailbox sharing P1, P2, and P3 share mailbox A P1, sends; P2 and P3 receive Who gets the message? Solutions Allow a link to be associated with at most two processes Allow only one process at a time to execute a receive operation Allow the system to select arbitrarily the receiver. Sender is notified who the receiver was.

2. Process Management

Mailbox ownership
Process: When a process that owns a mailbox terminates, the mailbox disappears Operating system: Mailbox is independent and not atttahced to partiular proces. Steps for message passing Initially, the owner is the only process that can receive messages through this mailbox. However, the ownership and receiving privilege may be passed to other processes through appropriate system calls. Of course, this provision could result in multiple receivers for each mailbox.

2. Process Management

Synchronization
Message passing may be either blocking or non-blocking

Blocking is considered synchronous Blocking send has the sender block until the message is received Blocking receive has the receiver block until a message is available
Non-blocking is considered asynchronous Non-blocking send has the sender send the message and continue Non-blocking receive has the receiver receive a valid message or null

2. Process Management

Buffering
Queue of messages attached to the link; implemented in one of three ways 1. Zero capacity 0 messages Sender must wait for receiver (rendezvous) 2. Bounded capacity finite length of n messages Sender must wait if link full 3. Unbounded capacity infinite length Sender never waits

Process Management

2. Process Management

Local Procedure Calls in Windows XP

Process Management
2. Process Management

Communications in Client-Server Systems


Sockets

Remote Procedure Calls


Remote Method Invocation (Java)

2. Process Management

Sockets
A socket is defined as an endpoint for communication

Concatenation of IP address and port


The socket 161.25.19.8:1625 refers to port 1625 on host 161.25.19.8 Communication consists between a pair of sockets

2. Process Management

Socket Communication

2. Process Management

2. Process Management

2. Process Management

2. Process Management

Socket Communication in Java

2. Process Management

Socket Communication in Java

2. Process Management

Remote Procedure Calls


Remote procedure call (RPC) abstracts procedure calls between processes on networked systems Stubs client-side proxy for the actual procedure on the server The client-side stub locates the server and marshalls the parameters

The server-side stub receives this message, unpacks the marshalled parameters, and peforms the procedure on the server

2. Process Management

Execution of RPC

2. Process Management

Remote Method Invocation (RMI) is a Java mechanism similar to RPCs RMI allows a Java program on one machine to invoke a method on a remote object

Remote Method Invocation

2. Process Management

2. Process Management

Matchmaker Requested Procedure

2. Process Management

Socket flow of events -- synchronous


Client
Get user input Decode user input(Marshaling) Create server message Send message to server Await server response Receive server message Decode reply Send output to user

Server
Await client message Receive client message Decode client message (Unmarshaling) Perform action Create client message Send to client

Method call on standalone object

Socket flow - asynchronous


Client1
User input (UI) Decode UI Create srvr msg Send srvr msg Await srvr reply Receive server message Decode reply Output to user

Server
Wait Receive client msg Decode client msg Perform action Create client message Send to client1 Send to client2

Client2
User input (UI) Decode UI Create srvr msg Send srvr msg Await srvr reply Receive server message Decode reply Output to user

RMI Example
x = remoteObj.MethodA(param);

Remote Object

Stub

Receiver

Remote Reference Layer Transport Layer

Stub is generated which then sends marshalled data to receiver

2. Process Management

RMI Example

x = remoteObj.MethodA(param);

Remote Object

Stub

Receiver

Remote Reference Layer Transport Layer

Receiver unmarshals, or decodes, parameters, locates object and calls the method specified by the stub

2. Process Management

RMI Example

x = remoteObj.MethodA(param);

Remote Object

Stub

Receiver

Remote Reference Layer Transport Layer

Receiver retrieves and marshals return value and sends back the encoded info to the stub

2. Process Management

Marshalling Parameters

2. Process Management

RMI Example

2. Process Management

RMI Example

2. Process Management

RMI Example

Chapter Index: 2 Process Management

2. Process Management

2. Process Management

Pipes
Pipes: Pipes are used to allow one or more processes to have information flow between

2. Process Management

Reading from pipes read() will return 0 (end of file) when the write end of the pipe is closed. if write end of the is still open and there is no data, read() will sleep until input become available. if a read() tries to get more data than is currently in pipe, read() will only contain the number of bytes actually read. Subsequent reads will sleep until more data is available. Writing to pipes When writing to a pipe: If read end of pipe is closes, a write() will fail and process will be sent SIGPIPE signal. Default SIGPIPE handler terminates.

2. Process Management

There are 2 types of pipes: unnamed pipes named pipes Unnamed/Anonymous pipes:They are created, used and destroyed within the life a set of processes. Each end of the pipe has its own file descriptor. One end is for reading and one end is for writing. When you are done with a pipe, it is closed like any other file. #include <unistd.h> int pipe(int fd[2]); Returns 2 file descriptors in the fd array. fd[0] is for read fd[1] write Returns 0 on successful creation of pipe, 1 otherwise. Each end of the pipe is closed individually using normal close() system call. Pipes are only available the process that creates the pipe and its descendants.

2. Process Management

Named pipes Named pipes are also called FIFOs (first in first out). They have names and exist as special files within a file system. (file type p) They exist until they are removed with rm or unlink() They can be used with unrelated process not just descendants of the pipe creator. i.e. accessing by process from outside of pipe Created with: mknod utility mknod() system call

2. Process Management

Reading from pipes When reading from a pipe: read() will return 0 (end of file) when the write end of the pipe is closed. if write end of the is still open and there is no data, read() will sleep until input become available. if a read() tries to get more data than is currently in pipe, read() will only contain the number of bytes actually read. Subsequent reads will sleep until more data is available. Writing to pipes When writing to a pipe: If read end of pipe is closes, a write() will fail and process will be sent SIGPIPE signal. Default SIGPIPE handler terminates.

2. Process Management

Trace of Processes

2. Process Management

Process States

Process Management
2. Process Management

2. Process Management

RTOS
Real-time operating system 1 Real-time operating system A real-time operating system (RTOS) is an operating system (OS) intended to serve real-time application requests. It must be able to process data as it comes in, typically without buffering delays. jitter.: amount of time it takes to accept and complete an application's task; A hard real-time operating system has less jitter than a soft real-time operating system. minimal interrupt latency and minimal thread switching latency; a real-time OS is valued more for how quickly or how predictably it can respond than for the amount of work it can perform in a given period of time.[3]

2. Process Management

2. Process Management

Das könnte Ihnen auch gefallen