2

我必须编写一个程序来执行与du |相同的操作。排序 | 命令行中的head会做,但我被卡住了,我的程序不工作。现在的输出是112 。并且程序不会终止。请帮忙,我不知道该怎么办!

int main(void) {

int fd[2];
int fd1[2];
int pid;

if (pipe(fd) == -1) {
    perror("Pipe");
    exit(1);
}

switch (fork()) {
 case -1:
    perror("Fork");
    exit(2);
 case 0:            
    dup2(fd[1], STDOUT_FILENO);
    close(fd[0]);
    close(fd[1]);
    execl("/usr/bin/du", "du", (char *) 0);
    exit(3);
}
if (pipe(fd1) == -1) {
    perror("Pipe");
    exit(1);
} 

switch (fork()) {
 case -1:
    perror("Fork");
    exit(2);
 case 0:    
    dup2(fd[0], STDIN_FILENO);
    dup2(fd1[1], STDOUT_FILENO);
    close(fd[0]);
    close(fd[1]);
    close(fd1[0]);
    close(fd1[1]);
    execl("/usr/bin/sort", "sort", (char *) 0);
    exit(3);
}

close(fd[0]);
close(fd[1]);

switch (fork()) {
 case -1:
    perror("Fork");
    exit(2);
 case 0:    
    dup2(fd1[0], STDIN_FILENO);
    close(fd1[0]);
    close(fd1[1]);
    execl("/usr/bin/head", "head", (char *) 0);
    exit(3);
}

}

4

1 回答 1

1

head成为您的父进程sort - 它的子进程du - sort的子进程或head的孙子进程。

您需要两个管道,因此需要两个数组——fd 和 fd1。让 fd 管道将sorthead连接起来,并将 fd1- dusort连接起来。

您将需要一个大的 switch 语句,它将确定您当前是在父进程中(head, pipe(fd) 不是 0)还是子进程(sort, pipe(fd) 是 0)。如果您处于排序状态,则需要创建 fd1 管道并运行孙进程du。现在,由于您再次有两个进程(总共三个),您需要根据您的位置设置一个管道 - 无论您是在孙子进程中还是在子进程中。您可以使用与 pipe fd 类似的 switch 语句。这里的技巧是正确设置 fd1 管道的输入和输出。

您的代码必须执行以下操作:

int main(void) {

    int fd[2];             // sort <===> head
    int fd1[2];            //  du  <===> sort

    pipe(fd);

    switch (fork()) {
        case 0:            // Are we in sort?
             pipe(fd1);    // If yes, let's make a new pipe!

             switch (fork()) {
                 case 0:   // Are we in du?
                     dup2(fd1[1], STDOUT_FILENO);
                     close(fd1[0]);
                     close(fd1[1]);
                     execl("/usr/bin/du", "du", (whatever directory), NULL);
                     exit(1);

                 default:
                     /* If not in du, we're in sort! in the middle!
                        Let's set up both input and output properly.
                        We have to deal with both pipes */
                     dup2(fd1[0], STDIN_FILENO);
                     dup2(fd[1], STDOUT_FILENO);
                     close(fd1[0]);
                     close(fd1[1]);
                     execl("/usr/bin/sort", "sort (flags if needed)", (char *) 0);
                     exit(2);
             }

            exit(3);

        default:            // If we're not in sort, we're in head
            dup2(fd[0], STDIN_FILENO);
            close(fd[0]);
            close(fd[1]);
            execl("/usr/bin/head", "head (flags if needed)", (char *) 0);
            exit(4);

    }   
}
于 2015-12-01T01:33:55.710 回答