Reputation: 69
I've to solve a problem in C. I've two process, P1 and P2. P1 takes an array of integers and have to send it to P2, P2 have to check only prime numbers in this array, modify it and send back to P1, P1 have to print the modified array.
Example: Array of Int (myArr) = {3,9,17,21,4,2,5} Final result = {3,0,17,0,0,2,5}
The problem is, how can I send the array of integers trough pipes?
//parent process
if(p>0)
{
int i;
int printArr[N];
close(fd1[0]);
//myArr is an array of integers previously declared
write(fd1[1],myArr,N);
close(fd1[1]);
wait(NULL);
close(fd2[1]);
read(fd2[0],printArr,N);
printf("\nPrinting modified array: ");
for(i=0; i<N; i++)
{
printf("\t%d",printArr[i]);
}
close(fd2[0]);
}
//child process
else if(p==0)
{
int i,k;
close(fd1[1]);
int readArr[N];
read(fd1[0],readArr,N);
//here's the problem, it doesn't print correct values
printf("Array that comes from parent");
for(i=0; i<N; i++)
{
printf("\n%d\n",readArr[i]);
}
for(i=0; i<N; i++)
{
k=checkprime(readArr[i]);
if(k==1)
readArr[i]=0;
}
close(fd1[0]);
close(fd2[0]);
write(fd2[1],readArr,sizeof(readArr)+1);
close(fd2[1]);
exit(0);
}
As I commented my code, when I read the array from pipe into readArr, it doesn't print correctly.
Upvotes: 0
Views: 245
Reputation: 23356
Your read()
call is reading N
bytes into an array of N
int
s. Use read(fd, buf, N * sizeof(int))
. Looks like you need to fix write()
as well.
Upvotes: 2