• 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 } 

  • 相关阅读:
    python,可变参数
    python process,queue
    python 进程池Pool
    python 中的set与list,tuple
    python 元组tuple
    深夜装ubuntu
    python中的协程
    python Queue在两个地方
    (转载)Spring mvc中@RequestMapping 6个基本用法小结
    数据库jdbc连接--【DRP】
  • 原文地址:https://www.cnblogs.com/ym65536/p/4783559.html
Copyright © 2020-2023  润新知