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;
    }
    
  • 相关阅读:
    字符串提取数字/汉字/英文字母
    CHARINDEX,PATINDEX,STUFF函数
    raiserror的用法
    数据库备份与还原(通过命令)
    查询某个字段属于哪些表
    设备驱动基础1:设备模型之总线,驱动,设备
    设备模型之kobject,kset及其关系
    模拟电路创新设计
    cdev、udev
    PCB阻抗调节
  • 原文地址:https://www.cnblogs.com/Sico2Sico/p/5384210.html
Copyright © 2011-2022 走看看