Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read from standard input into mmap

Tags:

c

I have this loop that reads from standard input into the array

int* arr;
arr = malloc(sizeof(int)*size);
for (i = 0; i < size; i++)
{
    read(0, &arr[i], 4);
}

How can I make it work if arr is a shared memory pointer arr=createSharedMemory(sizeof(int)*size)

int* createSharedMemory(size_t size) {
    int protection = PROT_READ | PROT_WRITE;
    int visibility = MAP_ANONYMOUS | MAP_SHARED;
    return (int*)mmap(0, size, protection, visibility, 0, 0);
}

currently it Segmentation Faults

like image 975
AskingMyselfWhy Avatar asked Sep 07 '25 11:09

AskingMyselfWhy


1 Answers

Check your return from mmap().

You tried to mmap() stdin. Barring exotic environments, stdin is some kind of terminal or pipe, neither of which support memory mapped IO.

Try this sample:

int* createSharedMemory(size_t size) {
    int protection = PROT_READ | PROT_WRITE;
    int visibility = MAP_ANONYMOUS | MAP_SHARED;
    int *p = (int*)mmap(0, size, protection, visibility, -1, 0);
    if (p == (int*)(ptrdiff_t)-1) return NULL;
    return p;
}

arr = createSharedMemory(sizeof(int)*size);
if (arr == NULL) {
    perror("mmap");
    exit(3);
}

Incidentally, your read loop will explode if sizeof(int) < 4 which is unlikely.

like image 118
Joshua Avatar answered Sep 09 '25 18:09

Joshua