无名管道
#include <unistd.h>
int pipe(fd[2]);
特点
- 单机通信,适用于亲属进程(父子、兄弟进程);<子进程拷贝了父进程的fd>
- 半双工,具有固定的读端和写端(fd[0]-读,fd[1]-写);
- 特殊文件,不属于任何文件系统,但是依赖于文件系统,存在于内/外存,可用普通i/o函数read(),write()进行操作;
- 基于数据流,有大小限制—4K(查询命令:ulimit -a)
- 同一时间。数据流单向,read完之后数据就没了
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
// int pipe(int pipefd[2]);
int main()
{
int fd[2];
pid_t pid;
char buff[1024]={0};
if(pipe(fd)==-1){//创建管道
printf("create pipe failed\n");
}
pid = fork();//创建子进程
if(pid<0){
printf("create child proess error\n");
perror("");
exit(-1);
}
if(pid>0){
printf("this is father process,pid = %d\n",getpid());
close(fd[0]);
write(fd[1],"message from father",strlen("message from father"));
wait();//等待子进程结束
}else if(pid == 0){
printf("this is child process,pid = %d\n",getpid());
close(fd[1]);
read(fd[0],buff,1024);
printf("%s\n",buff);
exit(0);
}
close(fd[0]);
close(fd[1]);
return 0;
}
命名管道
FIFO,也称命名管道。
特点:
1.它是以一种特殊文件类型存在于文件系统(设备文件);
2.它适用于不仅限于亲属进程间的通信;
3.FIFO(first in first out)按照先进先出的原则工作,先被写入的先被读出。
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <error.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
//路径 权限
//int mkfifo(const char *pathname, mode_t mode);
int main()
{ //创建管道文件
if(mkfifo("./file",0600)==-1 && errno != EEXIST){
printf("mkfifo error\n");
exit(-1);
}
//打开管道文件
int fd = open("./file",O_WRONLY);
if(fd == -1){
printf("open filure\n");
exit(-1);
//写入传递的信息
}else if( write(fd,"hello",strlen("hello")) == -1){
printf("write filure\n");
}else
printf("write success\n");
//关闭管道
close(fd);
return 0;
}
创建管道后“写端”进程会堵塞,等待另外一个进程读出数据
int main()
{
//创建缓冲区
char buf[256]={0};
//以只读权限打开管道文件
int fd = open("./file",O_RDONLY);
if(fd == -1){
printf("open filure\n");
exit(-1);
}
//初始化缓冲区
memset(buf,'\0',sizeof(buf));
//将管道文件里的内容读到缓冲区
read(fd,buf,sizeof(buf));
printf("read from FIFO: %s\n",buf);
close(fd);
return 0;
}
管道文件里的内容读完之后就某有了