实例——Linux管道pipe的使用
来源:互联网 发布:怎样批量删除淘宝订单 编辑:程序博客网 时间:2024/05/29 07:11
实例——Linux管道pipe的使用
Moakap总结
函数
#include <unistd.h>
int pipe(intfiledes[2]);
描述
pipe()函数创建一个管道和指向该管道的一对文件描述符,并且将文件描述符存储到文件描述符数组filedes[]中。其中filedes[0]为读端,filedes[1]为写端。
返回值
0– 管道创建成功;
-1– 管道创建失败,同时errno置位;
错误指示
EFAULT– 无效的输入参数filedes;
EMFILE– 达到当前进程允许的文件描述符最大值;
ENFILE– 达到系统允许的打开文件的最大数;
实例
下边的例子首先创建一个管道,然后通过fork()创建当先进程的子进程。接着每个进程关闭读写管道不需要的文件描述符。子进程在当前路径下执行“ls –a”命令,通过将管道写描述符fd[1]复制成标准输出,将命令执行输出写到管道;父进程通过fd[0]读取管道数据并显示。
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{
int fd[2];
pid_t pid;
charread_buffer[500] = {0};
int read_count= 0;
int status = 0;
//创建管道
if (pipe(fd) < 0)
{
printf("Create pipe failed.");
return -1;
}
//创建子进程
if ((pid = fork()) < 0)
{
printf("Fork failed.");
return -1;
}
//子进程操作
if (pid == 0)
{
printf("[child]Close read endpoint...");
close(fd[0]); /* 关闭不使用的读 文件描述符 */
//复制fd[1]到标准输出
if (fd[1] != STDOUT_FILENO)
{
if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
{
return -1;
}
//close fd[1],标准输出即为fd[1]
close(fd[1]);
}
//执行命令
status = system("ls –a");
if (status == -1)
{
return -1;
}
}
else
{
printf("[parent]Close write endpoint...");
//父进程 读操作
close(fd[1]); /* 关闭不使用的写 文件描述符 */
//从管道读数据
read_count = read(fd[0], read_buffer, 500);
printf("Content under current directory: /n%s", read_buffer);
}
}
- 实例——Linux管道pipe的使用
- Linux管道pipe使用实例
- linux脚本编程---“|”管道pipe的使用
- Linux Shell 管道命令(pipe)的使用
- pipe管道的使用
- linux操作系统编程——简单的pipe管道
- 管道pipe——Linux学习笔记
- Linux学习笔记——管道PIPE
- linux系统编程——管道pipe
- 管道Pipe的初次使用
- 无名管道pipe的使用
- 无名管道pipe的使用
- 无名管道pipe的使用
- Linux 管道(pipe)原理及使用
- Linux进程通信(一)——pipe管道
- Linux进程间通信——管道 pipe 详解
- linux下的pipe()管道函数
- Linux管道PIPE的原理和应用
- ashx文件
- 详解 Oracle 分布式系统数据复制技术
- 检测和剔除文件名不能兼容的字符
- eclipse3.5 galileo 汉化
- 标题描述是影响百度推广关键字质量度的重要因素
- 实例——Linux管道pipe的使用
- ubuntu操作系统由图形界面转到字符界面
- CUDA优化之七种武器
- 如何利用EnteLib Unity Interception Extension 和PIAB实现Transaction的Call Handler
- 【转帖】让国人脸红!崔永元套出的震撼!
- Lotus Notes email via vbscript
- php常用代码大全
- 个人简历
- preparedStatement和Statement 有什么不一样