Skip to content

Commit 8bd6fd9

Browse files
option to check if modbus client is still alive
1 parent c626b94 commit 8bd6fd9

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/main.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,11 @@ int main(int argc, char **argv) {
115115
options.add_options("shared memory")("semaphore-timeout",
116116
"maximum time (in seconds) to wait for semaphore (default: 0.1)",
117117
cxxopts::value<double>()->default_value("0.1"));
118+
options.add_options("shared_memory")(
119+
"pid",
120+
"terminate application if application with given pid is terminated. Provide "
121+
"the pid of the modbus client to terminate when the mosbus client is terminated.",
122+
cxxopts::value<pid_t>());
118123

119124
// parse arguments
120125
cxxopts::ParseResult args;
@@ -425,6 +430,11 @@ int main(int argc, char **argv) {
425430
std::cerr << e.what() << '\n';
426431
return EX_SOFTWARE;
427432
}
433+
} else {
434+
std::cerr << "WARNING: No semaphore specified.\n"
435+
" Concurrent access to the shared memory is possible that can result in CORRUPTED DATA.\n"
436+
" Use --semaphore to specify a semaphore that is provided by the Modbus client.\n";
437+
std::cerr << std::flush;
428438
}
429439

430440
const double SEMAPHORE_TIMEOUT_S = args["semaphore-timeout"].as<double>();
@@ -439,6 +449,22 @@ int main(int argc, char **argv) {
439449
static_cast<suseconds_t>(std::modf(SEMAPHORE_TIMEOUT_S, &modf_dummy) * 1'000'000),
440450
};
441451

452+
// modbus client pid
453+
pid_t mb_client_pid = 0;
454+
bool use_mb_client_pid = false;
455+
if (args.count("pid")) {
456+
mb_client_pid = args["pid"].as<pid_t>();
457+
use_mb_client_pid = true;
458+
} else {
459+
std::cerr << "WARNING: No Modbus client pid provided.\n"
460+
" Terminating the Modbus client application WILL NOT result in the termination of this "
461+
"application.\n"
462+
" This application WILL NOT connect to the shared memory of a restarted Modbus client.\n"
463+
" Use --pid to specify the pid of the modbus client.\n"
464+
" Command line example: --pid $(pidof modbus-tcp-client-shm)\n"
465+
<< std::flush;
466+
}
467+
442468
std::cout << std::fixed;
443469

444470
auto last_time = std::chrono::steady_clock::now();
@@ -648,6 +674,20 @@ int main(int argc, char **argv) {
648674
input_thread.detach();
649675

650676
while (!terminate) {
677+
if (use_mb_client_pid) {
678+
// check if modbus client is still alive
679+
int tmp = kill(mb_client_pid, 0);
680+
if (tmp == -1) {
681+
if (errno == ESRCH) {
682+
std::cerr << "Modbus client (pid=" << mb_client_pid << ") no longer alive.\n" << std::flush;
683+
} else {
684+
perror("failed to send signal to modbus client");
685+
}
686+
terminate = true;
687+
break;
688+
}
689+
}
690+
651691
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // NOLINT
652692
}
653693

0 commit comments

Comments
 (0)