我要做的是发送由父母生成的随机数,然后发送给孩子,然后孩子执行“sort -nr”,然后将排序后的数字发回给父母。我发现这个问题已经被问到并在这里得到了非常类似于我的回答:how to redirect output of "sort" program from child to parent,我想我做了它所说的一切让它工作,但我不能让排序真正发生。我什至检查过它是否出错,但我什么也没得到。
两个管道发送和接收相同的数字,但它们从未排序。我错过了什么?
int pipe1[2], pipe2[2];
pid_t childID;
if (pipe(pipe1) < 0 || pipe(pipe2) < 0) {
perror("pipe");
exit(EXIT_FAILURE);
}
childID = fork();
if (childID < 0) {
//Child Process Failure
perror("fork");
exit(EXIT_FAILURE);
}
else if (childID == 0){
//Child Process Instructions
cout << "Sent Numbers: " << endl;
//Closes Unused Pipes
close(pipe1[WRITE_END]);
close(pipe2[READ_END]);
//Dups Over the Others, then closes them
dup2(pipe1[READ_END], STDIN_FILENO);
close(pipe1[READ_END]);
dup2(pipe2[WRITE_END], STDOUT_FILENO);
close(pipe2[WRITE_END]);
int fail = execlp("sort", "sort", "-nr", (char *)NULL);
cout << fail << endl;
}
else {
//Parent Process Instructions
//Close Unused Pipes
close(pipe1[READ_END]);
close(pipe2[WRITE_END]);
srand(randSeed);
cout << "Random Numbers: " << endl;
for (int i = 0; i < nWorkers; i++){
//Generate nWorker numbers, then Write
randNumbers[i] = rand() % (sleepMax - sleepMin + 1) + sleepMin;
write(pipe1[WRITE_END], &randNumbers[i], sizeof(randNumbers[i]));
cout << randNumbers[i] << endl;
}
close(pipe1[WRITE_END]);
wait(NULL);
cout << "SORTED NUMBERS:" << endl;
double sortedNumbers[nWorkers];
int n;
for(int k = 0; k < nWorkers; k++) {
n = read(pipe2[READ_END], &sortedNumbers[k], sizeof(sortedNumbers[k]));
cout << sortedNumbers[k] << ", " << n << endl;
}
}