示例代码1:
comm.h
#ifndef __COMM_H_
#define __COMM_H_
#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#define PATHNAME "."
#define PROJ_ID 0X6666
int createshm(int sz);//创建
int destroyshm(int shmid);//销毁
int getshm(int sz);//获得
#endif//__COMM_H_
common.cpp
#include "comm.h"
static int commshm(int sz,int flag)
{
key_t key = ftok(PATHNAME,PROJ_ID);
if(key < 0){
perror("ftok");
return -1;
}
int shmid=0;
if((shmid=shmget(key,sz,flag)) < 0){
perror("shmget");
return -2;
}
return shmid;
}
int destroyshm(int shmid)
{
if(shmctl(shmid,IPC_RMID,NULL)<0){
perror("shmctl");
return -1;
}
return 0;
}
int createshm(int sz)
{
return commshm(sz,IPC_CREAT|IPC_EXCL|0666);
}
int getshm(int sz)
{
return commshm(sz,IPC_CREAT);
}
server.cpp
#include "comm.h"
#include <unistd.h>
int main()
{
int shmid=createshm(4096);
printf("server:the shmid is %d!\n",shmid);
char* addr=(char*)shmat(shmid,NULL,0);
sleep(2);
int i=0;
while(i++<26){
printf("client# %s\n",addr);
sleep(1);
}
shmdt(addr);
sleep(2);
destroyshm(shmid);
return 0;
}
client.cpp
#include"comm.h"
#include <unistd.h>
int main()
{
int shmid=getshm(4096);
printf("client:the shmid is %d!\n",shmid);
sleep(1);
char* addr=(char*)shmat(shmid,NULL,0);
sleep(2);
int i=0;
while(i<26){
addr[i] = 'A'+i;
i++;
addr[i] = 0;
sleep(1);
}
shmdt(addr);
sleep(2);
return 0;
}
编译所用的Makefile
.PHONY:all
all:server client
client:client.cpp comm.cpp
gcc -o $@ $^
server:server.cpp comm.cpp
gcc -o $@ $^
.PHONY:clean
clean:
rm -f client server
分别运行server和client文件。
注意:
1、段错误 (核心已转储)错误,原因是共享内存没有释放;
解决办法是:
a、ipcs -m 查看共享内存状况,找到对应的shmid号为3178510
------------ 共享内存段 --------------
键 shmid 拥有者 权限 字节 连接数 状态
0x0000000 1376256 iflytek-dy 600 524288 2 目标
0x00000000 327681 iflytek-dy 600 524288 2 目标
0x00000000 524290 iflytek-dy 600 524288 2 目标
0x00000000 557059 iflytek-dy 600 16777216 2
0x00000000 720900 iflytek-dy 600 524288 2 目标
0x00000000 884741 iflytek-dy 600 524288 2 目标
0x00000000 1114118 iflytek-dy 600 524288 2 目标
0x00000000 950279 iflytek-dy 600 16777216 2 目标
0x00000000 1277960 iflytek-dy 600 524288 2 目标
0x00000000 1409033 iflytek-dy 600 33554432 2 目标
0x00000000 1507338 iflytek-dy 600 524288 2 目标
0x00000000 1540107 iflytek-dy 600 4194304 2 目标
0x00000000 1671180 iflytek-dy 600 524288 2 目标
0x00000000 3112973 iflytek-dy 600 2097152 2 目标
0x66281cdd 3178510 iflytek-dy 0 4096 0
b、ipcrm -m 3178510 清除当前共享内存id
上面的方式没有使用信号量,下面是使用信号量的例子,以达到同步:
https://download.csdn.net/download/sinat_35706094/10968933
参考:
https://blog.csdn.net/jinzhilong580231/article/details/36686589
https://blog.csdn.net/dove1202ly/article/details/79962889
https://blog.csdn.net/qq_40946787/article/details/78754690