26{
27 bool hasFile = false;
28 std::string tmpPathName;
29
30 if (strcmp(name, "private") != 0) {
31 int tmpFilefd = -1;
32 hasFile = true;
33 tmpPathName = getTmpFileName(getenv("USER"), name);
34 tmpFilefd = open(tmpPathName.c_str(), O_CREAT | O_EXCL | O_RDWR, 0644);
35
36
37 if (tmpFilefd > 0) {
38 printf("SharedMem: Creating a new tmp file %s\n", name);
40 close(tmpFilefd);
41 } else if (tmpFilefd == -1 && errno == EEXIST) {
42 printf("SharedMem: Found existing tmp file %s\n", name);
44 } else {
45 printf("SharedMem: error to open tmp file %s\n", tmpPathName.c_str());
46 return;
47 }
48 m_shmkey = ftok(tmpPathName.c_str(), 1);
49 m_semkey = ftok(tmpPathName.c_str(), 2);
50 } else {
51 hasFile = false;
55 printf("SharedMem: Opening private shared memory\n");
56 }
57
59
60
61
62
63
64
67 perror("SharedMem::shmget");
68 return;
69 }
70 m_shmadr = (
int*) shmat(
m_shmid, 0, 0);
71 if (m_shmadr == (int*) - 1) {
72 perror("SharedMem::shmat");
73 return;
74 }
75
76
77
78
79
80
81
84
85 int semval = 1;
87 if (semctl(
m_semid, 0, SETVAL, semval) == -1) {
88 perror("Initializing semaphore with semctl() failed.");
89 return;
90 }
91 } else if (errno == EEXIST) {
93 printf(
"Found existing Semaphore ID %d for key $%X\n",
m_semid,
m_semkey);
94 }
96 perror("SharedMem::shmget");
97 return;
98 }
99
100
101 if (hasFile) {
102
103 bool updateneeded =
m_new;
104
106 int shmid = 0, semid = 0;
107 if (getIdFromTmpFileName(tmpPathName.c_str(), shmid, semid)) {
109 printf("tmp file %s content still uptodate\n", tmpPathName.c_str());
110 } else {
111 updateneeded = true;
112 }
113 }
114
115 if (updateneeded) {
116 char shminfo[256];
117 int tmpFilefd = open(tmpPathName.c_str(), O_RDWR, 0644);
118 if (tmpFilefd < 0) {
119 printf("SharedMem: error to reopen tmp file %s\n", tmpPathName.c_str());
120 return;
121 }
123 int is = write(tmpFilefd, shminfo, strlen(shminfo));
124 if (is < 0) perror("write");
125 close(tmpFilefd);
126 printf("tmp file %s has been updated with shminfo \"%s\"\n", tmpPathName.c_str(), shminfo);
127 }
128 }
129 printf(
"SharedMem: created. shmid = %d, semid = %d\n",
m_shmid,
m_semid);
130
131}
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.