c - 在 Linux 中使用 c 实现管道

标签 c pipe

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

ls | grep“某事”

用c编程语言。谁能帮我解决这个问题。

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

这不可能吗?

最佳答案

我终于找到了它的代码。

#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;
}

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

相关文章:

c - 在 C 中使用管道运行并发进程

c++ - boost 1.46.1 中的 boost::asio::windows::stream_handle 在哪里?

r - 统计每列非零元素的个数——管道友好

c - 将 STDOUT 重定向到文本文件无法正常工作

c - 指针指向指针的二叉树递归插入

c - 如何在 sscanf 中传递可变长度宽度说明符?

c++ - 宏参数上的 Foreach 宏

无法用c中的for循环写入文本文件

c - switch 语句将数字转换为单词

c - 检查另一个程序的输出的程序