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
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
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++. It will be better to use C++-streams...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.