linux--进程通信--管道通信

IPC是各种进程间通信方式的统称。

进程间通信:是指在不同进程之间传播或交换信息。

IPC的方式通常有:

单机:管道(包括无名管道和命名管道)、消息队列、信号量、共享存储、

多机:Socket、Streams等

1、管道:通常指无名管道,是UNIX系统IPC最古老的形式。

特点:①它是半双工的(数据只能在一个方向上流动),具有固定的读端和写端。

· ②只能用于具有亲缘关系的进程之间的通信(也就是父子进程或者兄弟进程)

③它可以看成是一种特殊的文件,对于它的读写也可以使用普通的read、write等函数。但是它不是普通的文件,并不属于其他任何文件系统,并且只存在于内存中。

管道api

cpp 复制代码
#include <unistd.h>
 
int pipe(int fd[2]);

fd[0]为读而打开,fd[1]为写而打开 0读1写

要关闭管道,只需要将这两个文件描述符关闭即可close(fd[0]);close(fd[1]);

fork:返回值<0表示创建失败;返回值>0,程序为父进程;返回值=0,程序为子进程;

代码:

cpp 复制代码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>


int main()
{
	int fd[2];
	int pid;
	int status = 10;	
	char buf[1024]= {0};
	if(pipe(fd) == -1){

		printf("creat pipe failed\n");   

	}
	pid = fork();
	if(pid<0){

		printf("creat child failed\n");


	}
	else if(pid >0){
		sleep(3);
//		wait(&status);
		printf("this is father process\n");
//		printf("child quit child status = %d\n",WEXITSTATUS(status));
		close(fd[0]);
		write(fd[1],"qing yuan henshuai from father",strlen("qing yuan henshuai from father"));
		wait(&status);
		printf("child quit child status = %d\n",WEXITSTATUS(status));


	}
	else{

		printf("this is child process\n");
		close(fd[1]);
		read(fd[0],buf,1024);
		printf("read from father:%s\n",buf);
		exit(0);
	}



	return 0 ;
}

结果:

相关推荐
浩浩测试一下10 分钟前
网络安全实战指南:从安全巡检到权限维持的应急响应与木马查杀全(命令查收表)
linux·安全·web安全·ubuntu·网络安全·负载均衡·安全架构
我想吃余32 分钟前
Linux学习笔记(一):Linux下的基本指令
linux·笔记·学习
刘某的Cloud1 小时前
openstack迁移虚机rbd报错,删除异常rbd
linux·运维·openstack·nova·rbd
啊吧怪不啊吧1 小时前
Linux权限概念讲解
linux·运维·服务器
努力努力再努力wz2 小时前
【Linux实践系列】:进程间通信:万字详解命名管道实现通信
android·linux·运维·服务器·c++·c
Zfox_2 小时前
【Shell 脚本入门】轻松上手的实战指南
linux·服务器·运维开发·shell脚本
共享家95272 小时前
Linux调试器 - gdb使用指南
linux
华青水上3 小时前
第一节:Linux系统简介
linux·运维·服务器
每日出拳老爷子3 小时前
[Linux运维] [Ubuntu/Debian]在Lightsail Ubuntu服务器上安装Python环境的完整指南
linux·运维·ubuntu·debian
成工小白3 小时前
【Linux】进程状态
linux·算法