I/O重定向和管道

本文详细介绍了如何利用dup、dup2和pipe函数在进程中实现高效的数据传输,通过创建管道和复制文件描述符,使得子进程能够获取到父进程的数据流,实现进程间通信。
 dup,dup2
目标复制一个文件描述符
头文件#include <unistd.h>
函数原型

newfd = dup(oldfd);

newfd = dup2(oldfdm, newfd);

参数

oldfd需要复制的文件描述符

newfd复制oldfd后得到的文件描述符

返回值

-1    发生错误

newfd    新的文件描述符

 

 pipe
目标创建管道
头文件#include <unistd.h>
函数原型

result = pipe(int array[2]);

参数

array包含两个int类型数据的数组

返回值

-1  发生错误

0         成功

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <unistd.h>
 5 #include <fcntl.h>
 6 
 7 int main()
 8 {
 9     int len, i, apipe[2];
10     char buf[BUFSIZ];
11 
12     if (pipe(apipe) == -1)
13     {
14         perror("could not make pipe");
15         exit(1);
16     }
17 
18     printf("Got a pipe! It is file descriptors: {%d %d}\n", apipe[0], apipe[1]);
19 
20     int infd = open("/etc/passwd", O_RDONLY);
21     dup2(infd, 0);
22     int outfd = open("userlist", O_WRONLY);
23     dup2(outfd, 1);
24 
25 
26     while (fgets(buf, BUFSIZ, stdin))
27     {
28         len = strlen(buf);
29         if (write(apipe[1], buf, len) != len)
30         {
31             perror("writing to pipe");
32             break;
33         }
34 /*
35         for (i = 0; i < len; i++)
36         {
37             buf[i] = 'X';
38         }
39 */
40         len = read(apipe[0], buf, BUFSIZ);
41         if (len == -1)
42         {
43             perror("reading from pipe");
44             break;
45         }
46         if (!fputs(buf, stdout))
47         {
48             perror("writing to stdout");
49             break;
50         }
51     }
52 
53     return 0;
54 }

 

转载于:https://www.cnblogs.com/bournet/p/4037643.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值