zoukankan      html  css  js  c++  java
  • 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 ", 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 ", 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(" ");
    33         }
    34         printf("%d ", addr[i]);
    35     }
    36     
    37     return 0;

    38 } 

  • 相关阅读:
    关于SQL Server中的DateTime类型和C#中的DateTime类型的一点小记录
    强类型DataSet的使用简明教程2
    byte[]转string的感悟
    ArrayList的Insert方法
    FormsAuthenticationTicket对象
    powerdesigner设置唯一键,但不是主键的方式
    KeyValuePair用法(转)
    如何在安装过程中部署DevExpress控件
    asp.net GridView手写事件,包括取主键、取值、更新、选择、删除
    序列化(Serialize)、反序列化(Deserialize)
  • 原文地址:https://www.cnblogs.com/ym65536/p/4783559.html
Copyright © 2011-2022 走看看