Home > Article > Backend Development > How to kill the child process when terminating the main process in Go language
php Xiaobian Yuzai will introduce to you how to kill the child process when terminating the main process in Go language. In development, we often encounter situations where we need to run multiple child processes at the same time. However, when the main process ends, if the child process is not terminated properly, resource leaks or other problems may result. Therefore, it is very important to master how to correctly kill the child process when terminating the main process in Go language. In the following article, we will introduce several common methods to achieve this goal and discuss their advantages and disadvantages.
I want to terminate the child process when the main process terminates.
I am using exec.Command() to run the child process
But the main process may be terminated with an unexpected error, so I want to make sure the child process is terminated as well.
How to archive in Go language?
You may want to use commandcontext
instead and cancel the context in main when the process is terminating. Here are two examples: the first is a simple demonstration of terminating a process after a short timeout, and the second is terminating a child process when the process catches an external termination signal from the operating system:
package main import ( "context" "os/exec" "time" ) func main() { // terminate the command based on time.Duration ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) defer cancel() if err := exec.CommandContext(ctx, "sleep", "5").Run(); err != nil { // This will fail after 100 milliseconds. The 5 second sleep // will be interrupted. } // or use os signals to cancel the context ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) defer stop() }
The above is the detailed content of How to kill the child process when terminating the main process in Go language. For more information, please follow other related articles on the PHP Chinese website!