在 C 中处理管道

Dealing with pipes in C

我正在尝试在我正在从事的 Linux.This 项目上用 C 语言实现一个 shell,要求用 C 语言创建一个 shell,从创建一个非常基本的一个(我的Shell),它更深入 step.First 我不得不用像

这样的简单命令创建一个 shell

ls,pwd,echo,date,time

(shell1).

在那之后,我的 Shell 必须得到改进,以便它可以从文件(例如 txt's)中进行排序 (shell2),随着它的继续,我不得不通过开发它,并让它执行像

这样的命令

sort -r,sort -u.(shell3).

直到第 3 次 shell,我一直在处理重定向,一切都很顺利。

现在是第 4 个 shell,我应该用管道使它成为 运行 命令,例如ls -l /家/ |排序 > out.txt。我已经设法使命令工作,out.txt 文件已成功创建并进行了相应的排序。在我的代码中有一个 while() ,所以在我给 shell 的每个命令之后,它都会要求下一个等等。但是当给出上面的示例命令并使用管道时,程序停止。终端不显示 "myShell4>" 但显示 Desktop$,它基本上退出 shell。给它一些简单的命令,比如 "ls -l" ,不使用管道,效果很好,所以我意识到问题出在管道上,它们阻止了我的程序循环。

我的代码中发生这种情况的部分:

//CHILD
dup2(pipefd[1],1);
close(pipefd[0]);
execute(cmd,path,argm);

//PARENT
dup2(pipefd[0],0);
close(pipefd[1]);
execlp(cmd2,cmd2,NULL);

有什么想法吗?提前致谢!

parent就是shell,对吧?不要在那里执行;为管道的两端创建 children 并在 parent 中等待它们。如果这样做,shell 将被替换,并且在命令结束后不再是 运行。

下面是一些 pseudo-code 两个命令之间的管道:

int pipefd[2];
pipe (pipefd);

// child for first command
if (fork () == 0) {
   // setup in redirection if any
   ...
   // setup out redirection
   close (pipefd[0]);
   dup2 (pipefd[1], STDOUT_FILENO);
   ...

   exec (cmd1, ...);
   exit (1);
}

// child for second command
if (fork () == 0) {
    // setup in redirection
    close (pipefd[1]);
    dup2 (pipefd[0], STDIN_FILENO);
    // setup out redirection if any
    dup2 (output_file_fd, STDOUT_FILENO);

    exec (cmd2, ...);
    exit (1);
}

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

// parent waits and then restarts the loop
wait (NULL);
wait (NULL);

对于由管道连接的两个以上命令的列表,事情变得更加复杂。