| 177 | } |
| 178 | |
| 179 | bool lockSingleInstance() |
| 180 | { |
| 181 | // We will never close this file manually. The operating system will |
| 182 | // take care of that, because flock keeps the lock as long as the |
| 183 | // file is open and closes it automatically on file close. |
| 184 | // This is intentional. |
| 185 | int32_t pidFile = open(kSingleInstanceMutexName, O_CREAT | O_RDWR, 0666); |
| 186 | |
| 187 | if (pidFile == -1) |
| 188 | { |
| 189 | std::cerr << "Cannot open lock file for writing."; |
| 190 | return false; |
| 191 | } |
| 192 | |
| 193 | struct flock lock; |
| 194 | |
| 195 | lock.l_start = 0; |
| 196 | lock.l_len = 0; |
| 197 | lock.l_type = F_WRLCK; |
| 198 | lock.l_whence = SEEK_SET; |
| 199 | |
| 200 | if (fcntl(pidFile, F_SETLK, &lock) == -1) |
| 201 | { |
| 202 | if (errno == EWOULDBLOCK) |
| 203 | { |
| 204 | std::cerr << "Another OpenLoco session has been found running."; |
| 205 | return false; |
| 206 | } |
| 207 | std::cerr << "flock returned an uncatched errno: " << errno; |
| 208 | return false; |
| 209 | } |
| 210 | return true; |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | #endif |