Operating Systems Lecture 07.pps
Operating Systems Lecture 07.pps
Systems
Lecture 7
Agenda for Today
Review of previous lecture
The wait and exec system calls and
sample code
Cooperating processes
Producer-consumer problem
pid = fork();
if(pid == -1) {
printf(“fork failed\n”);
exit(1);
}
June 5, 2020 © Copyright Virtual University of
Pakistan
Sample Code—fork
if(pid == 0) { /* Child */
printf(“Child here!\n”);
exit(0);
}
else { /* Parent */
wait(&status);
printf(“Well done kid!\n”);
exit(0);
}
}June 5, 2020 © Copyright Virtual University of
Pakistan
Semantics of fork
fork
#include <unistd.h>
int execlp (const char *file, const
char *arg0, ..., const char *argn,
(char *)0);
June 5, 2020 © Copyright Virtual University of
Pakistan
Sample Code—fork
and exec
#include <stdio.h>
void main()
{
int pid, status;
pid = fork();
if(pid == -1) {
printf(“fork failed\n”);
exit(1);
June 5, 2020 © Copyright Virtual University of
} Pakistan
Sample Code—fork
and exec
if(pid == 0) { /* Child */
if (execlp(“/bin/ls”, “ls”, NULL)< 0) {
printf(“exec failed\n”);
exit(1);
}
}
else { /* Parent */
wait(&status);
printf(“Well done kid!\n”);
exit(0);
}
}June 5, 2020 © Copyright Virtual University of
Pakistan
Semantics of fork
parent parent parent
P P P
fork
P P ls ls
exec
child child child
June 5, 2020 © Copyright Virtual University of
1 2 Pakistan 3
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
Empty Pool
Producer
Producer Consumer
Consumer
Full Pool
June 5, 2020 © Copyright Virtual University of
Pakistan
Bounded-Buffer 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
JuneBUFFER_SIZE-1
5, 2020 elements
© Copyright Virtual University of
Pakistan
Producer Process
item nextProduced;
while (1) {
while (((in + 1) % BUFFER_SIZE) == out)
; /* do nothing */
buffer[in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
}
while (1) {
while (in == out)
; /* do nothing */
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
}
Mailbox sharing
P1, P2, and P3 share mailbox A.
P1, sends; P2 and P3 receive.
Who gets the message?