chapter 3 processes. processes 2 process concept process scheduling operations on processes ...
TRANSCRIPT
Chapter 3
Processes
Processes
2
Process Concept Process SchedulingOperations on Processes Interprocess CommunicationExamples of IPC SystemsCommunication in Client-Server Systems
Objectives
3
To introduce the notion of a process -- a program in execution, which forms the basis of all computation
To describe the various features of processes, including scheduling, creation termination, and communication
To describe communication in client-server systems
Process Concept
4
An operating system executes a variety of programs: Batch system – jobs Time-shared systems – user programs or tasks
Process – a program in execution A program is a sequence of instructions saved
in disk, or loaded into memory (your executable file, a.out, …)
A process execute a program in sequential fashion
Jump instruction provided to support branch, loop. program counter points to next instruction to
be executed
Process in Memory
5
As a process executes, it changes state
Process State
6
new: being created running: Instructions are being executed waiting: waiting for some event to occur ready: waiting to be assigned to a processor terminated: has finished execution
Process Control Block (PCB)
7
Information associated with each process Process state Program counter:
address of next instruction to be executed CPU registers:
Contents of CPU registers CPU scheduling information
Process priority, … Memory-management information
Value of base and limit registers, page/segmentation tables (to be studied later)
Accounting information Amount of CPU time used …
I/O status information I/O device allocated, list of open files…
Process Control Block (PCB)
8
CPU Switch From Process to Process
9
P0, P1 are running concurrently, i.e., their executions are interleaved.
Context Switch
10
When CPU switches to another process, OS must save the state/context of old process (PCB) and load saved state for new process via a context switch
Context of a process represented in PCB Context-switch time is overhead; system does
no useful work while switching Time dependent on hardware support
Process Scheduling Queues
11
OS maintain multiple process queues for scheduling purpose:
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
Ready Queue And I/O Device Queues
12
Queuing Diagram: A Process
13
Rectangles: queueOvals: resources that serve the queue or events being waited for
Schedulers
14
Long-term scheduler (or job scheduler) – selects which processes should be brought into the ready queue controls the degree of multiprogramming invoked very infrequently (seconds, minutes) (may be slow)Goal: a good mix of I/O-bound and CPU-bound processes
=> efficient utilization of CPU and I/O– 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
Short-term scheduler (or CPU scheduler) – selects which process should be executed next and allocates CPU invoked very frequently (milliseconds) (must be fast)
Unix, Windows have no long-term scheduler
Medium Term Scheduling: swapping
15
Midterm-term scheduler: to remove process from memory (and
ready queue) and reduce degree of multiprogramming; and later reintroduce the process into memory to resume its execution
Process Creation
16
Parent process create children processes, which, in turn create other processes, forming a tree of processes process identified and managed via a process
identifier (pid)
A tree of processes on a typical Solaris
17
Child/Parent Process Relation
18
Child process needs resource (memory, files, I/O devices)
Resource sharing between parent & child: Parent and children share all resources Children share subset of parent’s resources Parent and child share no resources
Linux allows user to specify the degree of resource sharing
After parent creates a child process Parent continues to execute concurrently with the child Parent waits until some or all of its children terminated
Address space Child duplicate of parent: same program and data as
parent Child process loads a program into its address space
Process Creation: Unix example
19
fork system call creates new processexec system call used after a fork to replace the process’ memory space with a new program
To find out details of system calls, use man command, e.g., man 2 wait
C Program Forking Separate Process
20
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);
}}
fork()
21
Only way to create a process The child is a copy of the parent:
Inherits the parent's data, heap and stack. All file descriptors that are open in the parent are duplicated
in the child They also share the same file offset (Files opened after fork
are not shared). Often parent and child share text segment (code) Never know whether parent or child will start
executing first. Parent waits. Parent and child go their own way.
fork() may fail if it if num. of processes exceeds user limit or total system limit.
Two uses (reasons) for fork() Each can execute a different sections of code One process can execute a different program.
Load a program: exec() family of functions
22
Replace current process image with a new process image
execl(), execv(), execle(), execlp(), execvp(), and execve().
Replace current process with a new program and start execution. Brand new text, data, heap and stack segments.
Only execve() is a system call. Meaning of different letters:
l: needs a list of arguments. v: needs an argv[] vector (l and v are mutually exclusive). e: needs an envp[] array. p: needs the PATH variable to find the executable file.
Example
23
/* example argument list; program name is arg0 */ const char *ps_argv{} = {"ps", "-ax", 0}; /* trivial example environment */ const chare *ps_envp[] = {"PATH=/bin:/usr/bin",
"TERM=console", 0}; /* possible calls to exec */ execl("/bin/ps", "ps", "-as", 0); execlp("ps", "ps", "-ax", 0); /* assumes ps on path */execle("/bin/ps", "ps", "-as", 0, ps_envp); /* passes env */ execv("/bin/ps", ps_argv); /* passes args as vector */ execvp("ps", ps_argv); execve("ps", ps_argv, ps_envp);
Process Termination
24
• Process executes last statement and asks operating system to delete it (exit)– Output data from child to parent (via wait)– Process’ resources are deallocated by operating
system– Parent process must “wait” for child processes– Child processes terminated but not “waited for”
become “zombie” processes until the parent terminates (then these zombies will become children of init…) or waits for it.
– To make sure parent process obtain states info of the child
wait() system call (UNIX)
25
– wait, waitpid - wait for process to change stateSYNOPSIS
#include <sys/types.h> #include <sys/wait.h> pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options); int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int
options);
pid: which child processes to wait forstatus: if not NULL, wait(), waitpid() store status
info. in the integer it points to. (see manual for how to
26
#include <sys/wait.h> #include <stdlib.h> #include <unistd.h> #include <stdio.h> int main(int argc, char *argv[]) { pid_t cpid, w; int status; cpid = fork(); if (cpid == -1) { perror("fork");
exit(EXIT_FAILURE); } if (cpid == 0) { /* Code executed by child */ printf("Child PID is %ld\n", (long) getpid()); if (argc == 1) pause(); /* Wait for signals */ _exit(atoi(argv[1])); }
27
else { /* Code executed by parent */
do {
w = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
if (w == -1) {
perror("waitpid"); exit(EXIT_FAILURE);
}
if (WIFEXITED(status))
printf("exited, status=%d\n", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("killed by signal %d\n", WTERMSIG(status));
else if (WIFSTOPPED(status))
printf("stopped by signal %d\n", WSTOPSIG(status));
else if (WIFCONTINUED(status))
printf("continued\n");
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
exit(EXIT_SUCCESS);
} //end of else
} //end of main
Process Termination (2)
28
Parent may terminate execution of children processes (kill)– 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
Case study: shell
29
How shell works?1. Read a command line, parse it2. Create a child process to run the command3. Parent process waits for child process’s
termination4. Go back to 1.
Useful hints for using shell To run a program in background, i.e., shell not
waiting for its termination To allow a program to continue running even
shell exits: (standard output is saved to nohug.out)
nohup <program name> <program arguments> &
Linux Booting Procedure
Sirak Kaewjamnong
31
How computer startup? Booting is a bootstrapping process that starts
operating systems when the user turns on a computer system
A boot sequence: the sequence of operations computer performs
when it is switched on that load an operating system
32
Booting sequence1. Turn on2. CPU jump to address of BIOS (0xFFFF0)3. BIOS runs POST (Power-On Self Test)4. Find bootable devices5. Loads and execute boot sector from Master Boot
Record(MBR)6. Load OS
33
BIOS (Basic Input/Output System)
BIOS: software code run by a computer when first powered on Stored in predefined location in ROM (read-only memory)
The primary function of BIOS: Power-On Self Test (POST): diagnostic tests to check
memory/devices for their presence and for correct operation
BIOS on boardBIOS on screen
34
Bootable Disk Last step in BIOS:
Load boot record from the system’s boot disk (A: floppy disk as the default, …)
A boot disk contains a boot record, also called Master Boot Record (MBR) at its first sector MBR is a 512-byte sector, located in the first sector on
the disk (sector 1 of cylinder 0, head 0) After MBR is loaded into RAM, the BIOS yields control
to it.
35
MBR (Master Boot Record)
First 446 bytes: primary boot loader, which contains both executable code and error message text
Next sixty-four bytes: partition table, which contains a record for each of four partitions
Ends with two bytes (magic number) used for validation check of MBR
36
Extracting the MBR To see the contents of MBR, use this command: # dd if=/dev/hda of=mbr.bin bs=512 count=1 # od -xa mbr.bin**T he dd command, which needs to be run from root, reads the
first 512 bytes from /dev/hda (the first Integrated Drive Electr onics, or IDE drive) and writes them to the mbr.bin file.
** The od command prints the binary file in hex and ASCII formats.
37
Boot loader Boot loader could be more aptly called the kernel loader.
The task at this stage is to load the Linux kernel GRUB and LILO are the most popular Linux boot loader.
38
Other boot loader (Several OS) bootman GRUB LILO NTLDR XOSL BootX loadlin Gujin Boot Camp Syslinux GAG
39
GRUB: GRand Unified Bootloader GRUB is an operating system independant boot loader A multiboot software packet from GNU Flexible command line interface File system access Support multiple executable format Support diskless system Download OS from network Etc.
40
GRUB boot process
1. The BIOS finds a bootable device (hard disk) and transfers control to the master boot record
2. The MBR contains GRUB stage 1. Given the small size of the MBR, Stage 1 just load the next stage of GRUB
3. GRUB Stage 1.5 is located in the first 30 kilobytes of hard disk immediately following the MBR. Stage 1.5 loads Stage 2.
4. GRUB Stage 2 receives control, and displays to the user the GRUB boot menu (where the user can manually specify the boot parameters).
5. GRUB loads the user-selected (or default) kernel into memory and passes control on to the kernel.
41
Example GRUB config file
42
LILO: LInux LOader Not depend on a specific file system Can boot from harddisk and floppy Up to 16 different images Must change LILO when kernel image file or
config file is changed
43
Kernel image
The kernel is the central part in most computer operating systems because of its task, which is the management of the system's resources and the communication between hardware and software components
Kernel is always store on memory until computer is turned off
Kernel image is not an executable kernel, but a compress kernel image
zImage size less than 512 KB bzImage size greater than 512 KB
44
Init process
The first thing the kernel does Initialize internal data structures, process
manager Create the first process (initial process, 0) Initial process create process 1 to run init program
Init is the root/parent of all processes executing on Linux
The first processes that init starts is a script /etc/rc.d/rc.sysinit
Based on the appropriate run-level, scripts are executed to start various processes to run the system and make it functional
45
The Linux Init Processes The init process is identified by process id "1“
Init is responsible for starting system processes as defined
in the /etc/inittab file
Init typically will start multiple instances of "getty" which wait
s for console logins which spawn one's user shell process
Upon shutdown, init controls the sequence and processes for
shutdown
46
System p rocesses
Process ID Description
0 The Scheduler
1 The init process
2 kflushd
3 kupdate
4 kpiod
5 kswapd
6 mdrecoveryd
47
Inittab file
The inittab file describes which processes are started at bootup and during normal operation /etc/init.d/boot /etc/init.d/rc
The computer will be booted to the runlevel as defined by the initdefault directive in the /etc/inittab file id:5:initdefault:
48
Runlevels A runlevel is a software configuration of the
system which allows only a selected group of processes to exist
The processes spawned by init for each of these runlevels are defined in the /etc/inittab file
Init can be in one of eight runlevels: 0-6
49
Runlevels
Runlevel
Scripts Directory
(Red Hat/Fedor a Core)
State
0 0/etc/rc.d/rc .d/ ssssss/
1 1/etc/rc.d/rc .d/ ssssss ssss ssss2 2/etc/rc.d/rc .d/ sssssssss ssss ss sssssss ssssssss ssssssss3 3/etc/rc.d/rc .d/ ssss ssssss ssss sssssssss/.
4 4/etc/rc.d/rc .d/ - Reserved for local use. Also X windows (Slackware/BSD
)
5 5/etc/rc.d/rc .d/ - XDM X windows GUI mode (Redhat/System V)
6 6/etc/rc.d/rc .d/ Reboot
s or S Single user/Maintenance mode (Slackware)
M Multiuser mode (Slackware)
50
rc#.d files rc#.d files are the scripts for a given run level
that run during boot and shutdown The scripts are found in the directory
/etc/rc.d/rc#.d/ where the symbol # represents the run level
51
init.d Deamon is a background process init.d is a directory that admin can start/stop i
ndividual demons by changing on it /etc/rc.d/init.d / (Red Hat/Fedora ) /etc/init.d / (S.u.s.e .) /etc/init.d / (Debian )
52
Start/stop deamon Admin can issuing the command and either
the start, stop, status, restart or reload option i.e. to stop the web server:
cd /etc/rc.d/init.d/ (or /etc/init.d/ for S.u.s.e. and Debian) httpd stop
53
References http://en.wikipedia.org/ http://www-128.ibm.com/developerworks/linux/library/l-
linuxboot/ http://yolinux.com/TUTORIALS/LinuxTutorialInitProcess.html http://www.pycs.net/lateral/stories/23.html http://www.secguru.com/files/linux_file_structure http://www.comptechdoc.org/os/linux/commands/
linux_crfilest.html
Interprocess Communication
54
Interprocess Communication
55
Processes within a system may be independent or cooperating Cooperating process can affect or be affected by
other processes, including sharing data Cooperating processes need interprocess
communication (IPC) Two models of IPC
Shared memory Message passing
Communications Models
56
Cooperating Processes
57
• 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 – Computation speed-up– Modularity– Convenience
Producer-Consumer Problem
58
Paradigm for cooperating processes, producer process produces information that is consumed by a consumer process unbounded-buffer places no practical limit on the
size of the buffer bounded-buffer assumes that there is a fixed
buffer size
Bounded-Buffer – Shared-Memory Solution
59
Shared data#define BUFFER_SIZE 10typedef struct {
. . .} item;
item buffer[BUFFER_SIZE];int in = 0;int out = 0;
Solution is correct, but can only use BUFFER_SIZE-1 elements
Bounded-Buffer – Producer
60
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;
}
Bounded Buffer – Consumer
61
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;
}
Interprocess Communication – Message Passing
62
• 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)
Implementation Questions
63
• 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?
Direct Communication
64
Processes must name each other explicitly: send (P, message) – send a message to
process P receive(Q, message) – receive a message
from process Q 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
Indirect Communication
65
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
Indirect Communication
66
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 Areceive(A, message) – receive a message from mailbox A
Indirect Communication
67
• 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.
Synchronization
68
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
Buffering
69
Queue of messages attached to the link; implemented in one of three ways1. Zero capacity – 0 messages
Sender must wait for receiver (rendezvous)2. Bounded capacity – finite length of n
messagesSender must wait if link full
3. Unbounded capacity – infinite length Sender never waits
Examples of IPC Systems - POSIX
70
• POSIX Shared Memory– Process first creates shared memory segmentsegment id = shmget(IPC PRIVATE, size, S IRUSR | S IWUSR);
– Process wanting access to that shared memory must attach to it
shared memory = (char *) shmat(id, NULL, 0);– Now the process could write to the shared
memorysprintf(shared memory, "Writing to shared memory");
– When done a process can detach the shared memory from its address space
shmdt(shared memory);
Examples of IPC Systems – Windows XP
71
• Message-passing centric via local procedure call (LPC) facility– Only works between processes on the same system– Uses ports (like mailboxes) to establish and
maintain communication channels– Communication works as follows:
• The client opens a handle to the subsystem’s connection port object
• The client sends a connection request• The server creates two private communication ports and
returns the handle to one of them to the client• The client and server use the corresponding port handle
to send messages or callbacks and to listen for replies
Local Procedure Calls in Windows XP
72
Communications in Client-Server Systems
73
Sockets Remote Procedure Calls Remote Method Invocation (Java)
Sockets
74
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
Socket Communication
75
Remote Procedure Calls
76
• 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
Execution of RPC
77
Remote Method Invocation
78
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
Marshalling Parameters
79