There are two programs that communicate with each other via named pipes. One in C ++, the second in Python. And the first one starts the second (in the standard way, via fork + exec).
Communication section of the parent program (C ++):
// ... int pipeDescr; std::string outputPipeName{"inputPipe"}; std::string inputPipeName{"outputPipe"}; char *message = new char[BUFSIZE]; // ... while (true) { int bytesNumber = 0; // ... if ((pipeDescr = open(outputPipeName.c_str(), O_WRONLY)) <= 0) break; bytesNumber = write(pipeDescr, message, strlen(message)); if (bytesNumber <= 0) break; close(pipeDescr); message[0] = '\0'; if ((pipeDescr = open(inputPipeName.c_str(), O_RDONLY)) <= 0) break; bytesNumber = read(pipeDescr, message, BUFSIZE); if (bytesNumber <= 0) break; close(pipeDescr); // ... } In a separate thread, the watchDog function works, which is responsible for the operation of the child application in Python.
void watchDog(int clientSocket, pid_t pid, bool &stopWatchDog) { while (true) { // Дочерняя программа завершилась с ошибкой if (waitpid(pid, NULL, WNOHANG) != 0) { // ... } // Родительская программа закрывается mutexClosing.lock(); if (closing) { mutexClosing.unlock(); if (waitpid(pid, NULL, WNOHANG) == 0) { kill(pid, SIGTERM); waitpid(pid, NULL, 0); } break; } mutexClosing.unlock(); // Программное отключение WatchDog-а mutexWatchDog.lock(); if (stopWatchDog) { if (waitpid(pid, NULL, WNOHANG) == 0) { kill(pid, SIGTERM); waitpid(pid, NULL, 0); } mutexWatchDog.unlock(); break; } mutexWatchDog.unlock(); } } There are three outcomes:
child program crash
completion of the parent program
completing a child program without terminating the parent
In the last two options, you need to smoothly terminate the child program, so I send her a SIGTERM signal and wait for completion.
Communication section of the child program (Python):
def sigterm_handler(signal, frame): print('\nGot sigterm!\n') sys.exit(0) def main(): input_pipe_name = "inputPipe" output_pipe_name = "outputPipe" # ... signal.signal(signal.SIGTERM, sigterm_handler) # ... while True: pipe_descr = os.open(input_pipe_name, os.O_RDONLY) request = os.read(pipe_descr, 10000) os.close(pipe_descr) reply = work_func(request) pipe_descr = os.open(output_pipe_name, os.O_WRONLY) os.write(pipe_descr, bytes(reply, 'UTF-8')) os.close(pipe_descr) In the code I added signal processing SIGTERM. However, when this signal is transmitted, the sigterm_handler function is not called.
But! If you write something like this:
def main(): signal.signal(signal.SIGTERM, sigterm_handler) while True: print('waiting...') time.sleep(2) That function will be called.
Tell me how to solve this problem!
while True:addtime.sleep(1), and check, please. - Senior Pomidor