简体   繁体   English

将整数数组写入管道

[英]Writing an array of ints to pipe

I am having trouble trying to write and read from a pipe.我在尝试从管道中写入和读取时遇到问题。 I have to create an array of prime numbers and write that array to a pipe to be read that array from the pipe.我必须创建一个素数数组并将该数组写入管道以从管道中读取该数组。 I have tried multiple different ways but cannot figure it out.我尝试了多种不同的方法,但无法弄清楚。

Here is my code.这是我的代码。

#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);
    }
}

} }

You write byte encoding of int values您编写 int 值的字节编码

write(fd[1], &answer[i], sizeof(int))

read them correctly正确阅读它们

nbytes = read(fd[0], readbuffer, sizeof(int))

but try to print them as C-strings但尝试将它们打印为 C 字符串

printf("recieved string: %s", readbuffer)

Your compiler should have complain about wrong type here.你的编译器应该在这里抱怨错误的类型。 Replace by替换为

printf("...%d\n",*readbuffer);

Beware that you are using C-streams while your code is C++.请注意,当您的代码是 C++ 时,您正在使用 C 流。 It will be better to use C++-streams...使用 C++-streams 会更好......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM