16 char *__shm_mapname(const char *, char *);
25 #define FLAGS (O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NONBLOCK)
27 sem_t *sem_open(const char *name, int flags, ...)
32 int fd, i, e, slot, first=1, cnt;
38 char buf[NAME_MAX+10];
40 if (!(name = __shm_mapname(name, buf)))
44 /* Allocate table if we don't have one yet */
45 if (!semtab && !(semtab = calloc(sizeof *semtab, SEM_NSEMS_MAX))) {
50 /* Reserve a slot in case this semaphore is not mapped yet;
51 * this is necessary because there is no way to handle
52 * failures after creation of the file. */
54 for (cnt=i=0; i<SEM_NSEMS_MAX; i++) {
55 cnt += semtab[i].refcnt;
56 if (!semtab[i].sem && slot < 0) slot = i;
58 /* Avoid possibility of overflow later */
59 if (cnt == INT_MAX || slot < 0) {
64 /* Dummy pointer to make a reservation */
65 semtab[slot].sem = (sem_t *)-1;
68 flags &= (O_CREAT|O_EXCL);
70 /* Early failure check for exclusive open; otherwise the case
71 * where the semaphore already exists is expensive. */
72 if (flags == (O_CREAT|O_EXCL) && access(name, F_OK) == 0) {
78 /* If exclusive mode is not requested, try opening an
79 * existing file first and fall back to creation. */
80 if (flags != (O_CREAT|O_EXCL)) {
81 fd = open(name, FLAGS);
83 if ((map = mmap(0, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED ||
94 if (!(flags & O_CREAT))
99 mode = va_arg(ap, mode_t) & 0666;
100 value = va_arg(ap, unsigned);
102 if (value > SEM_VALUE_MAX) {
106 sem_init(&newsem, 1, value);
108 /* Create a temp file with the new semaphore contents
109 * and attempt to atomically link it as the new name */
110 clock_gettime(CLOCK_REALTIME, &ts);
111 snprintf(tmp, sizeof(tmp), "/dev/shm/tmp-%d", (int)ts.tv_nsec);
112 fd = open(tmp, O_CREAT|O_EXCL|FLAGS, mode);
114 if (errno == EEXIST) continue;
117 if (write(fd, &newsem, sizeof newsem) != sizeof newsem || fstat(fd, &st) < 0 ||
118 (map = mmap(0, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
124 if (link(tmp, name) == 0) break;
127 /* Failure is only fatal when doing an exclusive open;
128 * otherwise, next iteration will try to open the
130 if (e != EEXIST || flags == (O_CREAT|O_EXCL))
134 /* See if the newly mapped semaphore is already mapped. If
135 * so, unmap the new mapping and use the existing one. Otherwise,
136 * add it to the table of mapped semaphores. */
138 for (i=0; i<SEM_NSEMS_MAX && semtab[i].ino != st.st_ino; i++);
139 if (i<SEM_NSEMS_MAX) {
140 munmap(map, sizeof(sem_t));
143 return semtab[i].sem;
145 semtab[slot].refcnt = 1;
146 semtab[slot].sem = map;
147 semtab[slot].ino = st.st_ino;
153 int sem_close(sem_t *sem)
157 for (i=0; i<SEM_NSEMS_MAX && semtab[i].sem != sem; i++);
158 if (!--semtab[i].refcnt) {
163 munmap(sem, sizeof *sem);