Code:
#include <iostream>
#include <cstring>
#include <ctime>
#include "string2int.h"
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
#define BSIZE 512
void parent(int Msgs);
int main()
{
parent(100);
return 0;
}
void parent(int Msgs)
{
int numMsgs = Msgs;
int message = 1;
char line [512];
int lineNum=0;
string linestr;
string chldmsg;
string msgstr;
int pid;
int ranLines;
int pipe1[2];
int pipe2[2];
int err1 = pipe(pipe1);
int err2 = pipe(pipe2);
if(err1 == -1 || err2 == -1)
cout<<"error with pipes"<<endl;
char buf[512];
ssize_t nbytes;
pid = fork();
if(pid < 0)
cout<<"ERROR"<<endl;
else if (pid == 0)
{
int a=0;
int chLines;
char chMsg[512];
string chMsgNum;
string lnNum;
nbytes=read(pipe1[0], buf, BSIZE);
while(nbytes!=0 && buf[0] != 'b')
{
cout<<"parent: ";
for(a=0; buf[a]!= '*'; a++)
{
cout<<buf[a];
}
cout<<endl;
nbytes=read(pipe1[0], buf, BSIZE);
if(nbytes==0)
{
//child should now send message to parent
}
}
}
else
{
//close(pipe1[0]);
srand(time(0));
int x=0;
int y=1;
int z=0;
while(message<101)
{
ranLines = (1+ rand() % 5);
if(message==100)
write(pipe1[1],"bye",3);
else
{
for(x=1; x<ranLines+1; x++)
{
y=0;
z=0;
line[0]='m';
msgstr=BasicTypeToStr(message);
for(y=1; z<msgstr.size(); y++)
{
line[y]=msgstr[z];
z++;
}
y=msgstr.size()+1;
line[y]=' ';
y++;
line[y]='l';
y++;
line[y]='i';
y++;
line[y]='n';
y++;
line[y]='e';
y++;
line[y]=' ';
y++;
lineNum++;
linestr=BasicTypeToStr(lineNum);
z=0;
for(y; z<linestr.size(); y++)
{
line[y]=linestr[z];
z++;
}
line[y]='*';
cout<<endl; //write to external file here
write(pipe1[1],line,y+1);
}
//parent proccess should now wait for a response from child
nbytes=read(pipe2[0],buf,BSIZE);
cout<<nbytes<<endl;
// while(nbytes != -1)
// {
// cout<<"parent read"<<endl;
// nbytes=read(pipe2[0],buf,BSIZE);
// }
}
message++;
}
//close(pipe1[1]);
//parent code goes here
}
}
i now have it so that the parent sends the #of lines of the message and the child reads it. how can i make it so that the child is able to write a message and have the parent wait for it and read the message from the child and then it writes a message back and so on? For some reason I dont think the read is returning 0 at the end of file.