共享内存练习

设计两个进程,进程A申请一块共享内存,并向内存中写入数据,进程B从共享内存中读取数据并输出

/********************************************************************************
*
*
* 共享内存练习
* author:jindouliu2024@163.com 
* date:2025.5.8
* 
* Copyright (c)  2024-2025   jindouliu2024@163.com   All right Reserved
* *****************************************************************************/
//进程A
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
	//设置键值
	key_t key = ftok(".",2);
	//创建一块共享内存空间
	int shm_id = shmget(key,256,IPC_CREAT|IPC_EXCL|0644);
	if(shm_id == -1){
		printf("shmget error\n");
		return 1;
	}
	//连接映射空间,并写入数据
	char *shm_map = (char *)shmat(shm_id,NULL,0);
	sprintf(shm_map,"this is shm_a process,id = %d\n",getpid());
	while(1);
	return 0;
}
//进程B

#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main()
{
	//设置键值
	key_t key = ftok(".",2);
	//创建一块共享内存空间
	int shm_id = shmget(key,256,IPC_CREAT|IPC_EXCL|0644);
	if(shm_id == -1){
		printf("shmget error\n");
		shm_id = shmget(key,256,0644);
		
	}
	//连接映射空间,并读取数据
	char *shm_map = (char *)shmat(shm_id,NULL,0);
	printf("%s\n",shm_map);
	//解除映射
	shmdt(shm_map);
	return 0;


}
posted @ 2025-05-08 14:58  LRadian  阅读(43)  评论(0)    收藏  举报