简介
在上篇中我们实现了通过exec命令,重新进入了后台运行中的容器,本篇将实现stop命令,将运行中的容器停止
源码说明
同时放到了Gitee和Github上,都可进行获取
本章节对应的版本标签是:5.5,防止后面代码过多,不好查看,可切换到标签版本进行查看
代码实现
实现该功能的主要思路如下:
1 首先根据容器名称,定位到其配置文件
2 读取配置文件,得到容器的PID,发送kill信号,停止进程,这样容器运行也停止了
3 将相关的停止信息更新写入配置文件中进行保存
stop命令新增
在main函数中新增stop命令:
func main() {
app.Commands = []cli.Command{
command.InitCommand,
command.RunCommand,
command.CommitCommand,
command.ListCommand,
command.LogCommand,
command.ExecCommand,
command.StopCommand,
}
}
main_command.go新增相关的命令:
var StopCommand = cli.Command{
Name: "stop",
Usage: "stop container",
Action: func(context *cli.Context) {
if len(context.Args()) < 1 {
log.Errorf("missing container name")
return
}
containerName := context.Args().Get(0)
if err := run.StopContainer(containerName); err != nil {
log.Errorf("stop container err: %v", err)
}
},
}
读取容器配置文件,停止并更新容器
我们根据容器名称,找到容器的配置文件的存放位置
读取配置文件后,我们能得到容器在宿主机上的PID
更加PID,我们就能发送kill命令