/*
* function: 使用管道实现父子进程间通信,完成: ls | wc –l。
* ls 命令正常会将结果集写出到 stdout,但现在会写入管道的写端; wc –l 正 常应该从 stdin 读取数据, 但此时会从管道的读端读。
*
* 2020-12-01
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd[2] = {0};
int ret = pipe(fd); // 创建管道
if (ret < 0)
{
perror("pipe faild");
exit(1);
}
pid_t pid = fork();
if (pid < 0)
{
perror("fork faild");
exit(1);
}
else if (pid == 0)
{
close(fd[0]);
int newfd = dup2(fd[1], STDOUT_FILENO); // 重定向
if (newfd < 0)
{
perror("dup2 faild");
exit(1);
}
execlp("ls", "ls", NULL);
close(fd[1]);
}
else
{
close(fd[1]);
int newfd = dup2(fd[0], STDIN_FILENO); // 重定向
if (newfd < 0)
{
perror("dup2 faild");
exit(1);
}
execlp("wc", "wc", "-l", NULL);
close(fd[0]);
}
return 0;
}
pipe 实现命令 ls | wc -l
最新推荐文章于 2024-04-21 12:08:44 发布