使用共享内存实现Linux进程通信

我们通过共享内存的技术实现进程间的通信,刚开始定义两个文件,读进程从输入文件intput中读取数据,并将其放入共享内存中,然后写进程将共享内存中的数据输出到输出文件output中。程序比较简单,因此只能实现5个字符的通信。待以后再改进吧。

读进程:

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
	key_t key;
	key = 1234;

	int shm_id = shmget(key, 27, IPC_CREAT|0666);
	if(shm_id == -1)
	{
		perror("shmget error");
		return;
	}
	FILE *fp = fopen("input", "r");
	if(fp == NULL)
	{
		perror("Open file recfile");
		exit(1); 
	}
	char *s = shmat(shm_id, NULL, 0);
	fread(s, sizeof(char), 5, fp );
	fclose(fp);
	if(shmdt(s)==-1)
		perror("detach error");
}





写进程:

#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
	key_t key;
	key = 1234;

	int shm_id;
	shm_id = shmget(key, 27, IPC_CREAT|0666);
	if(shm_id == -1)
	{
		perror("shmget error");
		return;
	}

	char *s = shmat(shm_id, NULL, 0);
	FILE *fp = fopen("output", "w");
	if(fp == NULL)
	{
		perror("Open file recfile");
		exit(1); 
	}
	fwrite(s, sizeof(char), 5, fp);
	fclose(fp);
	if(shmdt(s)==-1)
		perror("detach error");
}



 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值