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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With