IPC (interprocess communication) ---- pipeline

IPC method (interprocess communication)

(1)管道(使用最简单):pipe,匿名管道,不可反复读     /  fifo  有名管道,可以反复读(用于非血缘关系进程间通信)
	原理:内核缓冲区机制,环形队列形式实现
	局限性:   1.进程不能自己读自己写
		2.数据不能反复读
		3.单向通信,半双工
		4.只能用与有公共的祖先进程间
(2)信号(开销最小)
(3)共享内存(无血缘关系):mmap-------munmap(释放分配出来的共享内存,一定要从首地址开始释放)
	void *mmap(void *addr, size_t length, int prot, int flags int fd, off_t offset )
	返回值:成功返回创建映射去的首地址,失败返回MAP_FAILED宏
	参数:   1.add,建立映射区的首地址,由内核指定,使用时直接NULL;
	             2.length, 欲创建映射区的大小
	             3.prot,映射区权限,PROT_READ,PROT_WRITE,PROT_READ | PROT_WRITE
	             4.flags, 标志为参数,MAP_SHARED(将映射区 所做的操作反映到磁盘上)
			            MAP_PRIVATE(映射区所作的修改不会反映到磁盘上)
	             5.fd, 用来建立映射区的文件描述符(文件必须读写打开,因为4会通过共享内存往磁盘上写)
	             6.映射文件的偏移量(4K的整数倍)
(4)本地套接字(最稳定)

Using simple communication pipe

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<string.h>
  4 #include<unistd.h>
  5 int main()
  6 {
  7         int fd[2];
  8         pid_t pid;
  9 
 10 
 11 
 12         int ret = pipe(fd);
 13         if(ret == -1)
 14         {
  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<string.h>
  4 #include<unistd.h>
  5 int main()
  6 {
  7         int fd[2];
  8         pid_t pid;
  9 
 10 
 11 
 12         int ret = pipe(fd);
 13         if(ret == -1)
 14         {
 15                 perror("pipe error");
 16                 exit(1);
 17         }
 18 
 19         pid = fork();
 20         if(pid == -1)
 21         {
 22                 perror("fork error");
 23                 exit(1);
 24         }
 25         else if(pid == 0)
 26         {
 27                 sleep(3);
 28                 close(fd[1]);
 29                 char buff[1024]={0};
 30                 int ret = read(fd[0],buff,sizeof(buff));
 31                 if(ret == 0)
 32                 {
 33                         printf("child finish\n");
 34                 }
 35                 write(STDOUT_FILENO,buff,ret);
 36         }
 37         else
 38         {
 39                 close(fd[0]);
 40                 write(fd[1],"pipe hello\n",strlen("pipe hello\n"));
 41         }
 42 
 43         return 0;
 44 }
      
Published 38 original articles · won praise 13 · views 4335

Guess you like

Origin blog.csdn.net/YanWenCheng_/article/details/103930059