使用exec对发送给子节点的随机数进行排序

sorting random numbers sent to child using exec

本文关键字:随机数 排序 子节点 exec 使用      更新时间:2023-10-16

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