pipe

管道在unix类系统中是一个很重要的概念,文件的重定向就是使用管道来实现的,在shell中也提供了"|"来直接使用管道,那么在C中,如何使用管道呢?

管道在unix中是通过pipe函数来实现的。

头文件: #include <unistd.h>
函数定义:int pipe(int filedes[2]);
函数说明:
函数返回文件描述符,其中filedes[0]为管道的写入端,filedes[1]为管道的读取端


函数实例(一)pipe的简单使用:
#include <unistd.h>
#include <stdio.h>

int main( void )
{
int filedes[2];
char buf[80];
pid_t pid;

pipe( filedes );

if ( (pid=fork()) > 0 )
{
printf( "This is in the father process,here write a string to the pipe.\n" );
char s[] = "Hello world , this is write by pipe.\n";
write( filedes[1], s, sizeof(s) );
close( filedes[0] );
close( filedes[1] );
}
else
{
printf( "This is in the child process,here read a string from the pipe.\n" );
read( filedes[0], buf, sizeof(buf) );
printf( "%s\n", buf );
close( filedes[0] );
close( filedes[1] );
}

waitpid( pid, NULL, 0 );

return 0;
}

函数输出结果:

This is in the child process,here read a string from the pipe.
This is in the father process,here write a string to the pipe.
Hello world , this is write by pipe.

函数实例(二)使用dups文件重定向和父子进程的数据交互:
在shell命令下输入:
#cat file | grep "string"
grep 命令将使用cat命令的输出作为自己的输入,这个就是简单的用管道实现文件重定向的例子。
为了实现父子进程间的管道,我们需要将父进程的标准输出重定向到管道的输入端,将子进程的标准输入重定向到管道的标准输出端,这样父进程的输出就可以作为子进程的输入来使用了。

实现文件重定向:
只需要将管道的输入端(输出端)复制到文件描述符0(1)即可

  dup2(fd1, 0);   /* 复制fd1到文件描述符0中,更改标准输入为fd1,这里fd1应为管道的输入端 */

  dup2(fd2, 1);   /* 复制fd2到文件描述符1中,更改标准输出为fd2,这里fd2应为管道的输出端 */

  dup2(fd3, 2);   /* 复制fd3到文件描述符2中,更改标准错误输出为fd3 */

看一个例子:

#include <unistd.h>
#include <stdio.h>
int main()
{
int fildes[2];
pid_t pid;
int i, j;
char buf[256];
if (pipe(fildes) < 0 || (pid = fork()) < 0) /* 创建管道和子进程 */
{
fprintf(stderr, "error!n");
return 1;
}
if (pid == 0)

    {
close(fildes[1]);                  
dup2(fildes[0], 0);                
close(fildes[0]);
gets(buf);                        
fprintf(stderr, "child:[%s]n", buf);
return 2;
}
close(fildes[0]);
dup2(fildes[1], 1);                  
close(fildes[1]);
puts("Hello!");                       
return 0;                          
}

在上例中,父进程的输出被重定向到管道输入端,子进程从管道的输出端读数据。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值