您的位置:首页 > 运维架构 > Linux

Linux IPC之共享内存

2016-06-06 11:25 393 查看
在IPC通信中,共享内存效率最高,以下是经过实验的example:
shared_memory_read.c:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<unistd.h>

#define BUF_SIZE 1024
#define MYKEY 999

int main(int argc, char **argv){

int shmid = 0;
char *shmptr = NULL;

if((shmid = shmget(MYKEY, BUF_SIZE, IPC_CREAT)) == -1){
printf("shmget errors!\n");
fprintf(stderr, "errno number:%d--%s\n", errno ,strerror(errno));
exit(1);
}
shmptr = (char *)shmat(shmid, 0, 0);
if(-1 == (int)shmptr){
printf("shmat error-read!\n");
exit(1);
}
while(1){
printf("==shmptr:%s==\n", shmptr);
if(!strcmp(shmptr, "quit")){
break;
}
memset(shmptr, '\0', BUF_SIZE);
sleep(3);
}
// shmdt(shmptr);
if(shmctl(shmid, IPC_RMID, &shmbuf) != 0){
perror("close shared memory error!\n");
}

return 0;
}
shared_memory_write.c:

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<errno.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>

#define BUF_SIZE 1024
#define MYKEY 999

int main(int argc, char **argv){

int shmid;
char *shmptr;
struct shmid_ds shmbuf;

shmid = shmget(MYKEY, BUF_SIZE, (IPC_CREAT|0777));
if(-1 == shmid){
printf("shmget error!\n");
fprintf(stderr, "Error:%d - %s\n", errno, strerror(errno));
exit(1);
}
shmptr = (char *)(shmat(shmid, 0, 0));
if(-1 == (int)shmptr){
printf("shmat error!\n");
if(shmctl(shmid, IPC_RMID, &shmbuf) < 0){
perror("shmctl error");
fprintf(stderr, "Error:%d - %s\n", errno, strerror(errno));
}
exit(1);
}
strcpy(shmptr, "this is test--read\n");
while(1){
printf("please input:");
scanf("%s", shmptr);
while('\n' != getchar());
if(!strncmp(shmptr, "quit", sizeof("quit"))){
break;
}
}
shmdt(shmptr);
if(shmctl(shmid, IPC_RMID, &shmbuf) < 0){
perror("shmctl error");
}

return 0;
}
例子较为简单,需要的可以拿过去根据项目需要修改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Linux 内存 IPC