#include #include // pipe, fork. #include // perror #include #include using namespace std; void DoParent(int readfd, int writefd); void DoChild(int readfd, int writefd); string EightBall(); const char EOM = '\n'; int main() { int pipe1[2]; int pipe2[2]; pid_t pid; string message; if(-1 == pipe(pipe1)) { perror("Pipe1 failed"); exit(-1); } if(-1 == pipe(pipe2)) { perror("Pipe2 failed"); exit(-1); } pid = fork(); if (-1 == pid) { perror("Fork Faild"); exit(-1); } // in this case, the parent will send messages to the child. if (pid) { // parent, writer close(pipe1[0]); close(pipe2[1]); DoParent(pipe2[0], pipe1[1]); } else { // child close(pipe1[1]); close(pipe2[0]); DoChild(pipe1[0], pipe2[1]); } return 0; } void DoParent(int readfd, int writefd){ string question, answer; char letter; while (question != "EXIT") { // get a question from the user cout << "Enter a question for the 8-ball => "; getline(cin, question); cout << endl; // send the question to the child write(writefd, question.c_str(), question.size()); write(writefd, &EOM, 1); // read the answer from the child if (question != "EXIT") { answer = ""; do { read(readfd, &letter, 1); if (letter != EOM) { answer += letter; } } while (letter != EOM); // write the answer to the user cout << "The 8-ball answers \"" << answer << '"' << endl; } } return; } void DoChild(int readfd, int writefd){ string question, answer; char letter =' '; srand(time(NULL)); ofstream logFile; logFile.open("EightBall.log"); while (question != "EXIT") { // read the question question = ""; read(readfd, &letter, 1); while (letter != EOM) { question += letter; read(readfd, &letter, 1); } if (question != "EXIT") { // generate the answer answer = EightBall(); // send the answer write(writefd,answer.c_str(), answer.size()); write(writefd, &EOM, 1); // log the question and the answer. logFile << question << endl; logFile << answer << endl; logFile << endl; } } logFile.close(); return ; } string EightBall() { int answer = rand() % 20; switch(answer) { case 0: return "It is certain."; case 1: return "It is decidedly so."; case 2: return "Without a doubt."; case 3: return "Yes, definitely."; case 4: return "You may rely on it."; case 5: return "As I see it, yes."; case 6: return "Most likely."; case 7: return "Outlook good."; case 8: return "Yes."; case 9: return "Signs point to yes."; case 10: return "Reply hazy try again."; case 11: return "Ask again later."; case 12: return "Better not tell you now."; case 13: return "Cannot predict now."; case 14: return "Concentrate and ask again."; case 15: return "Don't count on it."; case 16: return "My reply is no."; case 17: return "My sources say no."; case 18: return "Outlook not so good."; case 19: return "Very doubtful."; } return "Program error, conuslt your systems administrator!"; }