26{
27 bool hasFile = false;
28 std::string tmpPathName;
29
30 if (strcmp(name, "private") != 0) {
31 hasFile = true;
32 if (user) {
33 tmpPathName = getTmpFileName(user, name);
34 } else {
35 tmpPathName = getTmpFileName(getenv("USER"), name);
36 }
37 printf("Open Shared Memory: %s writeable %d\n", tmpPathName.c_str(), writeable);
38 int tmpFilefd = open(tmpPathName.c_str(), O_CREAT | O_EXCL | O_RDWR, 0644);
39
40
41 if (tmpFilefd > 0) {
42 printf("DqmSharedMem: Creating a new tmp file %s\n", name);
44 close(tmpFilefd);
45 } else if (tmpFilefd == -1 && errno == EEXIST) {
46 printf("DqmSharedMem: Updating existing tmp file %s\n", name);
48 } else {
49 printf("DqmSharedMem: error to open tmp file %s\n", tmpPathName.c_str());
50 return;
51 }
52 m_shmkey = ftok(tmpPathName.c_str(), 1);
53 m_semkey = ftok(tmpPathName.c_str(), 2);
54 } else {
55 hasFile = false;
59 printf("DqmSharedMem: Opening private shared memory\n");
60 }
61
63
64
65
66
67
68
72 } else if (errno == EEXIST) {
75 }
77 perror("SharedMem::shmget");
78 return;
79 }
80 if (!writeable) {
81 printf(
"ShM ID %d opened Readonly\n",
m_shmid);
82 m_shmadr = (
int*) shmat(
m_shmid, 0, SHM_RDONLY);
83 } else {
84 printf(
"ShM ID %d opened Writeable\n",
m_shmid);
85 m_shmadr = (
int*) shmat(
m_shmid, 0, 0);
86 }
87 if (m_shmadr == (int*) - 1) {
88 perror("DqmSharedMem::shmat");
89 return;
90 }
91
92
93
94
95
96
97
100
101 int semval = 1;
103 if (semctl(
m_semid, 0, SETVAL, semval) == -1) {
104 perror("Initializing semaphore with semctl() failed.");
105 return;
106 }
107 } else if (errno == EEXIST) {
109 printf(
"Found existing Semaphore ID %d for key $%X\n",
m_semid,
m_semkey);
110 }
112 perror("DqmSharedMem::shmget");
113 return;
114 }
115
116
117 if (hasFile) {
118
119 bool updateneeded =
m_new;
120
122 int shmid = 0, semid = 0;
123 if (getIdFromTmpFileName(tmpPathName.c_str(), shmid, semid)) {
125 printf("tmp file %s content still uptodate\n", tmpPathName.c_str());
126 } else {
127 updateneeded = true;
128 }
129 }
130
131 if (updateneeded) {
132 char shminfo[256];
133 int tmpFilefd = open(tmpPathName.c_str(), O_RDWR, 0644);
134 if (tmpFilefd < 0) {
135 printf("SharedMem: error to reopen tmp file %s\n", tmpPathName.c_str());
136 return;
137 }
139 int is = write(tmpFilefd, shminfo, strlen(shminfo));
140 if (is < 0) perror("write");
141 close(tmpFilefd);
142 printf("tmp file %s has been updated with shminfo \"%s\"\n", tmpPathName.c_str(), shminfo);
143 }
144 }
145 printf(
"DqmSharedMem: opened. shmid = %d, semid = %d\n",
m_shmid,
m_semid);
146}
key_t m_shmkey
SHM key, see shmget(2).
int m_shmid
shared memory id
bool m_new
True if we created the ring buffer ourselves (and need to clean it).
key_t m_semkey
Semaphore key.