【问题标题】:Pipe implementation in Linux using c在 Linux 中使用 c 实现管道
【发布时间】:2013-06-18 10:35:39
【问题描述】:

我正在尝试执行以下命令,

ls | grep "SOMETHING"

在 c 编程语言中。任何人都可以帮我解决这个问题。

我想 fork 一个孩子,我将在其中使用 execlp 运行 ls 命令。 在父级中,我得到子级和 grep 的输出(再次使用 execlp)。

不可能吗?

【问题讨论】:

标签: c pipe


【解决方案1】:

我终于找到了它的代码。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int pfds[2];
pipe(pfds);
if (!fork()) {
    close(1);       /* close normal stdout */
    dup(pfds[1]);   /* make stdout same as pfds[1] */
    close(pfds[0]); /* we don't need this */
    execlp("ls", "ls", NULL);
} else {
    close(0);       /* close normal stdin */
    dup(pfds[0]);   /* make stdin same as pfds[0] */
    close(pfds[1]); /* we don't need this */
    execlp("grep", "SOMETHING", NULL);
}
return 0;
}

【讨论】:

    【解决方案2】:

    管道只是从一个标准输出读取并写入另一个标准输入。
    你想实现一个带有管道功能的 shell 解释器吗?
    首先,你需要一个shell解析器来解析command。
    然后,您将拥有一个管道要素。
    ...

    【讨论】:

    • 不,我不想实现 shell 解释器。使用 execlp ,我想执行 ls 并将其传送到 grep ,它也使用 execlp 运行。
    • 为什么不作为单个命令运行?这有点复杂。不过,popen 是获取 shell 命令输出的最佳选择。
    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多