Linux IPC - Shared memory

http://blog.163.com/muren20062094@yeah/blog/static/161844416201161974646434/

1. Create shared memory

 
int shmget(key_t key, int size, int shmflg);
 
if ((shm_id = shmget (mykey, sizeof (struct sharedbuf), 0600 | IFLAGS)) < 0)
    perror ("shmget");
2. Attach shared memory
 
char *buf = shmat (shm_id, 0, 0);
 
3. Read / Write shared memory
 
sharedbuf->size = size_;
 
memcpy(sharedbuf->buf, mybuf, size_);
 
memcpy(mybuf, sharedbuf->buf, sharedbuf->size); 
 
3. Detach shared memory (optional)
 
shmdt (buf);
 
4. Remove shared memory
 
if (shmctl (shm_id, IPC_RMID, (struct shmid_ds *)0) < 0)
    perror ("shmctl");
 

shmctl

 
  shmctl 删除共享内存:
 
  int shmctl( int shmid , int cmd , struct shmid_ds *buf );
 
  int shmid:是共享内存的ID。
 
  int cmd: 是控制命令,可取值如下:
 
  IPC_STAT 得到共享内存的状态,
 
  IPC_SET 改变共享内存的状态
 
  IPC_RMID 删除共享内存
 
  struct shmid_ds *buf是一个结构体指针。IPC_STAT的时候,取得的状态放在这个结构体中。如果要改变共享内存的状态,用这个结构体指定。
 
  返回值: 成功:0失败:-1
 
  使用例子:
 
  shmctl(shmid,IPC_RMID,NULL);
posted @ 2013-09-16 17:24  小心小意  阅读(483)  评论(0编辑  收藏  举报