繁体   English   中英

bash脚本如何在向子进程发送信号时在非0退出时重启进程

[英]How can a bash script restart a process on non-0 exit while sending signals to child

提出以下问题: 如果死了,我如何编写bash脚本来重新启动进程?

我正在尝试制作一个bash脚本,该脚本仅运行python脚本,如果脚本以非0输出结束,则重新启动该脚本。 我的bash脚本看起来像:

#!/bin/bash

trap 'kill $(jobs -p)' SIGTERM SIGKILL; 
until python test.py & wait; do 
  echo "Test Critically Crashed" >&2
  sleep 1; 
done

虽然我的python脚本(尽管并不十分相关)看起来像:

import logging,sys,signal,time

def signal_term_handler(signal, frame):
  print("SIGTERM recieved...quitting")
  sys.exit(0)

signal.signal(signal.SIGTERM, signal_term_handler)
while True:
  time.sleep(1)
  sys.exit(1)

我想运行bash脚本并使它无限运行我的进程,直到将sigterm或sigkill发送到bash脚本,然后在其中将其发送到子进程(python test.py)并最终以代码0退出,因此打破直到循环并干净地退出。

仅供参考,我正在使用无限运行的python脚本,并将此bash脚本用作docker容器的入口点。

不要写一个shell脚本。 使用systemdsupervisordocker或任何可用的服务管理器直接管理docker / script进程。 这是专为工作服务经理准备的,他们为此而努力。

systemd服务将运行docker run {image} python test.py ,您需要将其设置为无限期运行。

systemd配置如下所示:

[Unit]
Description=My Super Script
Requires=docker.service
After=docker.service

[Service]
ExecStart=/bin/docker run --name={container} --rm=true {image} python test.py
ExecStop=/bin/docker stop --time=10 {container}
TimeoutStopSec=11
KillMode=control-group

Restart=on-failure
RestartSec=5
TimeoutStartSec=5

[Install]
WantedBy=multi-user.target

Restart=on-failure设置符合您仅在返回非0退出代码时重新启动进程的要求,因此,如果需要,您仍然可以终止systemd下的进程。

如果要在已经运行的容器中运行和管理python进程,则可以更容易地将supervisord作为主容器进程运行,并使其管理python test.py 主管的功能不如systemd完整,但它可以完成所有基本的服务管理任务。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM