What is the best practice for gracefully shutting down processes that are generated by external programs using python?

use the subprocess library:

try:
    p = sh.ping("-c", "5", "www.bing.com", _bg=True, _bg_exc=False, 
                _out=sys.stdout, _err=sys.stderr)
    p.wait()
except KeyboardInterrupt as e:
    alive, _ = p.process.is_alive()
    if alive:
        p.process.terminate()

what are the disadvantages of this way of ending an external process?

Mar.23,2021

answer your own questions.

the requirement for me to ask this question is to use python to call external third-party programs, similar to shell scripts.
if it is a normal multi-process programming cooperation to complete a task, then of course the best way is for two processes to cooperate, even if the parent process sends the end information to the child process in the way of IPC, and then the child process exits gracefully.

but if you use python to call external third-party commands and use it as a way similar to shell scripts, because you cannot modify the code of external programs, the means of IPC are very limited and are limited to sending signals to child processes.

then the idea of this problem is very clear. I once used the terminate () function to terminate the child process so that the child process could not release resources properly (linux system). By querying the document, we can know that the behavior of the terminate () function in the linux system is to send SIGTERM to the process. In that case, the cause of the problem is that there is a problem with the processing logic after the third-party program receives the SIGTERM signal.

therefore, the best way to end the process is to use a way that is acceptable to the third-party program, which can be obtained by consulting the documentation of the third-party program.

for example, command-line programs consider SIGINT signals better, because SIGINT signals are sent by pressing Ctrl-C when the terminal is in use. Therefore, for most third-party programs, it is better to send SIGINT signals:

p.process.signal(signal.SIGINT)    
Menu