Linux 进程通信学习1-管道
2016-11-07 21:57
183 查看
*进程通信的目的:1、进程间数据传输2、进程之间资源共享3、进程通知事件,发送消息4、进程的控制,一个进程完全控制另一个进程如debug进程。*名词解释:IPC(interprocess comunication) 进程间通信POSIX 可移植的操作系统接口*Linux进程间通信的7种主要方式:无名管道pipe、有名管道FIFO,信号signal、消息队列、共享内存、、信号量、套接字socket*管道通信 一个进程在尾部写入数据另一个进程从管道头部读出数据。 无名管道:只能用于父进程和子进程间的通信。 有名管道: 运行于同一系统的任意两个进程间的通信。 特点: 管道通信是单向的,有固定的读端口和写端。 数据被进程读出后,管道中的数据就不存在了 进程读取空管道的时候,进程会阻塞。 当进程像满管道写入数据的时,进程会阻塞。 管道的容量为64KB(../include/linux/pipe_fs_i.h) #define ..buffer 16 //16*4kb >无名管道: 无名管道被创建后等同于操作文件,读端被视为一个文件,在写端也被视为一个文件。 无名管道:只能用于父进程和子进程间的通信。 创建无名管道: int pipe(int pipefd[2]); // 成功返回0,失败返回-1 pipefd[0],返回2个文件描述符中的读端,pipefd[1],返回2个文件描述符中的写端, *注意需要在fork之前创建管道。 关闭管道:close 读管道:read 写管道:write 程序例子:
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<stdio.h> #include <stdlib.h> void main() { pid_t pid; int pipefd[2]; char buf[10]; pipe(pipefd);//先创建一个管道 pid=fork();//创建一个进程 if(pid>0) //父进程 { write(pipefd[1],"hello",6);//写管道 wait();//wait for read close(pipefd[1]);//关闭 exit(0); } if(pid==0) //子进程 { read(pipefd[0],buf,6); printf("%s\n",buf); close(pipefd[0]); exit(0); } }>有名管道 FIFO|pipe区别: 读取fifo文件的进程只能一只读的方式打开。 写fifo文件的进程只能以只写的方式打开。 数据被进程读出后,管道中的数据就不存在。 创建有名管道: int mkfifo(const char * pathname,mode_t mode);//创建一个fifo 文件(有名管道) pathname:要创建文件的名字-含路径 mode:创建文件的权限 删除有名管道 int unlink(const char * pathname); 打开open 写 write 读read 关闭 close
//write.c #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<stdio.h> #include <stdlib.h> void main() { int fd; mkfifo("/tmp/myfifo",0666);//先创建一个管道 fd=open("/tmp/myfifo",WRONLY);//先创建一个管道</span> write(fd,"hello",6);//写管道,当写入的时候没有读进程会进入阻塞 close(fd);//关闭 } //read.c #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include<stdio.h> #include <stdlib.h> void main() { int fd; char buf[15]; fd=open("/tmp/myfifo",WRONLY);//先创建一个管道</span> read(fd,buf,6);//写管道 printf("%s\n",buf); close(fd);//关闭 unlink("/tmp/myfifo");//删除管道</span> }
相关文章推荐
- linux学习笔记-读《Linux编程技术详解》(10)-管道与命名管道
- 嵌入式linux的学习笔记-标准文件流管道与命名管道(三)
- linux学习入门17——LINUX多命令协作、管道及重定向(linuxcast.net)
- Linux学习笔记24——进程管道
- Linux进程通信(1):管道(上)
- 短期快速学习LINUX,涉及vi用法,管道,标准输入、输出和错误,grep 用法
- Linux学习记录--管道命令
- linux 管道学习
- linux 学习之管道
- Linux学习(五)--文件权限,信息显示,管道,重定向
- 嵌入式linux的学习笔记-pipe管道(二)
- [linux学习笔记]第3天:变量分类,重定向,管道命令,程序执行流,文本处理类命令, 正则表达式,短路操作符
- 实例学习Linux进程通信(一)
- linux管道学习
- Linux 变干边学 学习笔记之Linux进程、管道和重定向命令
- Linux进程线程学习笔记:进程间通信 之 管道
- linux管道学习资料
- 学习 Linux,101: 流、管道和重定向(转,合)
- Linux进程间通信IPC学习笔记之有名管道
- Linux学习记录--管道命令