// chat_template.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void)
{
int fd1[2];
int fd2[2];
pid_t pid;
char question[50], answer[50];
int i;
const char *questions[] = {
"What is your name?",
"How old are you?",
"Bye!"
};
const char *answers[] = {
"Pipe Master",
"3 milliseconds",
"Goodbye!"
};
if (pipe(fd1) == -1) {
perror("pipe1");
exit(1);
}
if (pipe(fd2) == -1) {
perror("pipe2");
exit(1);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
}
if (pid == 0) {
close(fd1[1]);
close(fd2[0]);
for (i = 0; i < 3; i++) {
read(fd1[0], question, sizeof(question));
printf("Child received: %s\n", question);
write(fd2[1], answers[i], strlen(answers[i])+1);
}
close(fd1[0]);
close(fd2[1]);
exit(0);
} else {
close(fd1[0]);
close(fd2[1]);
for (i = 0; i < 3; i++) {
write(fd1[1], questions[i], strlen(questions[i])+1);
read(fd2[0], answer, sizeof(answer));
printf("Parent got: %s\n", answer);
}
close(fd1[1]);
close(fd2[0]);
wait(NULL);
}
return 0;
}