我是C ++的新手,我遇到了管道问题。我正在尝试在循环中生成随机数列表,通过管道将它们发送到子进程,对它们进行排序,然后将它们返回给父进程。我能够正确地获得第一个号码,但它永远不会更新到我发送的第二个号码。我觉得有一些基本的东西我忽略了,并且想知道是否有人可以指出我的错误。这是我的代码的相关部分:
if (pid == 0){ // child process---------------------------------
close(pipe1[1]); // close write end of pipe1
close(pipe2[0]); // close read end of pipe2
dup2(pipe1[0], STDIN_FILENO);
dup2(pipe2[1], STDOUT_FILENO);
execlp("sort", "sort", "-nr", NULL); // sort incoming data
close(pipe1[0]); // close read end of pipe1
close(pipe2[1]); // close write end of pipe2
}
else{ // parent process----------------------------------------
double range = sleepMax-sleepMin;
double randNum;
double randNum2;
char randNumSend[15];
char randNumRet[15];
if (randSeed==0){
srand(NULL);
}
else{
srand(randSeed);
}
close(pipe1[0]); // close read end of pipe1
close(pipe2[1]); // close write end of pipe2
for(int i=0; i<nWorkers; i++){
randNum = sleepMin + (((double) rand()) /RAND_MAX)*range; // generate random number within range
cout<<randNum<<" outbound" <<endl; // display value beore sending off to child process
sprintf(randNumSend, "%f", randNum); // convert double to string
write(pipe1[1],&randNumSend,sizeof(randNum)); // pass randNum through pipe1 to child process
close(pipe1[1]); // close write end of pipe1
}
for (int i=0; i<nWorkers; i++){ // loop to read back sorted values from child process
read(pipe2[0],&randNumRet,sizeof(randNum2)); // read back data
randNum2 = atof(randNumRet); // convert back from string to double
cout<<randNum2<<" inbound" <<endl; // display results
close(pipe2[0]); // close read end of pipe2
}
}
我的控制台输出是:
1.20022 outbound
4.97513 outbound
2.38587 outbound
2.06326 outbound
1.20023入境
1.20023入境
1.20023入境
1.20023入境