读书人

Linux C编程-进程间通信(IPC)5-Syst

发布时间: 2013-03-06 16:20:31 作者: rapoo

Linux C编程--进程间通信(IPC)5--System V IPC 机制3--共享内存

共享内存

最为高效的进程间通信方式

Linux C编程-进程间通信(IPC)5-System V IPC 机制3-共享内存

Linux C编程-进程间通信(IPC)5-System V IPC 机制3-共享内存

Linux C编程-进程间通信(IPC)5-System V IPC 机制3-共享内存

Linux C编程-进程间通信(IPC)5-System V IPC 机制3-共享内存

下面给出几个实例说明上述函数的相关用法。

1.用shmget函数编制一个创建或打开一块新共享内存的函数

#include <sys/types.h>#include <sys/ipc.h>#include <sys/shm.h>#include <stdio.h>char array[4000];int main(){int shmid;char *ptr, *shmptr;printf("array[] form %x to %x \n",&array[0],&array[3999]);printf("stack around %x \n", &shmid);if((ptr=malloc(10000))==NULL){printf("malloc failed.\n");exit(1);}if((shmid=shmget(IPC_PRIVATE,10000,SHM_R|SHM_W))<0){printf("shmget failed.\n");exit(2);}if((shmptr=shmat(shmid,0,0))==-1){printf("shmat failed.\n");exit(3);}printf("shared memory attached from %x to %x \n",shmptr,shmptr-10000);if(shmctl(shmid,IPC_RMID,0)<0){printf("shmctl failed.\n");exit(4);}return 0;}


读书人网 >系统运维

热点推荐