我基本上要做的是:我有一个有10个随机整数的数组,我需要有两个孩子;一个计算偶数索引的乘积,另一个处理概率。完成后,父进程将把这两个值相乘并打印出来。
这是我的代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int ans[2];
int array[10]; //main array
int i;
srand (time(NULL)); //for not the same numbers
for(i=0;i<10;i++)
{ //array filling
array[i]= ( rand() % 10 + 1); //from 1 to 10 random numbers
printf("Array: %d \n",array[i]);
}
int children = 2; //number of child processes
int *product=0; // var to store the product sums
int fd[2];
pipe(fd);
int arraymax[2]; //the two products
for(i=0;i<children;i++)
{ //for 10 children
//child processes
if(fork() == 0)
{
printf("checkpoint 1\n");
close(fd[0]); //close reading
for(int j=i;j<sizeof(array)-1;j+=2)
{
product+= (array[j]*array[j+2]);
}
write(fd[1], &product, sizeof(*product)); //write the max number into the pipe
printf("the product is: %d\n", *product);
close(fd[1]); //close write
wait(NULL);
exit(0);
} //parent process
else
{
printf("checkpoint 2\n");
wait(NULL);
close(fd[1]); //close write
/* read pipe */
for(int j=0; j<2; j++)
{
read(fd[0], &ans , sizeof(*product));
}
close(fd[0]); //close read
}
}
printf("Total answer is: %d \n", (ans[0]*ans[1]));
return 0;
}
结果是:
Array: 10
Array: 7
Array: 9
Array: 5
Array: 4
Array: 4
Array: 8
Array: 5
Array: 7
Array: 1
checkpoint 2
checkpoint 1
checkpoint 2
checkpoint 1
Total answer is: -432399864
答案不应该接近它给我的数字。感谢您的帮助:)
最佳答案
希望这对你有帮助。(这不涉及奇偶部分。希望你能搞清楚)
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int ans;
int total = 1;
int array[10]; //main array
int i;
srand (time(NULL)); //for not the same numbers
for(i=0;i<10;i++)
{ //array filling
array[i]= ( rand() % 10 + 1); //from 1 to 10 random numbers
printf("Array: %d \n",array[i]);
}
int children = 2; //number of child processes
int product=0; // var to store the product sums
int fd[2];
pipe(fd);
int arraymax[2]; //the two products
for(i=0;i<children;i++)
{ //for 10 children
//child processes
if(fork() == 0)
{
printf("checkpoint 1\n");
close(fd[0]); //close reading
for(int j=i;j<sizeof(array)/sizeof(int)-2;j+=2)
{
product+= (array[j]*array[j+2]);
}
printf("the product: %d\n", product);
write(fd[1], &product, sizeof(product)); //write the max number into the pipe
//printf("the product is: %d\n", product);
close(fd[1]); //close write
wait(NULL);
exit(0);
} //parent process
else
{
printf("checkpoint 2\n");
wait(NULL);
close(fd[1]); //close write
/* read pipe */
for(int j=0; j<2; j++)
{
read(fd[0], &ans , sizeof(product));
}
total *= ans;
close(fd[0]); //close read
}
}
printf("Total answer is: %d \n", (total));
return 0;
}
你的指针有些错误我已经纠正了。为了得到两个孩子的结果,我使用了一个单独的变量(total)。
这里的循环超出了界限
for(int j=i;j<sizeof(array)-1;j+=2)
{
product+= (array[j]*array[j+2]);
}
应该是
for(int j=i;j<sizeof(array)/sizeof(int)-2;j+=2)
{
product+= (array[j]*array[j+2]);
}
如果您有任何问题,请随时提出。
关于c - `write()`和`read()`不能正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46575684/