pipe 管道

管道是一种最基本的 IPC 机制,由pipe 函数创建:
#include <unistd.h>

int pipe(int filedes[2]);


调用pipe 函数时在内核中开辟一块缓冲区(称为管道)用于通信,它有一个读
端一个写端,然后通过filedes 参数传出给用户程序两个文件描述符,
filedes[0]指向管道的读端,filedes[1]指向管道的写端(很好记,就像0 是
标准输入1 是标准输出一样)。所以管道在用户程序看起来就像一个打开的文
件,通过read(filedes[0]);或者write(filedes[1]);向这个文件读写数据其

实是在读写内核缓冲区。pipe 函数调用成功返回0,调用失败返回-1。



/*
管道,一段读(hello word)一段写
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define N 1024
#define STR "hello word\n" 

char buf[N];

int main(void)
{
	int fd[2];
	int n = 0;
	pid_t pid;  						//fork 返回值pid_t类型


	if(pipe(fd) == -1){ 				//创建管道
		perror("pipe error");
		exit(1);
	}
	
	pid = fork();

	if(pid == 0){						//son  write
		close(fd[0]);					//关闭读端
/*		if(n == -1){
			perror("read fail");
			exit(1);
		}
*/
	write(fd[1], STR, strlen(STR));		//从STR读大小为strlen(STR)个字节,写到fd[1](写端)
	}else {								//parent read
		close(fd[1]); 					//关闭写端
		n = read(fd[0], buf, 1024);		//fd[0]为读端,从fd[0],读1024个到buf里.
		write(STDOUT_FILENO, buf, n);	//在从buf里读n个字节到标准输出
		wait(NULL);						//回收son
	}

	return 0;
}

/*akaedu@akaedu-G41MT-D3:~/lin/20140830_pipe_进程间通信$ ./a.out 
hello word
*/<pre name="code" class="cpp">
















//使用管道, wc 一段读 一段写
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
	pid_t pid;
	int fd[2];
	
	pipe(fd);
	pid = fork();

	if(pid == 0){
		close(fd[1]);	//子进程从管道中读数据,关闭写端
		dup2(fd[0], STDIN_FILENO);		//让wc从管道中读取数据
		execlp("wc", "wc", "-l", NULL);	//默认从标准读入取数据
	} else {
		close(fd[0]);	//父进程向管道中写数据,关闭读端
		dup2(fd[1], STDOUT_FILENO);		//将ls的结果写入管道中
		execlp("ls", "ls", NULL);		//ls输出结果默认对应屏幕
	}

	return 0;
}



/*akaedu@akaedu-G41MT-D3:~/桌面/T74_system/0830_chp3_process_pipe_myshell$ ./pipe1
13
*/

/*
akaedu@akaedu-G41MT-D3:~/桌面/T74_system/0830_chp3_process_pipe_myshell$ ls -l
总用量 100
-rw------- 1 akaedu akaedu   198  7月  9 08:42 makefile
-rwxrwxr-x 1 akaedu akaedu  8616  9月 11 16:29 pipe
-rwxrwxr-x 1 akaedu akaedu  8450  9月 11 16:29 pipe1
-rw-rw-r-- 1 akaedu akaedu   558  8月 30 11:43 pipe1.c
-rwxrwxr-x 1 akaedu akaedu  8526  9月 11 16:29 pipe2
-rw-rw-r-- 1 akaedu akaedu   558  8月 30 11:54 pipe2.c
-rwxrwxr-x 1 akaedu akaedu  9861  9月 11 16:29 pipe3
-rw-rw-r-- 1 akaedu akaedu   425  7月  9 08:58 pipe3.c
-rwxrwxr-x 1 akaedu akaedu  8727  9月 11 16:29 pipe4
-rw-rw-r-- 1 akaedu akaedu   733  8月 30 01:04 pipe4.c
-rw-rw-r-- 1 akaedu akaedu   381  8月 30 00:38 pipe.c
-rwxrwxr-x 1 akaedu akaedu 10540  9月 11 16:29 shell-c
-rw------- 1 akaedu akaedu  2403  8月 29 22:12 shell-c.c
*/

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值