試圖創建一個管道,可以關閉一串隨機數。分裂成父母和小孩,產生隨機數字,如果孩子寫信給管道,如果是父母讀書。我覺得這很接近,但我的輸出是無稽之談。有人可以解釋一下管道的作用,並告訴我如何執行這個動作的方向是正確的。與字符串數組一起使用管道
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream> /* c++ I/O headers */
#include <string.h>
#include<math.h>
using namespace std;
int main(int argc, char *argv[]) {
//Get the number of random numbers
int numberOfRandomNumbers = stoi(argv[1]);
//char childPipe[200], parentPipe[200]; //pipes to hold numbers
int pid, index, count; //counters
int pipe1[2]; // main pipe
int xyz = pipe(pipe1); //perform the pipe
string stringOfRandomNumbers = "";
pid = fork(); //fork the process
//check for errors-------------------------------------------
if(xyz < 0 || pid < 0){
//break
cout << "Error" << endl;
return 0;
}
//Check process----------------------------------------------
if (pid == 0) { /* child */
srand(pid+4); //seed the random
int randNum;
//Start building the string
stringOfRandomNumbers = "Child, ID = ";
stringOfRandomNumbers += to_string(pid);
stringOfRandomNumbers += ", Random numbers: >";
//Now generate random numbers
for (index = 0; index < numberOfRandomNumbers; index++) {
randNum = rand() % 100;
//add to string.....
if(index == (numberOfRandomNumbers - 1)){
//last one
stringOfRandomNumbers += (to_string(randNum) + "<");
}
else{
stringOfRandomNumbers = stringOfRandomNumbers + (to_string(randNum) + ", ");
}
}
cout << endl << stringOfRandomNumbers << " length = " << stringOfRandomNumbers.length() << endl;
close(pipe1[0]); //don't read off of pipe
write(pipe1[1], stringOfRandomNumbers, stringOfRandomNumbers.length());
close(pipe1[1]); //done
}
else { /* parent */
// Now generate random numbers
srand(pid+8);
int randNum;
//Start the string
stringOfRandomNumbers = "Parent, ID = ";
stringOfRandomNumbers += to_string(pid);
stringOfRandomNumbers += ", Random numbers: >";
//Now generate random numbers
for (index = 0; index < numberOfRandomNumbers; index++) {
randNum = rand() % 100;
//Add to string.....
if(index == (numberOfRandomNumbers - 1)){
//last one
stringOfRandomNumbers += (to_string(randNum) + "<");
}
else{
stringOfRandomNumbers = stringOfRandomNumbers + (to_string(randNum) + ", ");
}
}
close (pipe1[1]);
count = read(pipe1[0], stringOfRandomNumbers, stringOfRandomNumbers.length());
for (index=0; index < count; index++){
cout << stringOfRandomNumbers[index] << endl;
}
close (pipe1[0]); //done
}
}
此外,任何額外的材料,這個問題將不勝感激。 – MattCucco
你爲什麼在父母身上產生隨機數字?當你在父進行讀取調用時,你應該提供一個緩衝區和最大長度讀入緩衝區。 –
查看閱讀電話的文檔。我不相信它允許'std :: string'作爲參數傳遞。 –