zoukankan      html  css  js  c++  java
  • Linux _share 内存共享 demo

    main_r.c

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    #define SHM_SIZE  100
    
    int main(void)
    {
        int shmid;
        char buff[SHM_SIZE];
        void *shmadr;
        int ret;
    
        shmid = shmget((key_t)12345, SHM_SIZE, 0666|IPC_CREAT);
        if (shmid == -1) {
            printf("creat share memory failed!
    ");
            exit(1);
        }
    
        shmadr = shmat(shmid, 0, 0);
        if (shmadr == (void*)-1) {
            printf("shmat failed!
    ");
            exit(1);
        }
    
        memset(buff, 0, sizeof(buff));
        memcpy(buff, (char*)shmadr, sizeof(buff));
        printf("get: %s
    ", buff);
    
        ret = shmdt(shmadr);
        if (ret == -1) {
            printf("shmdt failed!
    ");
            exit(1);
        }
    
        return 0;
    }
    

    main_w.c

    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    #include <sys/ipc.h>
    #include <sys/shm.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    #define SHM_SIZE  100
    
    int main(void)
    {
        int shmid;
        char buff[SHM_SIZE];
        void *shmadr;
        int ret;
    
        shmid = shmget((key_t)12345, SHM_SIZE, 0666|IPC_CREAT);
        if (shmid == -1) {
            printf("creat share memory failed!
    ");
            exit(1);
        }
    
        shmadr = shmat(shmid, 0, 0);
        if (shmadr == (void*)-1) {
            printf("shmat failed!
    ");
            exit(1);
        }
    
        strcpy(buff, "hello word!");
        memcpy((char*)shmadr, buff, strlen(buff)+1);
    
        ret = shmdt(shmadr);
        if (ret == -1) {
            printf("shmdt failed!
    ");
            exit(1);
        }
    
        return 0;
    }
    
  • 相关阅读:
    vue-cli快速搭建
    js严格模式下判断数据类型
    js实现本地的图片压缩上传预览
    web端实现图片放大切换显示预览
    swiper.js在隐藏/显示切换时,轮播出现bug的解决办法
    Zepto.js实现fadeIn,fadeOut功能
    ms
    redis 解决秒杀
    单下滑线 事务 锁
    极验
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384210.html
Copyright © 2011-2022 走看看