查看: 25|回覆: 0

共享内存练习

[複製鏈接]

3

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2009-6-25
發表於 2025-5-8 14:58:00 | 顯示全部樓層 |閲讀模式

设计两个进程,进程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;


}


来源:https://www.cnblogs.com/lradian/p/18866339
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部