2

Linux システムで POSIX 共有メモリを使用しようとしています。しかし、そこにデータをコピーしようとすると、バス エラーが発生します。コードは次のとおりです。

#include <fcntl.h>
#include <sys/stat.h>
#include <pthread.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

void main ()
{
    char *s = "a";
    //<!--make file descripter-->
    int fd = shm_open (s, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR);
    if (fd == -1)
    {
        perror ("shm open:");
        printf ("error\n");
        shm_unlink (s);
        exit (1);
    }

    //<!--memory allocation-->
    char *str = (char *)mmap (NULL, 10, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if (str == MAP_FAILED)
    {
        perror ("mmap");
        exit (1);
    }

    *(str + 1) = 'a';   
    //<!--memory deallocation-->
    munmap (str, 10);
    //<!--unlink shared memory-->
    shm_unlink (s);
}

クラッシュする原因は何ですか?

4

1 に答える 1

4

マップしたファイルの末尾を超えてメモリにアクセスしています。スペースを確保するには、ファイルのサイズを拡張する必要があります。の後shm_open()に、次を追加します。

int size = 10; // bytes
int rc = ftruncate(fd, size);
if(rc==-1){ ...; exit(1); }
于 2015-08-20T12:23:35.537 に答える