/* * writeShareM.c * * Created on: 2011-11-20 * Author: snape */ #include <stdio.h> #include <sys/shm.h> #include <unistd.h> #include <string.h> int main(int argc, char **argv) { void say(int, char *); int shmid; int i = 0; char *pshm; char buf[1024]; //shmget第二个参数指定创建的共享内存的大小 say((shmid = shmget(1000, 1024 * 10, 0666 | IPC_CREAT)) < 0, "create share memory"); //shmat for share memory attach //第二个参数和第三个参数指定要映射得物理内存地址 //通常设为是 NULL 0 ,表示要映射得物理内存地址是进程空间得首地址 say((pshm = (char *) shmat(shmid, 0, 0)) == NULL, "attch shm"); printf("input node 0-9\n"); scanf("%d", &i); printf("node is %d\n", i); memset(buf, 0, sizeof(buf)); printf("input data\n"); scanf("%s", buf); memcpy(pshm + i * 1024, buf, 1024); //取消对pshm物理地址得映射(进程结束系统会释放共享内存对物理地址得映射) shmdt for share memory detach //调用该函数,不会删除共享内存对象,而是将该共享内存对象得链接数减1。 shmdt(pshm); return 0; } void say(int flag, char *str) { if (flag) { fprintf(stderr, "[%s] error\n",str); } else { fprintf(stderr, "[%s] success\n",str); } }
/* * rShareM.c * * Created on: 2011-11-20 * Author: snape */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/shm.h> int main(int argc, char **argv) { void say(int, char *); int i; char *pshm; char buf[1024]; int shmid; say((shmid = shmget(1000, 10240, 0666 | IPC_CREAT)) < 0, "create share memory"); say((pshm = (char *) shmat(shmid, 0, 0)) == NULL, "attach shm"); printf("input node 0-9\n"); scanf("%d", &i); printf("node is %d\n",i); memset(buf, 0, 1024); memcpy(buf,pshm+i*1024,1024); fprintf(stderr,"data [%s]\n",buf); shmdt(pshm); return 0; } void say(int flag, char *str) { if (flag) { fprintf(stderr, "[%s] error\n", str); } else { fprintf(stderr, "[%s] success\n", str); } }