我在尝试从管道写入和读取时遇到问题。我必须创建一个素数数组,并将该数组写入管道,以便从管道中读取该数组。我尝试了多种不同的方法,但无法弄明白。
这是我的代码。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include <sstream>
#include <string.h>
using namespace std;
int main(int argc, char *argv[]){
int n = 10000;
int array[n] = {0};
int nums[n] = {0};
int k = 0;
int answer[argc] = {0};
//this loop makes an array or prime numbers acording to the node
//if that node number is not a prime number it puts a 0 in that node
for(int i =2; i < n; i++){
for(int j = (i*i); j < n; j+=i){
array[j-1] = 1;
}
}
//this loop makes an array of all the prime numbers;
for(int i = 1; i < n; i++){
if(array[i -1] == 0){
nums[k] = i;
k++;
}
}
//this loop puts the selected prime numbers in the array
for(int j = 1; j < argc; j++){
int num = atoi(argv[j]);
answer[j - 1] = nums[num];
}
//this loop prints the primes for testing
for(int i = 1; i < argc; i++)
cout << answer[i - 1] << endl;
int fd[2], nbytes;
pid_t childpid;
string number;
int readbuffer[90];
string numbers;
pipe(fd);
if((childpid = fork()) == -1){
perror("fork");
exit(1);
}
if(childpid == 0){
close(fd[0]);
for(int i = 0; i < argc; i ++){
write(fd[1], &answer[i], sizeof(int));
}
exit(0);
}
else{
close(fd[1]);
for(int i = 0; i < argc; i++){
nbytes = read(fd[0], readbuffer, sizeof(int));
printf("recieved string: %s", readbuffer);
}
}
}
答案 0 :(得分:1)
您编写int值的字节编码
write(fd[1], &answer[i], sizeof(int))
正确阅读
nbytes = read(fd[0], readbuffer, sizeof(int))
但尝试将它们打印为C字符串
printf("recieved string: %s", readbuffer)
你的编译器应该在这里抱怨错误的类型。替换为
printf("...%d\n",*readbuffer);
请注意,当您的代码是C ++时,您正在使用C流。最好使用C ++ - streams ......