Skip to content

Commit bdb9e40

Browse files
add --pid: option to terminate if other process terminates
1 parent 9a818e9 commit bdb9e40

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

src/main.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ auto main(int argc, char **argv) -> int {
2828
"s,semaphore",
2929
"protect the shared memory with an existing named semaphore against simultaneous access",
3030
cxxopts::value<std::string>());
31+
options.add_options("shared_memory")(
32+
"pid", "terminate application if application with given pid is terminated.", cxxopts::value<pid_t>());
3133
options.add_options("other")("h,help", "print usage");
3234
options.add_options("version information")("version", "print version and exit");
3335
options.add_options("version information")("longversion",
@@ -243,6 +245,18 @@ auto main(int argc, char **argv) -> int {
243245

244246
const bool cyclic = opts["interval"].count();
245247
if (cyclic) {
248+
pid_t shm_owner_pid = 0;
249+
if (opts.count("pid") == 0) {
250+
std::cerr << "Warning: No SHM owner PID provided.\n"
251+
" This application is NOT terminated if the owner of the shared memory closes the "
252+
"shared memory.\n"
253+
" This application WILL NOT reconnect to the shared memory if it is recreated.\n"
254+
" Use --pid to specify the PID of the SHM owner.\n";
255+
std::cerr << std::flush;
256+
} else {
257+
shm_owner_pid = opts["pid"].as<pid_t>();
258+
}
259+
246260
// check interval
247261
const auto interval = opts["interval"].as<unsigned>();
248262
static constexpr unsigned MIN_INTERVAL = 10;
@@ -282,6 +296,19 @@ auto main(int argc, char **argv) -> int {
282296
}
283297

284298
if (sig != SIGALRM) break;
299+
300+
// check shm owner pid
301+
if (shm_owner_pid) {
302+
tmp = kill(shm_owner_pid, 0);
303+
if (tmp == -1) {
304+
if (errno == ESRCH) {
305+
std::cerr << "SHM owner (pid=" << shm_owner_pid << ") no longer alive.\n" << std::flush;
306+
} else {
307+
perror("failed to send signal to the SHM owner process");
308+
}
309+
break;
310+
}
311+
}
285312
}
286313

287314
} else {

0 commit comments

Comments
 (0)