Reputation: 117
I know that unnamed semaphores should be in shared memory area, but I don't know how to implement because mmap() returns a pointer to the mapped area, and i am obligated to use sem_t pointer, but this time, i think it s not really safe. Here what i did,
sem_t *sem;
char* name = "sharedSem";
int fd;
sem_init(sem, 1, 1);
fd = shm_open(name, O_CREAT | O_RDWR, 0666);
if(fd == -1)
{
perror("fail");
exit(-1);
}
ftruncate(fd, sizeof(sem_t));
sem = (sem_t*) mmap(0, sizeof(sem_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
When i use pointer, also i can't read the value of semaphore, i don't even know if it is possible..
Can i create an unnamed semaphore without sem_t pointer in shared memory area that children processes can also access?
Upvotes: 1
Views: 786
Reputation: 48572
The problem is you're calling sem_init
while sem
is still not pointing anywhere in particular. Move that call to after you point it to the result of mmap
(i.e., to the bottom of the snippet you posted).
Upvotes: 1