gpt4 book ai didi

c++ - 使用 exec 对发送给子进程的随机数进行排序

转载 作者:行者123 更新时间:2023-11-30 17:53:49 25 4
gpt4 key购买 nike

我想做的是发送由父级生成的随机数,然后发送给子级,然后子级执行“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;
}
}

最佳答案

sort(1) 期望其输入是 ASCII 字符串,而不是原始二进制数。当您使用 write(2) 向其传递数据时,会将数字的原始二进制表示形式写入管道,这不是您想要的。您需要将数字转换为其字符串表示形式。

一种方法是使用 fdopen(3) 在管道顶部打开 stdio 流。 。然后,您可以使用 fprintf 写入格式化数据:

FILE *childInput = fdopen(pipe1[WRITE_END], "w");
if (childInput == NULL) { /* Handle error */ }
for (...)
{
...
fprintf(childInput, "%d\n", 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);

关于c++ - 使用 exec 对发送给子进程的随机数进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15396939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com