1 /* shm_open - open a shared memory file */
2
3 /* Copyright 2002, Red Hat Inc. */
4
5 #include <sys/types.h>
6 #include <sys/mman.h>
7 #include <unistd.h>
8 #include <string.h>
9 #include <fcntl.h>
10 #include <limits.h>
11
12 int
shm_open(const char * name,int oflag,mode_t mode)13 shm_open (const char *name, int oflag, mode_t mode)
14 {
15 int fd;
16 char shm_name[PATH_MAX+20] = "/dev/shm/";
17
18 /* skip opening slash */
19 if (*name == '/')
20 ++name;
21
22 /* create special shared memory file name and leave enough space to
23 cause a path/name error if name is too long */
24 strlcpy (shm_name + 9, name, PATH_MAX + 10);
25
26 fd = open (shm_name, oflag, mode);
27
28 if (fd != -1)
29 {
30 /* once open we must add FD_CLOEXEC flag to file descriptor */
31 int flags = fcntl (fd, F_GETFD, 0);
32
33 if (flags >= 0)
34 {
35 flags |= FD_CLOEXEC;
36 flags = fcntl (fd, F_SETFD, flags);
37 }
38
39 /* on failure, just close file and give up */
40 if (flags == -1)
41 {
42 close (fd);
43 fd = -1;
44 }
45 }
46
47 return fd;
48 }
49