共享内存是不同进程间通过访问同一段逻辑内存,实现数据共享,非常方便。下面是一个简单实例
在share_write.c中
#include#include #include #include #include int main(int argc, char *argv[]) { int shmid = 0; int share_len = 64; void *shm = NULL; shmid = shmget((key_t)1000, share_len, 0666 | IPC_CREAT); if (shmid == -1) { printf("shmget failn"); } shm = shmat(shmid, 0, 0); if (shm == (void *) - 1) { printf("shmat failn"); } strcpy(shm, "TEST"); printf("Contents of share memory: %sn", shm); if (shmdt(shm) == -1) { printf("shmdt failn"); } return 0; }
在share_read.c中
#include#include #include #include #include int main(int argc, char *argv[]) { int shmid = 0; int share_len = 64; void *shm = NULL; shmid = shmget((key_t)1000, share_len, 0666 | IPC_CREAT); if (shmid == -1) { printf("shmget failn"); } shm = shmat(shmid, 0, 0); if (shm == (void *) - 1) { printf("shmat failn"); } printf("Contents of share memory: %sn", shm); if (shmdt(shm) == -1) { printf("shmdt failn"); } if (shmctl(shmid, IPC_RMID, 0) == -1) { printf("shmctl failn"); } return 0; }
示例说明share_write向共享内存段写入数据,share_read读出共享内存段数据,运行结果如下
示例中涉及的几个函数
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); //根据标识符shmid执行cmd控制 *** 作,如销毁分配的共享内存段
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)