Linux 文件形式的shared memory代码示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024  /* make it a 1K shared memory segment */

int main(int argc, char *argv[])
{
    key_t key;
    int shmid;
    char *data;
    int mode;

    if (argc > 2) {
        fprintf(stderr, "usage: shmdemo [data_to_write]\n");
        exit(1);
    }

    /* make the key: */
    if ((key = ftok("hello.txt", 'R')) == -1) /*Here the file must exist */ 
{
        perror("ftok");
        exit(1);
    }

    /*  create the segment: */
    if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
        perror("shmget");
        exit(1);
    }

    /* attach to the segment to get a pointer to it: */
    if ((data = shmat(shmid, NULL, 0)) == (void *)-1) {
        perror("shmat");
        exit(1);
    }

    /* read or modify the segment, based on the command line: */
    if (argc == 2) {
        printf("writing to segment: \"%s\"\n", argv[1]);
        strncpy(data, argv[1], SHM_SIZE);
    } else
        printf("segment contains: \"%s\"\n", data);

    /* detach from the segment: */
    if (shmdt(data) == -1) {
        perror("shmdt");
        exit(1);
    }

    return 0;
}
  1. Use ftok to convert a pathname and a project identifier to a System V IPC key

  2. Use shmget which allocates a shared memory segment

  3. Use shmat to attache the shared memory segment identified by shmid to the address space of the calling process

  4. Do the operations on the memory area

  5. Detach using shmdt

 

相关推荐

  1. Linux 文件形式shared memory代码示例

    2024-06-13 09:36:08       32 阅读
  2. linuxWget命令下载文件示例

    2024-06-13 09:36:08       35 阅读
  3. vue中.ts文件和.js文件区别及代码示例

    2024-06-13 09:36:08       37 阅读
  4. Linux 文件搜索大师:掌握 find 命令艺术与示例

    2024-06-13 09:36:08       45 阅读
  5. RepidJson将内容写入文件简单代码示例

    2024-06-13 09:36:08       55 阅读
  6. 策略模式代码实践示例

    2024-06-13 09:36:08       42 阅读
  7. Vuex插件机制代码示例

    2024-06-13 09:36:08       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-06-13 09:36:08       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-06-13 09:36:08       100 阅读
  3. 在Django里面运行非项目文件

    2024-06-13 09:36:08       82 阅读
  4. Python语言-面向对象

    2024-06-13 09:36:08       91 阅读

热门阅读

  1. angular编程规范

    2024-06-13 09:36:08       24 阅读
  2. ambari打包

    2024-06-13 09:36:08       27 阅读
  3. Vue常用命令

    2024-06-13 09:36:08       28 阅读
  4. Prometheus 监控系统

    2024-06-13 09:36:08       21 阅读
  5. 未来汽车网络安全行业发展趋势分析

    2024-06-13 09:36:08       34 阅读