gpt4 book ai didi

linux - 从 systemd 启动主进程时无法分 ionic 进程

转载 作者:IT老高 更新时间:2023-10-28 13:05:33 25 4
gpt4 key购买 nike

我想生成长时间运行的子进程,这些子进程在主进程重新启动/死亡时仍然存在。从终端运行时效果很好:

$ cat exectest.go
package main

import (
"log"
"os"
"os/exec"
"syscall"
"time"
)

func main() {
if len(os.Args) == 2 && os.Args[1] == "child" {
for {
time.Sleep(time.Second)
}
} else {
cmd := exec.Command(os.Args[0], "child")
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
log.Printf("child exited: %v", cmd.Run())
}
}
$ go build
$ ./exectest
^Z
[1]+ Stopped ./exectest
$ bg
[1]+ ./exectest &
$ ps -ef | grep exectest | grep -v grep | grep -v vim
snowm 7914 5650 0 23:44 pts/7 00:00:00 ./exectest
snowm 7916 7914 0 23:44 ? 00:00:00 ./exectest child
$ kill -INT 7914 # kill parent process
[1]+ Exit 2 ./exectest
$ ps -ef | grep exectest | grep -v grep | grep -v vim
snowm 7916 1 0 23:44 ? 00:00:00 ./exectest child

请注意,在父进程被杀死后,子进程仍然处于事件状态。但是,如果我像这样从 systemd 启动主进程...

[snowm@localhost exectest]$ cat /etc/systemd/system/exectest.service 
[Unit]
Description=ExecTest

[Service]
Type=simple
ExecStart=/home/snowm/src/exectest/exectest
User=snowm

[Install]
WantedBy=multi-user.target
$ sudo systemctl enable exectest
ln -s '/etc/systemd/system/exectest.service' '/etc/systemd/system/multi-user.target.wants/exectest.service'
$ sudo systemctl start exectest

...那么当我杀死主进程时, child 也死了:

$ ps -ef | grep exectest | grep -v grep | grep -v vim
snowm 8132 1 0 23:55 ? 00:00:00 /home/snowm/src/exectest/exectest
snowm 8134 8132 0 23:55 ? 00:00:00 /home/snowm/src/exectest/exectest child
$ kill -INT 8132
$ ps -ef | grep exectest | grep -v grep | grep -v vim
$

我怎样才能让 child 活下来?

在 CentOS Linux release 7.1.1503 (Core) 下运行 go version go1.4.2 linux/amd64。

最佳答案

解决办法是添加

KillMode=process

到服务 block 。默认值为 control-group,表示 systemd 会清理所有子进程。

来自 man systemd.kill

KillMode= Specifies how processes of this unit shall be killed. One of control-group, process, mixed, none.

If set to control-group, all remaining processes in the control group of this unit will be killed on unit stop (for services: after the stop command is executed, as configured with ExecStop=). If set to process, only the main process itself is killed. If set to mixed, the SIGTERM signal (see below) is sent to the main process while the subsequent SIGKILL signal (see below) is sent to all remaining processes of the unit's control group. If set to none, no process is killed. In this case, only the stop command will be executed on unit stop, but no process be killed otherwise. Processes remaining alive after stop are left in their control group and the control group continues to exist after stop unless it is empty.

关于linux - 从 systemd 启动主进程时无法分 ionic 进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32208782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com