Re: light weight user level semaphores

Ulrich Drepper
2001-04-19T20:08:19Z

Alan Cox <alan@lxorguk.ukuu.org.uk> writes:

> mknod foo p. Or use sockets (although AF_UNIX sockets are higher latency)
> Thats why I suggested using flock - its name based. Whether you mkstemp()
> stuff and pass it around isnt something I care about
>
> Files give you permissions for free too

I don't want nor need file permissions. A program would look like this:

process 1:

fd = open("somefile")
addr = mmap(fd);

pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);

pthread_mutex_init ((pthread_mutex_t *) addr, &attr);

pthread_mutex_lock ((pthread_mutex_t *) addr);

pthread_mutex_destroy((pthread_mutex_t *) addr);

process 2:

fd = open("somefile")
addr = mmap(fd);

pthread_mutex_lock ((pthread_mutex_t *) addr);

The shared mem segment can be retrieved in whatever way. The mutex in
this case is anonymous. Everybody who has access to the shared mem
*must* have access to the mutex.

For semaphores it looks similarly. First the anonymous case:

process 1:

fd = open("somefile")
addr = mmap(fd);

sem_init ((sem_t *) addr, 1, 10); // 10 is arbitrary

sem_wait ((sem_t *) addr);

sem_destroy((sem_t *) addr);

process 2:

fd = open("somefile")
addr = mmap(fd);

sem_wait ((sem_t *) addr);

Note that POSIX semaphores could be implemented with global POSIX
mutexes.

Finally, named semaphores:

semp = sem_open("somefile", O_CREAT|O_EXCL, 0600)

sem_wait (semp);

sem_close(semp);
sem_unlink(semp);

This is the only semaphore kind which maps nicely to a pipe or socket.
All the others don't. And even for named semaphores it is best to
have a separate name space like the shmfs.

> So you have unix file permissions on them ?

See above. Permissions are only allowed for named semaphores.

--
---------------. ,-. 1325 Chesapeake Terrace
Ulrich Drepper \ ,-------------------' \ Sunnyvale, CA 94089 USA
Red Hat `--' drepper at redhat.com `------------------------