进程之间内存共享
实例代码如下:
服务器端:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #define SHM_SIZE 26
- int main(int argc,char* argv[])
- {
- char* pMem = NULL;
- int shmid = 0;
- int i = 0;
- int retcode = 0;
- key_t key=ftok("/home/root",2);
- shmid = shmget(key, SHM_SIZE, IPC_CREAT|0600);
- if(shmid == -1)
- {
- perror("shmget");
- exit(-1);
- }
- pMem = (char*)shmat(shmid, NULL, 0);
- if(pMem == (char*)-1)
- {
- perror("shmat");
- exit(-1);
- }
- printf("SharedMemory:%p\n",pMem);
- for(i=0;i<SHM_SIZE;i++)
- {
- pMem[i]='a'+i;
- }
- while(pMem[0]!='*')
- sleep(1);
- retcode = shmdt(pMem);
- if(retcode == -1)
- {
- perror("shmdt");
- exit(-1);
- }
- retcode = shmctl(shmid, IPC_RMID, NULL);
- if(retcode == -1)
- {
- perror("shmctl");
- exit(-1);
- }
- return 0;
- }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
客户端:
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/shm.h>
- #define SHM_SIZE 26
- int main(int argc, char* argv[])
- {
- int i = 0;
- char* pMem = NULL;
- key_t key = ftok("/home/root", 2);
- int shmid = shmget(key, SHM_SIZE, 0600);
- if(shmid == -1)
- {
- perror("shmget");
- exit(-1);
- }
- pMem = (char*)shmat(shmid,NULL,0);
- if(pMem == (char*)-1)
- {
- perror("shmat");
- exit(-1);
- }
- printf("Client:SharedMemoryat%p\n", pMem);
- for(i=0; i<SHM_SIZE; i++)
- {
- putchar(pMem[i]);
- }
- putchar('\n');
- pMem[0]='*';
- shmdt(pMem);
-
- return 0;
- }
转载自: http://hi.baidu.com/jiangxun_lin/blog/item/9ae6703244df8abf5fdf0ef9.html
阅读(1265) | 评论(0) | 转发(0) |