[英]Pipe implementation in Linux using c
I am trying to implement following command, 我正在尝试执行以下命令,
ls | grep "SOMETHING"
in c programming language. 用C编程语言编写。 Can anybody please help me with this.
有人可以帮我吗
I want to fork a child , where i will run ls command using execlp. 我想派生一个孩子,在这里我将使用execlp运行ls命令。 In the parent i get the output of the child and grep (once again using execlp).
在父级中,我得到子级和grep的输出(再次使用execlp)。
Is it not possible? 不可能吗
I finally found the code for it. 我终于找到了代码。
#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;
}
The pipe is just read from one stdout and write to the other stdin. 仅从一个标准输出读取管道,然后将其写入另一个标准输入。
Do you want to implement a shell interpreter with pipe feature? 您要实现带有管道功能的Shell解释器吗?
First, you need a shell parser to parse the commond. 首先,您需要一个shell解析器来解析common。
Then, you would have a pipe line feature. 然后,您将具有管道功能。
... ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.