首页 > 解决方案 > pkill -f 在 shell 脚本中不起作用

问题描述

我有一个名为的 shell 脚本kill.sh,可以帮助我重新启动我编写的 python 脚本。我通常pkill -f main.py用来杀死我永远运行的 python 脚本。但是,当我将它写入 shell 脚本时,它不起作用。

我的剧本

pkill -f main.py
ps aux | grep main.py # Still shows the process running. 

虽然只是pkill -f main.py在 bash 命令行中执行,但可以按预期工作。为什么是这样?

标签: pythonbashshell

解决方案


这不是一个令人满意的答案,因为我无法找出为什么pkill -f在脚本中不起作用的根本原因。我最终使用systemd服务文件来管理我的 python 进程。这是一个示例,仅供参考。

[Unit]
Description=Service Name
[Service]
Environment=PYTHONUNBUFFERED=1
ExecStart=/path/to/python /path/to/python/script.py
Restart=on-failure
RestartSec=5s
WorkingDirectory=/python/project/dir/

命名文件main.service并将其放入/lib/systemd/system/

  • 运行服务systemctl start main.service
  • 停止服务systemctl stop main.service
  • 重启服务systemctl restart main.service
  • 显示状态和输出systemctl status main.service -l

现在我不必担心多个进程正在运行。如果程序死了,它甚至会重新启动。


推荐阅读