将数组写入共享内存

时间:2019-03-28 23:49:27

标签: c arrays char shared-memory

当我尝试向共享内存写入1GB阵列时出现细分错误。当我减小尺寸时,它运行良好。

这是怎么回事?顺序写是不是很麻烦?

  • @author Silberschatz,Galvin和Gagne
  • 操作系统概念-第九版
  • John Wiley&Sons版权所有-2013
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
int main()
{
    const int SIZE = 1024*1024*1024;
    const char *name = "shared_memory";

    int shm_fd;
    char *ptr, *start;

    shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);

    /*shm_open: cria ou abre um objeto de
    memória compartilhado.

    /* O tamanho inicial de um segmento é de 0 bytes.
    A função "ftruncate" define o tamanho do
    segmento.*/
    ftruncate(shm_fd,SIZE);


    ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (ptr == MAP_FAILED) {
        printf("Map failed\n");
        return -1;
    }
    /*Escreve na memória compartilhada.*/
    start = ptr;
    sprintf(ptr,"Hello: ");
    ptr += 7; //Move o ponteiro
    int c;
    for (c = 0; c <= SIZE; c++,ptr++)
            *ptr = 97 + rand() % (123-97);
    *ptr = '\0';
    ptr++;
    *ptr=10;

    //memcpy(ptr,"conteudo",tamanho);
    return 0;
}

0 个答案:

没有答案