使用c在Linux中实现管道

Tin*_*mer 1 c pipe

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

ls | grep "SOMETHING"

用c编程语言编写.任何人都可以帮助我.

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

这不可能吗?

Tin*_*mer 8

我终于找到了它的代码.

#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;
}
Run Code Online (Sandbox Code Playgroud)