c - 在 C 中实现管道

标签 c pipe execve

我正在 C 中实现管道。当我尝试命令 'cat aa | grep "something"' 在我的程序中。 grep 进程就卡在那里,似乎在等待输入。我不知道为什么。这是核心代码。只需将 ExecuteCommand 视为简单调用 execve 函数即可正确传递所有参数。

if ((pid = fork()) < 0)
{
    perror("fork failed\n");
    exit(1);
}               
if (pid)
{   // parent as pipe WRITER
    close(pd[0]);
    close(1);
    // replace input with pipe
    dup(pd[1]);

    // recursively call next commands
    ExecuteCommand(cmds, env);
    FreeCommandsArray(&cmds);

    exit(0);
}
else
{   // child as pipe READER
    close(pd[1]);
    close(0); // close its READ end
    dup(pd[0]);
    ExecuteCommand(*(++splitCmds), env);
    FreeCommandsArray(&cmds);
    exit(0);
}

full code开了。 另一个问题是我必须使用命令文件的完整路径作为 execve 的第一个参数(例如/bin/ls 代表 ls),否则,我会收到错误消息,不存在这样的文件。

最佳答案

这是 grep 第一个参数处的引号导致问题的原因。如果我在输入时去掉它,效果会很好。例如 'cat aa | grep drw' 而不是 'cat aa | grep“某事”'

关于c - 在 C 中实现管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32688741/

相关文章:

linux - 如何将多个二进制文件通过管道传输到从标准输入读取的应用程序

c++ - 重写一个小的 execve shellcode

c - 这段 C 代码有什么问题? child 不回来了?

c - 在通用选择中处理 size_t

c - 多个 CreateFileA 调用返回相同的文件句柄

c++ - 在C/C++中打开驻留在 “/sys/”下的文件时出错

c - 使用管道时出现段错误

c - 使用 gdb 调试 Unix 管道

c - 多个程序的 Execve()

c - C 中的字符串 : giving some logical error