我想在管道上写入一个大小未知的数组。数组的值是从标准输入读取的。下面是我到目前为止编写的代码的一部分。问题是使用 count
变量我写的正好是 0 个字节。我什么时候应该为执行读取的数组分配内存?有没有更好的方法来完成这项工作?
#include<stdio.h>
#include<unistd.h>
int main(){
int fd[2];
int *values;
int *received;
pid_t child;
int count = 0;
if(pipe(fd) != 0){
perror("pipe");
}
if((child = fork()) < 0){
perror("fork");
}
else if(child == 0)
{
close(fd[0]);
while(enteringValues){
//get values from stdin
//allocating memory for each read element
count++;
}
write(fd[1],values,count*sizeof(values[0]));
close(fd[1]);
exit(0);
}
close(fd[1]);
int i;
int nbytes = read(fd[0],&received,count*sizeof(received[0]));
for(i = 0;i<count;i++){
printf("%d received \n",received[i]);
}
return 0;
}
最佳答案
管道将字节从一个地方发送到另一个地方。所以你需要精确地指定你要发送的字节。然后确保您的发送代码准确地发送这些字节,并且您的接收代码准确地期望这些字节。
如果您想让它工作而不必以正确的方式做事,请执行以下操作:
发件人:
write(f[1], &val, sizeof(int));
接收者:
for (int i = 0; i < 3; ++i)
read(f[0], &buf[i], sizeof(int));
还要注意 printf("%d", *buff);打印数组中的第一个元素(元素零)。
接收代码不要改成read(f[0], buf, 3 * sizeof(int));。您的写入不是原子的(因为您调用了三次写入)所以您不能期望您的读取是原子的。
关于c - 在管道上写入和读取未知大小的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20028236/