Fill in the two missing blocks so that the entire program prints 0-29 in order.
ID: 3664800 • Letter: F
Question
Fill in the two missing blocks so that the entire program prints 0-29 in order. There are two challenges here:
1. Keeping the process count rational. Read the existing code carefully, and be sure you understand what it would do w/o any added statements on your part. For instance, you should be thinking "OMG! That's a lot of processes." Why?
2. Once you have #1 in hand, then you'll probably find that getting the right order of output is a challenge. That little sleep(2) statement causes problems. Don't try to eliminate it. Instead, use process control concepts from the lecture to get the printfsin the right order in spite of the sleep call.
Hints
You may find it useful to draw out the parent/child relationships between the processes created.
CODE
#include
#include
#include
#include
#include
#define FORKS 30
int main() {
int i, pid;
for (i = 0; i < FORKS; i++) {
if (!(pid = fork())) {
if (!(i % 10))
sleep(2);
printf("%d ", i);
//enter code here
}
else {
//code here
}
}
return 0;
}
Explanation / Answer
sleep(2);
printf("%d ", i);
r=read(fd,buffer,10);
write(STDOUT_FILENO,"child reads",14);
write(STDOUT_FILENO,buffer,10);
write(STDOUT_FILENO," ",1);
exit(0);
}
else{
r=read(fd,buffer,10);
write(STDOUT_FILENO,"parent reads",15);
write(STDOUT_FILENO,buffer,10);
write(STDOUT_FILENO," ",1);
wait();
r=read(fd,buffer,10);
write(STDOUT_FILENO,"parent reads",15);
write(STDOUT_FILENO,buffer,10);
write(STDOUT_FILENO," ",1);
}
return 0;
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.