• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <sys/mman.h>
2 #include <errno.h>
3 #include <fcntl.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <limits.h>
7 #include <pthread.h>
8 
__shm_mapname(const char * name,char * buf)9 char *__shm_mapname(const char *name, char *buf)
10 {
11 	char *p;
12 	while (*name == '/') name++;
13 	if (*(p = __strchrnul(name, '/')) || p==name ||
14 	    (p-name <= 2 && name[0]=='.' && p[-1]=='.')) {
15 		errno = EINVAL;
16 		return 0;
17 	}
18 	if (p-name > NAME_MAX) {
19 		errno = ENAMETOOLONG;
20 		return 0;
21 	}
22 	memcpy(buf, "/dev/shm/", 9);
23 	memcpy(buf+9, name, p-name+1);
24 	return buf;
25 }
26 
shm_open(const char * name,int flag,mode_t mode)27 int shm_open(const char *name, int flag, mode_t mode)
28 {
29 	int cs;
30 	char buf[NAME_MAX+10];
31 	if (!(name = __shm_mapname(name, buf))) return -1;
32 	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
33 	int fd = open(name, flag|O_NOFOLLOW|O_CLOEXEC|O_NONBLOCK, mode);
34 	pthread_setcancelstate(cs, 0);
35 	return fd;
36 }
37 
shm_unlink(const char * name)38 int shm_unlink(const char *name)
39 {
40 	char buf[NAME_MAX+10];
41 	if (!(name = __shm_mapname(name, buf))) return -1;
42 	return unlink(name);
43 }
44