So I have this problem, I need to create 3 processes (each handle a different task). The first process sends information over to the second (the first waits for an acknowledgement from the second). The second then sends information to the third (the second waits for an acknowledgement from the third). Then the third processes the final information... This process is supposed to loop over and over until process one analyzes an entire text file. So far, I tried writing the communication between the 3 processes with pipes. I'm not sure how I send an acknowledgment from process 2 to process 1 and process 3 to process 2. I'm also not entirely sure how to loop it. Thanks!
I have to use a stop and wait protocol... I'm not sure how that is done.
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int c = 0, t = 0;
int fd1[2], fd2[2];
char *theFile = "/Users/Desktop/thefile";
FILE *file = fopen (theFile, "r");
if (file == NULL) {
perror("FILE DOES NOT EXIST");
exit(1);
}
while (c == 0) {
int status;
char readbuffer[80];
char readbuffer2[80];
int tTemp = 0;
pipe(fd1);
pipe(fd2);
pid_t pid = fork();
if (pid < 0) {
perror("Pipe Error");
exit(1);
}
if (pid == 0) {
//Child 1
close(fd1[0]);
close(fd2[0]);
close(fd2[1]);
char line [80];
int c2 = 0;
file = fopen (theFile, "r");
while (fgets(line, sizeof(line), file) != NULL){
if (c2 == t) {
printf("Line: %s\n", line);
break;
}
c2++;
}
if (t != c2) {
c = 1;
} else {
write(fd1[1], line, (strlen(line)+1));
}
t++;
exit(1);
}
pid_t pid2 = fork();
if (pid2 < 0) {
perror("Pipe Error");
exit(1);
}
if (pid2 == 0) {
//Child 2
close(fd1[1]);
close(fd2[0]);
read(fd1[0], readbuffer, sizeof(readbuffer));
printf("2nd Child string: %s\n", readbuffer);
char string2[80] = "asdfasdf";
write(fd2[1], string2, (strlen(string2)+1));
exit(1);
}
pid_t pid3 = fork();
if (pid3 < 0) {
perror("Pipe Error");
exit(1);
}
if (pid3 == 0) {
//Child 3
close(fd2[1]);
close(fd1[0]);
close(fd1[1]);
read(fd2[0], readbuffer2, sizeof(readbuffer2));
exit(1);
}
waitpid(pid, &status, 0);
waitpid(pid2, &status, 0);
waitpid(pid3, &status, 0);
}
fclose(file);
return 0;
}