03 process
TRANSCRIPT
-
7/29/2019 03 Process
1/60
Processes and ThreadsProcess Basics
1
Fall 2012
-
7/29/2019 03 Process
2/60
. .
Linker links .o files and other libraries together,. ., . .
Loader loads a binary executable into memory for.
memory
source object load
2
-
7/29/2019 03 Process
3/60
. .,executable), this program is loaded into memoryand the control is transferred to this ro ramsfirst instruction. Then, the program runs.
.
A process is more than a program, because arocess has a ro ram counter stack data
section, code section, etc (i.e., the runtime stuffs).
Moreover multi le rocesses ma be associatedwith one program (e.g., run the same program,say a.out, multiple times at the same time).
3
-
7/29/2019 03 Process
4/60
stack
max
local data
out of memory if these two
dynamic allocations with
data
eap
global data
program counter points
to an instruction
malloc()obtain space here
text/code program code0
4
-
7/29/2019 03 Process
5/60
any momen , a process can e n one o e ve
states: new, running, waiting, ready and terminated.
: The process is being created
: The process is waiting for some event
o occur e.g., wa ng or comp e on
: The process is waiting to be assigned toa processor.
: The rocess has finished
5execution.
-
7/29/2019 03 Process
6/60
converting to processrec a m resource
destroy process
admittedscheduler dispatch exit
waiting for CPUn errup
I/O or event
completion
6waiting for I/O or event
-
7/29/2019 03 Process
7/60
unique number, the
.
pointer process
state
Process info are stored ina table the
process ID
( ). These PCBs are chained
registers
into a number of lists.
For example, all processes
memory limits
in the ready state are inthe .
7
-
7/29/2019 03 Process
8/60
nce e num er o processes may e arger
than the number of available CPUs, the OSmus ma n a n max mum u za on.
To determine which process can do what,
processes are chained into a number ofscheduling queues.
For example, in addition to the ready queue,
each event may have its own scheduling queue(i.e., waiting queue).
8
-
7/29/2019 03 Process
9/60
e rea y queue, w c may e organ ze n o
several sub-queues, has all processes ready to run. The OS has a .
When a CPU is free, the CPU scheduler looks at
the ready queue, picks a process, and resumes it.
queue is referred to as .
because we
9
.
-
7/29/2019 03 Process
10/60
process includes process ID, process state, thevalues of CPU re isters the ro ram counterand other memory/file managementinformation (i.e., execution environment).
What is a context switch? After the CPUscheduler selects a process and before allocatesCPU to it, the CPU scheduler must
save the context of the currently running process,
put it back to the ready queue,
load the context of the selected process, and
10
go to t e save program counter.
-
7/29/2019 03 Process
11/60
o eratin s stem
running idle
save context into PCB0executionsuspended execution
resumed
load context from PCB1 runningidle
save context into PCB1
execution
load context from PCB0idle
execution
resumed
11
running
-
7/29/2019 03 Process
12/60
There are three commonl seen o erations:
Process Creation: Create a new process. The
uses fork() to create new processes.
execution of a process. Unix uses exit().
rocess o n: a or e comp e on o a
child process. Unix useswait()
.
fork(), exit() and ait() are system calls.
12
-
7/29/2019 03 Process
13/60
Before ou use rocesses include header files
sys/types.h and unistd.h.
unistd.h declares standard symbolic
#include #include
13
-
7/29/2019 03 Process
14/60
-
7/29/2019 03 Process
15/60
A negative value means the creation of a child
rocess was unsuccessful.
A zero means the process is a child.
,the caller. The ID is of type pid_t.
unct on getp () returns t e process o
the caller.Function getppid() returns the parents
process ID. If the calling process has no
15parent, getppid() returns 1.
-
7/29/2019 03 Process
16/60
parentmain(){
int a, b;pid_t pidfork();
pid = ;}
16
-
7/29/2019 03 Process
17/60
parent child
main(){
main(){
int a, b;pid_t pid;
int a, b;pid_t pid;
fork();
pid = ;
fork();
pid = ;}
}
17two independent and separate address spaces
-
7/29/2019 03 Process
18/60
#include #include
nc u e sys ypes.#include
{
pid_t MyID, ParentID;
char buf[100];
fork create a child rocessMyID = getpid(); // get my process IDParentID = getppid(); // get my parents process ID
for (i = 1; i
-
7/29/2019 03 Process
19/60
Processes 19087 and 19088 run concurrently
19004
Child : 1908819087
19088
Parent 19087s arent is 19004, the shell that executes fork-1
19
-
7/29/2019 03 Process
20/60
void child(void)
main(void)int i;
for (i=1; i 0int i;for (i=1; i
-
7/29/2019 03 Process
21/60
parent
{
pid = fork();
p =
if (pid == 0)child();
e separent();
void child(void){ }
21
vo paren vo
{ }
-
7/29/2019 03 Process
22/60
main(void) pid=123parent
main(void) pid = 0child
pid = fork();
pid = fork();
child();else
child();
elsein two different address spaces
parent();}
parent();}
void child(void)
void child(void)
void parent(void)
void parent(void)
22{ } { }
-
7/29/2019 03 Process
23/60
main(void) pid=123parent
main(void) pid = 0child
pid = fork();
pid = fork();
child();else
child();
else
parent();}
parent();}
void child(void)
void child(void)
void parent(void)
void parent(void)
23
{ } { }
-
7/29/2019 03 Process
24/60
#include // child exits firstvoid main(void)
pid_t pid;
=
force the child to print after the parent terminates
if (pid == 0) { // child here
printf(" From child %ld: my parent is %ld\n",et id et id
sleep(5);printf(" From child %ld 5 sec later: parent %ld\n",getpid(), getppid());
}else { // parent here
sleep(2);printf("From parent %ld: child %ld, parent %ld\n",
getpid(), pid, getppid());printf("From parent: done!\n");
24
}
}
-
7/29/2019 03 Process
25/60
Orphan children have a new
parent init, the Unix process
that s awns all rocesses
while parent is still running19004 parent terminated1
19291parent
1 is the ID ofinit,
the Unix process that
spawns all processes
19292child 19292child
2519004 is the shell process that executes 19291
-
7/29/2019 03 Process
26/60
#include // separate address spaces
this is e uivalent tovo d ma n(vo d){
pid_t pid;
pid = fork();if (pid == 0)
c ar ou ;int i = 10, j = 20;
i = 1000; j = 2000; // child changes valuessprintf(out, " From child: i=%d, j=%d\n", i, j);
}else { // parent here
slee 3sprintf(out, "From parent: i=%d, j=%d\n", i, j);write(1, out, strlen(out));
}
26
} force the parent to print after the child terminated
-
7/29/2019 03 Process
27/60
child changes i and j to 1000 and 2000from 10 and 20, respectively parents i and j are not affected
ecause paren an c ave
independent and separate address
space
27
-
7/29/2019 03 Process
28/60
exits or a
.
wait() takes a pointer to an integer variable
process. If no child process is running,wait()returns -1.
Some flags that indicate the completion status
of the child rocess are assed back with theinteger pointer.
28
-
7/29/2019 03 Process
29/60
wait(&status);
, n,processes:
or = ; < n; ++
wait(&status);
a or a spec c c process w ose sknown:
e p != wa t &status
;
29
-
7/29/2019 03 Process
30/60
{
pid_t pid, pid_child;int status;
p = or == c erechild();parent();
pid_child = wait(&status);}}
30
-
7/29/2019 03 Process
31/60
A newly created process may run a different programrather than that of the parent.
This is done using the exec system calls. We willonly discuss execvp():
int execvp(char *file, char *argv[]);
file is a char array that contains the name of anexecutable file
argv[] s t e argument passe to your ma n program
argv[0] is a pointer to a string that contains the
argv[1], argv[2], are pointers to strings thatcontain the ar uments
31
-
7/29/2019 03 Process
32/60
< >argv[]
#include
c p \0
\0
{char prog[] = { cp };
t h i s . c \0
c ar n = s.c ;
char out[] = { that.c };char *argv[4];
t h a t . c \0
int status;pid_t pid;
argv[0] = prog; argv[1] = in;argv[2] = out; argv[3] = \0;
32
see nex s e
-
7/29/2019 03 Process
33/60
p = or printf(fork() failed\n);
exit(1); \0
argv[]
}else if (pid == 0)
if (execvp(prog, argv) < 0) {
c p \0
printf(execvp() failed\n);exit(1);
}
t s . c 0
elsewait(&status);
.
execute program cp
33
-
7/29/2019 03 Process
34/60
void parse(char *line, char **argv){
* = ' 'while (*line == ' ' || *line == '\t' || *line == '\n')
*line++ = '\0'; // replace white spaces with 0*ar v++ = line save the ar ument ositionwhile (*line != '\0' && *line ! =' '
&& *line!='\t' && *line != '\n')line++; // skip the argument until ...
}*argv = '\0'; // mark the end of argument list
}
c p t h i s . c t h a t . c \0
line[]
c p \0 t h i s . c \0 t h a t . c \0
line[]
34\0argv[]
-
7/29/2019 03 Process
35/60
void execute(char **argv){
p _ p ;int status;
if ((pid = fork()) < 0) { // fork a child process
exit(1);}
if (execvp(*argv, argv) < 0) { // execute the commandprintf("*** ERROR: exec failed\n");exit 1
}}
else { // for the parent:while (wait(&status) != pid) // wait for completion
;}
35
}
-
7/29/2019 03 Process
36/60
void main(void)
char line[1024]; // the input linechar *argv[64]; // the command line argument
while (1) { // repeat until done ....printf("Shell -> "); // display a promptets(line); // read in the command lineprintf("\n");parse(line, argv); // parse the lineif (strcmp(argv[0], "exit") == 0) // is it an "exit"?
exit(0); // exit if it isexecute(argv); // otherwise, execute the command
}}
Dont for et that ets is risk ! Use f ets instead.
36
-
7/29/2019 03 Process
37/60
The parent and child processes are run inn epen ent an separate a ress spaces.
processes, parent and children included, do not
s are anyt ng.
A shared memory segment is a piece of
memory that can be allocated and attached to
an address space. Processes that have thismemory segment attached will have access to it.
But race conditions can occur!
37
-
7/29/2019 03 Process
38/60
-
7/29/2019 03 Process
39/60
o use s are memory, nc u e e o ow ng:
#include #include
#include
A key is a value of type key_t. There arethree wa s to enerate a ke :
Do it yourself
Ask the system to provide a private key.
39
-
7/29/2019 03 Process
40/60
Do it yourself:
_
SomeKey = 1234;
o
key_t = ftok(char *path, int ID);path s a pat name e.g., ./
ID is an integer (e.g., a)
o ey_
SomeKey = ftok(./, x);
.your key, they can access your shared memory.
40
IPC_PRIVATE.
-
7/29/2019 03 Process
41/60
Include the following:
nc u e
#include
.
Use shmget() to request a shared memory:_ =
key_t key, /* identity key */* * ,
int flag); /* creation or use */
.The flag, for our purpose, is either 0666 (rw)
41
_ . , _ .
-
7/29/2019 03 Process
42/60
The following creates a shared memory of size
IPC_PRIVATE. This is a creation
IPC CREAT with read and write ermission_(0666).
struct Data { int a; double b; char x; };int ShmID;
ShmID = shmget(IPC_PRIVATE, /* private key */
sizeof(struct Data), /* size */
42
IPC_CREAT | 0666);/* cr & rw */
-
7/29/2019 03 Process
43/60
-
7/29/2019 03 Process
44/60
en as ng or a s are memory, e process
that creates it uses IPC_CREAT | 0666 andprocesses a access a crea e one use .
If the return value is negative (Unix
convention), the request was unsuccessful, andno shared memory is allocated.
44
-
7/29/2019 03 Process
45/60
shmget(,IPC_CREAT|0666);
shared memory
45
Shared memory is allocated; but, is not part of the address space
-
7/29/2019 03 Process
46/60
Use shmat() to attach an existing sharedmemory to an address space:
shm_ptr = shmat(int shm_id, /* ID from shmget() */
char *ptr, /* use NULL here */
int flag); /* use 0 here */
shm_id is the shared memory ID returned byshmget().
Use NULL and 0 for the second and thirdarguments, respectively.
shmat() returns a void pointer to the memory.
46
If unsuccessful, it returns a negative integer.
-
7/29/2019 03 Process
47/60
struct Data { int a; double b; char x;};int ShmID;key_t Key;
s ruc a a p;
=
ShmID = shmget(Key, sizeof(struct Data),IPC_CREAT | 0666);
p = (struct Data *) shmat(ShmID, NULL, 0);if ((int) p < 0) {
}->a = 1 ->b = 5.0 ->x = .
47
-
7/29/2019 03 Process
48/60
shmget(,IPC_CREAT|0666); shmget(,0666);ptr = shmat(); ptr = shmat();
shared memory
48
ow processes can access e s are memory
-
7/29/2019 03 Process
49/60
To detach a shared memory, use
shmdt(shm_ptr);
_ After a shared memory is detached, it is still
. .
To remove a shared memory, use
shmctl(shm_ID, IPC_RMID, NULL);
shm_ID is the shared memor ID returned bshmget(). After a shared memory is removed,it no lon er exists.
49
-
7/29/2019 03 Process
50/60
void main(int argc, char *argv[]){int ShmID, *ShmPTR, status;
id t id;_
ShmID = shmget(IPC_PRIVATE,4*sizeof(int),IPC_CREAT|0666);= *
ShmPTR[0] = getpid(); ShmPTR[1] = atoi(argv[1]);ShmPTR[2] = atoi(argv[2]); ShmPTR[3] = atoi(argv[3]); = ==Child(ShmPTR);exit(0);
parents process ID here}wait(&status);shmdt((void *) ShmPTR); shmctl(ShmID, IPC_RMID, NULL);
50
exit(0);
}
-
7/29/2019 03 Process
51/60
void Child(int SharedMem[])
printf(%d %d %d %d\n, SharedMem[0],
SharedMem[1], SharedMem[2], SharedMem[3]);}
shm et() shmat()
51
-
7/29/2019 03 Process
52/60
Define the structure of a shared memory
e ne _ -
#define FILLED (0)#define TAKEN (1)
struct Memory {
int status;int data[4];};
52
-
7/29/2019 03 Process
53/60
Prepare for a shared memoryThe Server
int main(int argc, char *argv[]){
_
int ShmID, i;struct Memory *ShmPTR;
ShmKEY = ftok(./, x);ShmID = shmget(ShmKEY, sizeof(struct Memory),
IPC_CREAT 0666);ShmPTR = (struct Memory *) shmat(ShmID, NULL, 0);
53
-
7/29/2019 03 Process
54/60
shared memory not ready
ShmPTR->status = NOT_READY;
ShmPTR->data[0] = et id();
filling in data
for (i = 1; i < 4; i++)ShmPTR->data[i] = atoi(argv[i]);
ShmPTR->status = FILLED;while (ShmPTR->status != TAKEN)
printf(My buddy is %ld\n, ShmPTR->data[0]);shmdt((void *) ShmPTR);
shmctl(ShmID, IPC_RMID, NULL);exit(0);
} wait until the data is taken
54detach and remove shared memory
-
7/29/2019 03 Process
55/60
int main(void)
key_t ShmKEY;
int ShmID; prepare for shared memory
struct Memory *ShmPTR;
ShmKEY=ftok(./, x);ShmID = shmget(ShmKEY, sizeof(struct Memory), 0666);
ShmPTR = (struct Memory *) shmat(ShmID, NULL, 0);hile ShmPTR->status != FILLED;
printf(%d %d %d %d\n, ShmPTR->data[0],
- - -, ,ShmPTR->data[0] = getpid();ShmPTR->status = TAKEN;
55
s m vo m ;
exit(0);}
-
7/29/2019 03 Process
56/60
The server must run first to prepare a
.Run the server in one window, and run the
client in another a little later.
Or, run the server as a background process.Then, run the client in the foreground later:
server 1 3 5 &client
Th s vers on uses busy wa t ng.
One may use Unix semaphores for mutual
56
.
-
7/29/2019 03 Process
57/60
you o no remove your s are memory
segments (e.g., program crashes before the
execu on o s mc , ey w e n e
system forever. This will degrade the system
per ormance.
Use the ipcs command to check if you haveshared memory segments left in the system.
Use the ipcrmcommand to remove your
shared memory segments.
57
-
7/29/2019 03 Process
58/60
-
7/29/2019 03 Process
59/60
-
7/29/2019 03 Process
60/60
e n
60