The code is supposed to count integers from 1 to 10000 and if its divisible by 5 then the parent counts how many times this happens, if it's not the number is sent via a pipe to the child to see if the number is divisible by 3.
At the end of the program the child is supposed to send its results to the parent which is supposed to print the counts of both the parent and child and print both process ids. I can only use one pipe.
I've been trying to figure out the problem with this for a while.
Here is the code. btw I'm using gcc.
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
//our file descriptor
int fd[2];
//parent count, and child count
int pcount = 0, ccount = 0, x = 0, i = 0;
//if childread is 0 then the child reads, other wise it writes
int childread = 0;
int temp;
pid_t childpid;
int *buffer;
ssize_t nread;
int pid;
//create a pipe
pipe(fd);
//fork the process
pid = fork();
// parent process
if(pid > 0)
{
if (childread != 0)
{
//close fd for writing to read what the child has
if(close(fd[1]) == -1)
printf("Closing error.\n");
nread = read(fd[0], &temp, sizeof(int));
//ccount = *buffer;
printf("Parent count: %d\n", pcount);
printf("Child count: %d\n", temp);
//wait for child to exit
waitpid(childpid);
exit(1);
}
else
{
//close fd for reading
if(close(fd[0]) == -1)
printf("Closing error.\n");
//start counting
for(i = 0; i < 10000; i++)
{
//if multiple of 5 increment parent count
if( (i % 5) == 0 )
{
pcount++;
}
else
//write i to pipe for child to process
{
write(fd[1], &i, sizeof(int));
wait();
}
}
//the child is now going to send its count to parent
childread = 1;
}
}
else if(pid == 0) //child process
{
if (childread != 0)
{
//close file descriptor for reading
if(close(fd[0]) == -1)
printf("Closing error.\n");
//*buffer = ccount;
//send result to parent and exit
write(fd[1], &ccount, sizeof(int)); //change to &buffer
//print the parent id
printf("\nThe parent pid is: %d\n", getppid());
//print the child pid
printf("The child pid is: %d\n", getpid());
childpid = getpid();
//exit the child process
exit(1);
}
else
{
//close file descriptor for writing
if(close(fd[1]) == -1)
printf("Closing error.\n"); exit(1);
//read the integer passed from the parent
nread = read(fd[0], &x, sizeof(int));
//x = *buffer;
//if the number is a multiple of 3 increment the child counter
if( (x % 3) == 0)
{
ccount++;
}
}
}
else
{
printf("Error forking.\n");
exit(1);
}
//printf("\nParent id: %d\nChild id: %d\nMultiples of 5 counted: %d\nMultiples of 3 counted: %d", pid, cid, pcount, ccount);
close(fd[0]);
close(fd[1]);
return 0;
}
This post has been edited by endomlic: 24 March 2009 - 03:00 PM

New Topic/Question
Reply




MultiQuote



|