学习linux pipe无名管道函数

管道:pipe 它把一个进程的输出和另一个进程的输入链接在一起
一个进程(写进程)在***管道尾部***写入数据
一个进程(读进程)在***管道头部***读出数据

管道是内核中的一个单向的数据通道,同时也是一个数据队列。具有一个读取端与一个写入端,每一端对应着一个文件描述符。

管道分为 无名管道pipe 和 命名管道fifo
无名管道只能用于 父进程和子进程之间的通信
命名管道可用于系通间任意两个进程通信

int pipe(int filedis[2]); 创建管道
当一个管道建立时,它会创建两个文件描符

filedis[0] 用于读管道
filedis[1] 用于写管道

关闭管道 只需将两个文件描述符关闭即可 close系统调用就ok

先创建一个管道,在通过fork创建一个子进程,该子进程会继承父进程所创建的管道,必须fork前调用pipe,否则子进程和父进程会各自创建管道,这样起不到管道通信的作用

#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main()
{
int pipe_fd[2];
pid_t pid;
char buf_r[100];
char *w_buf;
int r_num;
int status;

memset(buf_r,0,sizeof(buf_r));

/* 创建管道 */
status = pipe(pipe_fd);
if(-1 == status)
{
	printf("pipe create failed !\n");
	return -1;
}

/* 创建子进程 */
pid = fork();
if(0 == pid)
{
	printf("\n");
	close(pipe_fd[1]);
	sleep(2); /* 为什么要睡眠2秒 */
	/* 睡眠的原因是为了子进程休眠,父进程运行,使得先写入数据 */
	if(r_num=read(pipe_fd[0],buf_r,100) > 0 )
	{
		printf("%d numbers read from the pipe is %s\n",r_num,buf_r);
	}
	close(pipe_fd[0]);
	exit(0);
}
/* 父进程 */
else if(pid > 0)
{
	close(pipe_fd[0]);
	if(write(pipe_fd[1],"hello",5)!=-1)
	printf("parent write Hello \n ");
	
	if(write(pipe_fd[1],"pipe",5)!=-1)
	printf("parent write pipe \n ");
	
	close(pipe_fd[1]);
	waitpid(pid,NULL,0); /* 等待子进程结束 */
	exit(0);
}

运行结果:
./pipe
parent write Hello
parent write pipe

1 numbers read from the pipe is hellopipe

猜你喜欢

转载自blog.csdn.net/shi18363123750/article/details/82948823