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 ;
}

结果:

相关推荐
程序猿编码34 分钟前
一个授予普通进程ROOT权限的Linux内核级后门:原理与实现深度解析
linux·运维·服务器·内核·root权限
小夏子_riotous38 分钟前
openstack的使用——9. 密钥管理服务Barbican
linux·运维·服务器·系统架构·centos·云计算·openstack
六点的晨曦2 小时前
VMware安装Ubuntu的记录
linux·ubuntu
w6100104662 小时前
CKA-2026-Service
linux·服务器·网络·service·cka
HXQ_晴天2 小时前
castor什么时候已有的 .cdh 数据可以直接用,不需要重新从 root 转换?
linux
Mapleay3 小时前
Ubuntu 源的重要性!之 libgmp-dev 无法安装
linux·服务器·windows
Benszen3 小时前
Linux容器:轻量级虚拟化革命
java·linux·运维
念恒123064 小时前
Linux初识
linux·服务器·c++
开开心心就好4 小时前
能把网页藏在Word里的实用摸鱼工具
linux·运维·服务器·windows·随机森林·逻辑回归·excel
Lucis__4 小时前
Linux网络:基于协议栈原理实现UDP通信
linux·网络·udp