Upload
andre-perdigao
View
220
Download
0
Embed Size (px)
Citation preview
8/3/2019 Slides 3 Processos
1/41
OperatingSystems
Lus Moura SilvaEmail: [email protected] de Eng. InformticaUniversidade de Coimbra
2011/2012
3. Processes
8/3/2019 Slides 3 Processos
2/41
2
Disclaimer
This slides and notes are heavily based on the companion material of[Silberschatz05].The original material can be found at: http://codex.cs.yale.edu/avi/os-book/os7/slide-dir/index.html
In some cases, material from [Stallings04] may also be used. Theoriginal material can be found at:
http://williamstallings.com/OS/OS5e.html
The respective copyrights belong to their owners.
8/3/2019 Slides 3 Processos
3/41
3
Whats a Process?
Program = Binary Image (Executable) Process = The living Image of a program running
It includes information like:- Program Counter- Allocated Memory / Address Space- Identifier, Owner, Security Attributes, etc.
MS Excel
(1 process)
MS Word(1 process)
8/3/2019 Slides 3 Processos
4/41
4
A process in Memory
My Process
AddressS
pace
0
4GB
8/3/2019 Slides 3 Processos
5/41
5
The Process Memory Image in Unix
text Where the code of the program goes Called .text section
data Where all variables are .data section global and static initialized variables to non-zero .bss section global and static non-initialized variables
(or initialized to 0)
heap Where all dynamically allocated memory is set e.g. as a result of malloc()
stack Where all automatic variables existVariables that are automatically created and destroyed in methods It grows down
8/3/2019 Slides 3 Processos
6/41
6
The Process Memory Image in Unix (2)
code
(shared) .text segment
initializedstatic data .data segment
non-initialized
static data .bss segment
(low address)
heap
stack
(high address)
.stack segment
Basically, these are the
ones that take spacein the executable
possible hole in
address space!
8/3/2019 Slides 3 Processos
7/41
7
Quiz: Where does everything go?
#defineKB(1024)
#defineMB(1024*1024)
charbuf[10*MB];charcommand[KB]="command?";intn_lines=0;intn_tries=20;inttotal;
intf(intn){intresult;staticintnumber_calls=0;++number_calls;result=n*n;
returnresult;}
intmain(){intx=5;printf("f(%d)=%d\n",x,f(x));
return0;}
.bss
.data
.bss
.data
.bss
.stack
.bss
.stack
What about the globals:
charbuf[10*MB] = {0};
charbuf[10*MB] = {1};
8/3/2019 Slides 3 Processos
8/41
8
Finding things out: size & objdump
8/3/2019 Slides 3 Processos
9/41
9
Process States
Notes:
Waiting is also known as Blocked Processes in the Ready and Blocked states do not consume CPU!
This is very important!
8/3/2019 Slides 3 Processos
10/41
10
Process Control Block (PCB)
One of the mostimportant data structures of the OS Represents a running process
The PCB includes: Process identifier Process state Program Counter CPU registers CPU scheduling information Memory-management informationAccounting information I/O status information List of open files
8/3/2019 Slides 3 Processos
11/41
11
Context Switch from Process to Process
8/3/2019 Slides 3 Processos
12/41
12
Execution of three processes over time
8/3/2019 Slides 3 Processos
13/41
13
Process Queues
So, where are all the PCBs saved? Processes migrate among the various 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
(also known as blocked queues)
8/3/2019 Slides 3 Processos
14/41
14
The Several Queues
DeviceQ
ueues
(i.e.workslikeaglobalblockedqueue)
8/3/2019 Slides 3 Processos
15/41
15
PCBs Flow Among Queues
Process SchedulerNote that events do not necessarily
correspond to I/O (more on this latter)
8/3/2019 Slides 3 Processos
16/41
16
Why Event Driven? A Human Perspective
8/3/2019 Slides 3 Processos
17/41
17
Whats the Best Scheduler?
It all depends
Server Multitasking OperatingSystems
User Multitasking OperatingSystems
Batch Operating Systems Real-time Operating Systems Embedded Operating Systems Multimedia Operating Systems
Even in Windows
8/3/2019 Slides 3 Processos
18/41
18
Suspended States
In some operating systems, additional states areintroduced for describing processes that have beenswappedto disk
8/3/2019 Slides 3 Processos
19/41
19
Two Suspended States
8/3/2019 Slides 3 Processos
20/41
20
Scheduling with Suspended States
In systems with suspended states it is common to have:A long term (or medium term) scheduler
Selects which processes should be brought from disk intothe ready queue
A short-term (or CPU) scheduler Selects which process should be executed next and allocates CPU
8/3/2019 Slides 3 Processos
21/41
21
Types of Processes
I/O Bound Spend more time doing I/O than computation
(Live mostly in the blocked queue)
CPU Bound Spend more time doing computation than I/O
(Live mostly in the ready queue)
For a good utilization of computer resources its importantto have a good mix of I/O bounded and CPU boundedprocesses: the long-term scheduler is responsible for this
8/3/2019 Slides 3 Processos
22/41
22
Process Creation
Parent process create children processes, which in turncreate other processes, forming a tree of processes
Process Tree
in Solaris
8/3/2019 Slides 3 Processos
23/41
23
Different Heritance Models
The way resources are shared between parent and childprocesses varies widely among operating systems
Resource sharing Parent and children share all resources Children share subset of parents resources Parent and children share no resources
Execution Parent and children execute concurrently Parent waits until children terminate Children terminate if parent terminates (cascading termination)
8/3/2019 Slides 3 Processos
24/41
24
Process Model in UNIX
Process creation in Unix isbased on spawning childprocesses which inherit all thecharacteristics of their fathers
Variables, program counter,open files, etc.
Spawning a process is doneusing the fork() system call
After forking, each process willbe executing having differentvariables and different state.
The Program Counter will bepointing to the next instruction
Changing a variable in the childprogram doesnt affect itsfather (and vice-versa)
a = f();fork();b = g();
State
a = f();
fork();b = g();
State
a = f();
fork();b = g();
State
ChildProcess
Original Process
OriginalProcess
8/3/2019 Slides 3 Processos
25/41
25
Forking in Unix
#include#include
#include#include
int main(){pid_t id;
id = fork();if (id == 0){
printf("[%d] I'm the son!\n", getpid());
printf("[%d] My parent is: %d\n", getpid(), getppid());}
else{
printf("[%d] I'm the father!\n", getpid());wait(NULL);
}return 0;
}
8/3/2019 Slides 3 Processos
26/41
26
Process Management
Each process has an unique identifier (PID). Each process has a father,which is also identified (PPID).
pid_t getpid(void); Returns the PID of the current process. pid_t getppid(void); Returns the PID of the parent process.
pid_t fork(void);Creates a new process which inherits all its fathers state. It returns 0 on the childprocess and the childs PID in the original process.
pid_t wait(int* status);Waits until a child process exits. The status of the child is set in status. (status is thereturn value of the process)
pid_t waitpid(pid_t who, int* status, int options);Same as wait() but allows to wait for a particular child. In options, by using
WNOHANG in options, allows for checking if a child has already exited withoutblocking. 0 in whomeans wait for any child.
8/3/2019 Slides 3 Processos
27/41
27
Copy-on-Write
Nowadays, the memory of a process is organized inpages of typically 4KB
After a fork(), the child process and the parent processshare the same pages
The operating system detects when a page is beingwritten either by the parent process or the child process.When that happens, a copy is made on demand, beforethe write is allowed to proceed.
This is called copy-on-write
Thus, changing a variable on a child process doesnt affectits parent and vice-versa
8/3/2019 Slides 3 Processos
28/41
28
Shared Address Space with the Kernel
For making system calls and traps fast, it is possible to jump directly tothe kernel handler routine without remapping any memory
The address space of each process is divided into two parts: One that is specific of that process One that corresponds to the kernel and is shared by all processes
How does it work? The user process does not have direct access to the kernel memory; it
cannot read nor write that part of the address space
Whenever a trap occurs, it enters in kernel mode and thus has access tothe already mapped memory
8/3/2019 Slides 3 Processos
29/41
29
Address Space in Linux (32-bit)
Kernel 0x00000000
Program Text
Program Data
Program Stack
Kernel
0x08048000
0xC0000000
0xFFFFFFFF
3GB
1GB
(Shared Libraries)0x40000000
8/3/2019 Slides 3 Processos
30/41
30
Process Termination in UNIX
A process is only truly eliminated by the operatingsystem when its father calls wait()/waitpid() on it. This allows the parent to check things like the exit code of its sons
Zombie Process: One that has died and its parent hasnot acknowledged its death (by calling wait()) Be careful with this if your are designing servers. They are eating
up resources!!
Orphan Process: One whose original parent has died. Inthat case, its parent becomes init (process 1).
8/3/2019 Slides 3 Processos
31/41
31
Lets generate some Zombies
#include#include
#include#include#include
void worker() {printf("[%d] Hi, I'm a worker process! Going to die...\n",
getpid());}
int main(){
for (int i=0; i
8/3/2019 Slides 3 Processos
32/41
32
Zombies (2)
8/3/2019 Slides 3 Processos
33/41
33
Lets see adoption by init
#include (...)
void worker(){ sleep(10);printf("[%d] Let's see who is my dady is: %d\n", getpid(),
getppid());}
int main()
{for (int i=0; i
8/3/2019 Slides 3 Processos
34/41
34
And the result is...
8/3/2019 Slides 3 Processos
35/41
35
8/3/2019 Slides 3 Processos
36/41
36
8/3/2019 Slides 3 Processos
37/41
37
How a process becomes another executable
How to execute code starting from an executable file
int execl(const char *path, const char *arg, ...);int execlp(const char *file, const char *arg, ...);int execle(const char *path, const char *arg, ..., char *const envp[]);int execv(const char *path, char *const argv[]);int execvp(const char *file, char *const argv[]);
exec family of functionsAllow to substitute the current process executable image by
another one. The substitution is complete!
The functions that have a p make use of the environment PATH;The functions that have a v make use of a pointer to an array onparameters; The functions that have an l have the parameterspassed separated by commas
Make sure that the first parameter is the name of the program!
8/3/2019 Slides 3 Processos
38/41
38
Example
Simple program that lists the files in the current directory
Note:A successful exec() never returns The code, the stack, the heap, its all replaced by the new
executable
Original Code ls code
ls code
exec()
8/3/2019 Slides 3 Processos
39/41
39
The corresponding code...
#include#include
#include#include
int main(){if (execlp("ls", "ls", "-a", NULL) == -1)
perror("Error executing ls: ");else
printf("This cannot happen!\n");
return 0;
}
char* ls_param[] = { "ls", "-a", NULL };
if (execvp(ls_param[0], ls_param) == -1)
perror("Error executing ls: ");
Using an arraycan be moreflexible...
8/3/2019 Slides 3 Processos
40/41
40
Reasons for Process Termination
Normal completion Time limit exceeded Memory unavailable Bounds violation Protection error
I/O failure Invalid instruction Operating system intervention (e.g. on deadlock) Parent terminates so child processes terminate Parent request
8/3/2019 Slides 3 Processos
41/41
41
Reference
[Silberschatz05]Chapter 3: Processes 3.1, 3.2, 3.3
[Robbins03]Chapter 2: Programs, Processes and ThreadsChapter 3: Processes in Unix