一、管道的分类
管道分为匿名管道和命名管道。
匿名管道:
(1)、在关系进程中进行(父进程和子进程、兄弟进程之间)
(2)、由pipe系统调用,管道由父进程建立。
(3)、 管道位于内核空间、其实是一块缓存。
命名管道:
(1)、任何两个进程间都可通过命名管道进行数据传输。
(2)、通过系统调用mkfifo创建。
(3)、本质是内核中的一块缓存,另外在文件系统中以一个特殊的设备文件(管道文件)存在。
二、本篇主要讲匿名管道:
管道创建:
#include <unistd.h>
int pipe(int fd[2]);
返回: 成功返回0,出错返回-1;
fd[0]: 为pipe的读端
fd[1]:为pipe的写端
三、管道创建和读写代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
int main()
{
int fd[2];
pid_t pid;
//管道创建成功后,fd[0]是读管道,fd[1]是写管道
if(pipe(fd) < 0)
{
printf("pipe error\n");
exit(-1);
}
if((pid = fork())< 0)
{
printf("fork error\n");
exit(-1);
}
if(pid == 0)//子进程
{
close(fd[0]);//子进程关掉读管道
printf("child process\n");
int start = 1,end = 100;
write(fd[1],&start,sizeof(start));
write(fd[1],&end,sizeof(end));
exit(0);
}
else
{
printf("parent child\n");
close(fd[1]);//父进程关掉写管道
int start = 0,end = 0;
read(fd[0],&start,sizeof(start));
read(fd[0],&end,sizeof(end));
printf("start=%d,end=%d\n",start,end);
exit(0);
}
return 0;
}
运行结果: