the*_*ole 30
前两个命令的一个小例子.您需要使用pipe()函数创建一个管道,该管道将介于ls和grep之间以及介于grep和更多之间的其他管道之间.dup2做的是将文件描述符复制到另一个文件描述符中.管道通过将fd [0]中的输入连接到fd [1]的输出来工作.您应该阅读pipe和dup2的手册页.如果您有其他疑问,我可以稍后尝试简化示例.
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#define READ_END 0
#define WRITE_END 1
int
main(int argc, char* argv[])
{
pid_t pid;
int fd[2];
pipe(fd);
pid = fork();
if(pid==0)
{
printf("i'm the child used for ls \n");
dup2(fd[WRITE_END], STDOUT_FILENO);
close(fd[WRITE_END]);
execlp("ls", "ls", "-al", NULL);
}
else
{
pid=fork();
if(pid==0)
{
printf("i'm in the second child, which will be used to run grep\n");
dup2(fd[READ_END], STDIN_FILENO);
close(fd[READ_END]);
execlp("grep", "grep", "alpha",NULL);
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)