SystemV共享内存简介

 

 System V 共享内存区例子:

1、获取共享内存并写入数值 

 1 #include  " network.h "
 2 
 3  int main( int argc,  char *argv[])
 4 {
 5      int len = BLOCK_SIZE;
 6      int shmid =  0;
 7      int* addr = NULL;
 8      struct shmid_ds shmbuf;
 9      int i =  0;
10     key_t key = ftok( " /dev/shm/shm-mamo "' x ');
11     
12      //  create share memory
13      shmid = shmget(key, len, PERM);
14      if (shmid <  0)
15     {
16         perror( " shmget error: ");
17          return - 1;
18     }
19     
20      //  attach, get share memory address
21      addr = shmat(shmid, NULL,  0);
22      if (( int)addr == - 1)
23     {
24         perror( " shmat error: ");
25          return - 1;
26     }
27 
28      //  get shmid_ds struct
29      shmctl(shmid, IPC_STAT, &shmbuf);
30 
31      //  write operation in share memory
32       for (i =  0; i < shmbuf.shm_segsz /  sizeof( int); i++)
33     {
34         addr[i] = i;
35     }
36      for (i =  0; i <  10; i++)
37     {
38         printf( " shmget id=%d, addr=%x, size=%d\n ", shmid, (unsigned  int)addr, shmbuf.shm_segsz);
39         sleep( 60);
40     }
41 
42      //  delete share memory
43      shmctl(shmid, IPC_RMID, NULL);
44     
45      return  0;

46 } 

 

2、读取共享内存

 1 #include  " network.h "
 2 
 3  int main( int argc,  char *argv[])
 4 {
 5      int len = BLOCK_SIZE;
 6      int shmid =  0;
 7      int* addr = NULL;
 8      struct shmid_ds shmbuf;
 9      int i =  0;
10     key_t key = ftok( " /dev/shm/shm-mamo "' x ');
11     
12     shmid = shmget(key, len, PERM);
13      if (shmid <  0)
14     {
15         perror( " shmget error: ");
16          return - 1;
17     }
18     
19     addr = shmat(shmid, NULL,  0);
20      if (( int)addr == - 1)
21     {
22         perror( " shmat error: ");
23          return - 1;
24     }
25     shmctl(shmid, IPC_STAT, &shmbuf);
26 
27     printf( " shmget id=%d, addr=%x, size=%d\n ", shmid, (unsigned  int)addr, shmbuf.shm_segsz);
28      for (i =  0; i < shmbuf.shm_segsz /  sizeof( int); i++)
29     {
30          if ((i &  0x0f) ==  0)
31         {
32             printf( " \n ");
33         }
34         printf( " %d  ", addr[i]);
35     }
36     
37      return  0;

38 } 

 

转载于:https://www.cnblogs.com/ym65536/p/4783559.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值