进程间通信(CC++)

进程间通信(C/C++)

// 无名管道
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int main()
{
	int fd[2];
    // 创建无名管道
	int ret = pipe(fd);
	if (ret < 0) {
		perror("pipe error");
		return -1;
	}
    // 产生一个进程
	pid_t pid = fork();
	if (pid < 0) {
		perror("fork error");
	}
	else if (pid > 0) {
        // 父进程来写,写的时候先关闭读端,这里不用担心先执行子进程会执行,因为管道内没有可读的数据会自己阻塞
		close(fd[0]);
		write(fd[1], "cp666", strlen("cp666"));
	}
	else {
        // 读的时候先关闭写端
		close(fd[1]);
		char buf[1024];
        // 数组初始化
		memset(buf, 0*00, sizeof(buf));
		read(fd[0], buf, sizeof(buf));
		printf("%s\n", buf);
	}
	return 0;
}


// 命名管道(写)
// 写就是一个平常的进程往文件里面写东西
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
int main()
{
	// 打开文件获取一个文件描述符
				  //当前目录下要有cp这个文件//以写的方式打开这个文件
	int fd = open("./cp", O_WRONLY);
	if (fd < 0) {
		perror("open error");
		return -1;
	}
	
    // 判断是否写成功
	int ret = write(fd, "cp666", strlen("cp666"));
	if (ret < 0) {
		perror("write error");
	}
	else {
		printf("write success\n");
	}
	close(fd);
	return 0;
}


// 命名管道(读)
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
int main()
{
	// 打开文件
	int fd = open("./cp", O_RDONLY);
	if (fd < 0) {
		perror("open error");
		return -1;
	}
	// 建立管道        文件     权限
	int ret = mkfifo("./cp", 0666);
	if (ret < 0 && errno != EEXIST) {
		perror("mkfifo error");
		return -1;
	}

	char buf[1024];
	memset(buf, 0*00, sizeof(buf));
	int n = read(fd, buf, sizeof(buf));
	if (n < 0) {
		perror("read error");
	}
	else if (n == 0) {
		printf("no data");
	}
	else {
		printf("%s\n", buf);
	}
	
	close(fd);
	return 0;

}




// 共享内存(写)
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int main()
{
	int fd = open("./cp", O_RDWR);
	if (fd < 0) {
		perror("open error");
		return -1;
	}
	// 获得文件长度
	int len = lseek(fd, 0, SEEK_END);
	
	// 获取映射地址
	void* addr = mmap(NULL, len, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);

	// 直接对这个地址进行操作
	memcpy(addr, "cp666", strlen("cp666"));
	close(fd);
	return 0;
};

// 共享内存(读)
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
int main()
{
	int fd = open("./cp", O_RDWR);
	if (fd < 0) {
		perror("open error");
		return -1;
	}
	int len = lseek(fd, 0, SEEK_END);
	void* addr = mmap(NULL, len, PROT_WRITE|PROT_READ, MAP_SHARED, fd, 0);
	
	char* p = (char*)addr;
	printf("%s", p);
	close(fd);
	return 0;
}

进程间的通信管道是一个读端一个写端,其中pipe用于有血缘的进程通信,mkfifo可用于无血缘的进程通信,表面上看是管道操作一个文件,一个去写一个去读,其实在读的过程要将文件从用户态进入内核态,再从内核态到用户态到文件,十分耗时。而共享内存是将文件直接映射到内核,内核到文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值