IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    加载文件到共享内存

    rock发表于 2014-07-22 17:29:25
    love 0
    自己写的,先记录一下:

    #include
    #include
    #include
    #include
    #include
    #include stat.h><br >#include types.h><br >#include ipc.h><br >#include shm.h><br >
    #define SHM_KEY 0xff110000
    #define BUFF_SIZE 102400 //100k

    int main(int argc, char *argv[])
    {
    int fs;
    int fd;
    int shmid;
    char *shmptr;
    int len;
    char fbuf [BUFF_SIZE];
    struct stat buf;

    fs = stat("index.html", &buf;);
    len = (int) buf.st_size;


    if(-1 != fs){
    printf("file length: %d\n", len);
    }

    if(-1 !=( fd = open("index.html", O_RDONLY))){
    read(fd,fbuf, len);
    }
    close(fd);

    if(-1 != (shmid = shmget(SHM_KEY, 0, 0))){
    if (-1 == shmctl(shmid, IPC_RMID, 0)){
    printf("delete shm error\n");
    exit(1);
    }
    }

    if(-1 == (shmid = shmget(SHM_KEY, len, IPC_CREAT|0600))){
    printf("shmget error!\n");
    exit(1);
    }

    if((shmptr = shmat(shmid, 0, 0)) == (void *) -1){
    printf("shmat error!\n");
    exit(1);
    }
    strncpy(shmptr, fbuf, len);
    shmdt(shmptr);

    return 0;
    }

    读取共享内存内容:
    #include

    #include
    #include
    #include ipc.h><br >#include shm.h><br >
    #define SHM_KEY 0xff110000

    int main(int argc, char *argv[])
    {
    int shmid;
    char *shmptr;

    if(-1 ==(shmid = shmget(SHM_KEY, 0, 0))){
    printf("shmget error!\n");
    exit(1);
    }

    if((shmptr = shmat(shmid, 0, 0)) == (void *) -1){
    printf("shmat error!\n");
    exit(1);
    }

    printf("read from shm:%s \nfile len: %ld\n", shmptr,strlen(shmptr));
    shmdt(shmptr);

    return 0;
    }


沪ICP备19023445号-2号
友情链接