#include <stdio.h> #include <unistd.h> #define PROCS 5 int main () { int pid, pr
ID: 3557501 • Letter: #
Question
#include <stdio.h>
#include <unistd.h>
#define PROCS 5
int main () {
int pid, proc, checkTotal, pidTotal = 0, reportFds[2];
pipe(reportFds);
/* Create PROCS children, call them child 0 through child PROCS-1 */
for (proc = 0; proc < PROCS; proc++) {
if (!(pid = fork())) {
dup2(reportFds[0], 0);
close(reportFds[0]);
close(reportFds[1]);
}
else
pidTotal += pid;
}
for (proc = 0; proc < PROCS; proc++) {
if (0 < read(reportFds[0], &pid, sizeof(pid))) {
printf("Good read ");
pidTotal -= pid;
}
}
if (pidTotal == 0 && 0 == read(reportFds[0], &pid, sizeof(pid)))
printf("Good report and EOF ");
return 0;
}
Good read Good read Good read Good read Good read Good report and EOF
Explanation / Answer
#include <stdio.h>
#include<sys/wait.h>
#include<stdlib.h>
#include <unistd.h>
#define PROCS 5
int main () {
int pid, proc, checkTotal, pidTotal = 0, reportFds[2];
int status;
pipe(reportFds);
/* Create PROCS children, call them child 0 through child PROCS-1 */
for (proc = 0; proc < PROCS; proc++) {
if (!(pid = fork())) {
dup2(reportFds[0], 0);
close(reportFds[0]);
write(reportFds[1],&pid,sizeof(pid));
}
else{
pidTotal += pid;
if (0 < read(reportFds[0], &pid, sizeof(pid))) {
printf("Good read ");
pidTotal -= pid;
}
}
}
wait(&status); //wait till child processs are over
if (pidTotal == 0)
printf("Good report and EOF ");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.