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, cs;
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 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
72 /* Early failure check for exclusive open; otherwise the case
73 * where the semaphore already exists is expensive. */
74 if (flags == (O_CREAT|O_EXCL) && access(name, F_OK) == 0) {
80 /* If exclusive mode is not requested, try opening an
81 * existing file first and fall back to creation. */
82 if (flags != (O_CREAT|O_EXCL)) {
83 fd = open(name, FLAGS);
85 if (fstat(fd, &st) < 0 ||
86 (map = mmap(0, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
96 if (!(flags & O_CREAT))
101 mode = va_arg(ap, mode_t) & 0666;
102 value = va_arg(ap, unsigned);
104 if (value > SEM_VALUE_MAX) {
108 sem_init(&newsem, 1, value);
110 /* Create a temp file with the new semaphore contents
111 * and attempt to atomically link it as the new name */
112 clock_gettime(CLOCK_REALTIME, &ts);
113 snprintf(tmp, sizeof(tmp), "/dev/shm/tmp-%d", (int)ts.tv_nsec);
114 fd = open(tmp, O_CREAT|O_EXCL|FLAGS, mode);
116 if (errno == EEXIST) continue;
119 if (write(fd, &newsem, sizeof newsem) != sizeof newsem || fstat(fd, &st) < 0 ||
120 (map = mmap(0, sizeof(sem_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED) {
126 e = link(tmp, name) ? errno : 0;
129 /* Failure is only fatal when doing an exclusive open;
130 * otherwise, next iteration will try to open the
132 if (e != EEXIST || flags == (O_CREAT|O_EXCL))
136 /* See if the newly mapped semaphore is already mapped. If
137 * so, unmap the new mapping and use the existing one. Otherwise,
138 * add it to the table of mapped semaphores. */
140 for (i=0; i<SEM_NSEMS_MAX && semtab[i].ino != st.st_ino; i++);
141 if (i<SEM_NSEMS_MAX) {
142 munmap(map, sizeof(sem_t));
143 semtab[slot].sem = 0;
147 semtab[slot].refcnt++;
148 semtab[slot].sem = map;
149 semtab[slot].ino = st.st_ino;
151 pthread_setcancelstate(cs, 0);
155 pthread_setcancelstate(cs, 0);
157 semtab[slot].sem = 0;
162 int sem_close(sem_t *sem)
166 for (i=0; i<SEM_NSEMS_MAX && semtab[i].sem != sem; i++);
167 if (!--semtab[i].refcnt) {
172 munmap(sem, sizeof *sem);