0

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

1 回答 1

0

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

一种方法是在管道顶部使用fdopen(3). 然后,您可以使用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);
于 2013-03-13T22:04:03.013 回答