使用exec对发送给子节点的随机数进行排序
sorting random numbers sent to child using exec
我要做的是发送由父母生成的随机数,然后发送给孩子,然后执行"sort -nr",然后将排序的数字发送回父母。我发现这个问题已经被问过了,这里的答案和我的非常相似:如何重定向"sort"程序从子节点传递到父节点,我想我已经做了所有让它工作的事情,但是我不能让排序真的发生。我甚至检查了它是否出错,但我什么也没得到。
两个管道发送和接收相同的数字,但它们从来没有排序出来。我错过了什么?
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;
}
}
sort(1)
期望它的输入是ASCII字符串,而不是原始二进制数。当您用write(2)
传递数据时,这是将数字的原始二进制表示形式写入管道,这不是您想要的。您需要将数字转换为它们的字符串表示形式。
这样做的一种方法是在管道顶部用fdopen(3)
打开一个工作室流。然后您可以使用fprintf
来写入格式化的数据:
FILE *childInput = fdopen(pipe1[WRITE_END], "w");
if (childInput == NULL) { /* Handle error */ }
for (...)
{
...
fprintf(childInput, "%dn", randNumbers[i]);
}
fclose(childInput);
同样地,当从子进程回读输出时也需要做同样的事情:
FILE *childOutput = fdopen(pipe2[READ_END], "r");
if (childOutput == NULL) { /* Handle error */ }
while (fscanf(childOutput, "%d", &sortedNubers[i]) == 1)
{
...
}
fclose(childOutput);
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 整数不会重复超过随机数
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 需要关于如何将我的随机数数组连接到冒泡排序的帮助
- C++ - 如何保持半随机数组在循环中排序
- 随机数外排序
- 一个简单的程序来对随机数进行排序
- 冒泡排序随机数
- 将随机数插入排序顺序为C++的数组中
- 如何将冒泡排序函数添加到当前随机数生成器
- 排序前显示的随机数
- 使用exec对发送给子节点的随机数进行排序