Reputation: 368
I am working on the dining philosopher's problem and can't use threads so I need to use shared memory to make the array of chopsticks and philosophers visible to all child processes. I am trying to use mmap, however, my use of mmap is incorrect and I am unsure how to fix it since my argument is an array of ints not an int as per this question. Should I be using a different function to make it in shared memory?
(declared at the global scope)
int chopsticks[5];
int sizeOfSticks=sizeof(int)*5;
void* map = mmap(0,sizeOfSticks,PROT_READ|PROT_WRITE, MAP_SHARED,chopsticks,0);
Upvotes: 2
Views: 4247
Reputation: 4752
The second-to-last argument to mmap()
is a file descriptor, for cases where you're mapping a file into memory. If you just need to allocate some shared memory, then do this instead:
int *chopsticks;
...
chopsticks = mmap(NULL, N_CHOPSTICKS*sizeof(int),
PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED,
-1, 0);
MAP_ANONYMOUS
means the mapping has no corresponding file. Passing 0 for fd
is likely to work too, but -1 might be more portable (see e.g. the mmap(2)
man page on Linux).
The mapping will be inherited by fork(2)
'd child processes.
As a small style side note, you could write N_CHOPSTICKS*sizeof(*chopsticks)
instead of N_CHOPSTICKS*sizeof(int)
. That way the size will still be correct even if you change the type of chopsticks
.
Upvotes: 3