I am writing a program that is supposed to open a directory as a command line argument, read that directory, open each file and count a number of occurrences of a certain character, taken from the user as cin, fork the parent process to create a child process for each file. a pipe is created for communication with the parent and a 2 dimensional array of pipes is needed for communication with each child process (each file), one for the pipe number and the other is the read/write descriptor(0 or 1). My program is looping through all the files ok, but it seems it isn't writing the "char a" to the pipe correctly. for every child, do_child_stuff() is called, and it reads the file name, opens it, counts the # of occurrences and returns that count to the parent to hold a total for all the files. normally to write to a pipe, it should be write(pipe_name[1], &a, sizeof(a)) but I don't know how to do this with an array of pipes. i try to write to it by doing write(child_pipe[pc][1], &a...) pc is the array position for that pipe and it gets incremented after reading each file. can anyone find my error or if thats not my problem, what is?
struct dirent *d;
struct stat sb;
int adult_pipe[2];
int child_pipes[1000][2];
char *dir;
DIR *dptr;
char *name;
int pc=0;
void do_child_stuff(char *name)
{
std::ifstream is(name);
while(is.good())
{
if (a == is.get())
count++;
}
is.close();
write(adult_pipe[1], &count, sizeof(count));
pc++ ;
}
int main(int argc, char *argv[])
{
char a; //search character
int total=0; // counter for character match
int fc=0;
int pc=0;
int count=0;
dir = argv[1];
chdir(dir); //changes to directory from input
if ((dptr = opendir(".")) == NULL)
{
cout << "Error, can't open! " << endl;
exit(0);
}
if (pipe (child_pipes[1000]) == -1)
{
cerr << "Pipe failed! " << endl;
exit(0);
}
if (pipe (adult_pipe) == -1)
{
cerr << "Pipe failed! " << endl;
exit(0);
}
cout << "Enter a character to search: " << endl;
cin >> a; // char search variable
do
{
while(d=readdir(dptr)) //read each file in dir
{
if(d->d_type == DT_REG) //if reg file
{
I got it all working today. I had it all messed up. 1st was closing the pipe ends that werent supposed to be used. I had to read through all the files in the dir first, put them in an array. Next was i needed to create an array of pipes based on the amount of files i read, so that was a loop. Then i could prompt the user for a char to write to the child process to be counted in each file. Once prompted, i forked the parent process as many times as files, sending the file name and pipe index. Write sent the char to each child and read received that, then write sent back the count, and the parent read that count... I forgot my code at school so i dont have my changes, but i had this pretty messed up.