Posix共享内存区的基本操作

shmcreate程序

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>        /* For mode constants */

#define  FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)


int main(int argc, char** argv)
{
    int c, fd, flags;
    char    *ptr;
    off_t   length;

    flags = O_CREAT | O_RDWR;

    while((c = getopt(argc, argv, "e")) != -1)
    {
        switch(c)
        {
            case 'e':
                flags |= O_EXCL;
                break;
        }
    }
    if(optind != argc - 2)
    {
        printf("usage: shmcreate [-e] <name> <length>");
    }
    length = atoi(argv[optind + 1]);

    fd = shm_open(argv[optind], flags ,FILE_MODE);
    ftruncate(fd, length);

    ptr = mmap(NULL, length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);

    exit(0);
}

shmunlink程序

#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char** argv)
{
    if(argc != 2)
    {
        printf("usage: shmunlink <name>");
    }
    shm_unlink(argv[1]);

    exit(0);
}

shmwrite程序

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>

#define  FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)

int main(int argc, char** argv)
{
    int i, fd;
    struct stat stat;
    unsigned char   *ptr;

    if(argc != 2)
    {
        printf("usage: shmwrite <name>");
    }
    fd = shm_open(argv[1], O_RDWR, FILE_MODE);
    fstat(fd, &stat);

    ptr = mmap(NULL, stat.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    close(fd);

    for(i = 0; i < stat.st_size; i++)
    {
        *ptr++ = i % 256; 
    }
    exit(0);
}

shmread程序

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>

#define  FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)


int main(int argc, char** argv)
{
    int i, fd;
    struct stat stat;

    unsigned char c, *ptr;

    if(argc != 2)
    {
        prinf("usage: sharead <name>");
    }

    fd = shm_open(argv[1], O_RDONLY, FILE_MODE);
    fstat(fd, &stat);

    ptr = mmap(NULL, stat.st_size, PROT_READ, MAP_SHARED, fd, 0);
    close(fd);

    for(i - 0; i < stat.st_size; i++)
    {
        if((c = *ptr++) != (i % 256))
        {
            printf("ptr[%d] = %d", i, c);
        }
    }
    exit(0);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值