基本概念
共享内存区是最快的IPC形式。一旦这样的内存映射到共享它的进程的地址空间,这些进程间数据传递不再涉及到内核,换句话说是进程不再通过执行进入内核的系统调用来传递彼此的数据。
与消息队列管道的物理区别
用管道或者消息队列传递数据,内核为每个IPC对象维护一个数据结构
用共享内存传递数据
共享内存函数
struct shmid_ds { struct ipc_perm shm_perm; /* Ownership and permissions */ size_t shm_segsz; /* Size of segment (bytes) */ time_t shm_atime; /* Last attach time */ time_t shm_dtime; /* Last detach time */ time_t shm_ctime; /* Last change time */ pid_t shm_cpid; /* PID of creator */ pid_t shm_lpid; /* PID of last shmat(2)/shmdt(2) */ shmatt_t shm_nattch; /* No. of current attaches */};
#include <sys/ipc.h> #include <sys/shm.h> int shmget(key_t key, size_t size, int shmflg);创建共享内存
void *shmat(int shmid, const void *shmaddr, int shmflg);将共享内存段连接到进程地址空间
int shmdt(const void *shmaddr);
将共享内存段从进程空间中脱离
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
用于控制共享内存
写入共享内存内容
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> struct msg {char line[10]; }; int main(int argc, char *argv[]) { int shmid; shmid=shmget(0x1222,sizeof(struct msg),0666|IPC_CREAT); if(shmid==-1) {printf("create share memory failed!\n"); exit(0); } struct msg *p=NULL; p=shmat(shmid,NULL,0); strcpy(p->line,"hello"); shmdt(p); return 0; }读取共享内存内容
#include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> struct msg {char line[10]; }; int main(int argc, char *argv[]) { int shmid; shmid=shmget(0x1222,sizeof(struct msg),0666|IPC_CREAT); if(shmid==-1) {printf("create share memory failed!\n"); exit(0); } struct msg *p=NULL; p=shmat(shmid,NULL,0); printf("shmid msg is %s\n",p->line); shmdt(p); return 0; }
扫描二维码关注公众号,回复:
1301692 查看本文章