You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu 20.04下.NET Core应用执行脚本:服务关闭后需持续运行

问题解决:让脚本在.NET Core服务停止后继续运行

问题根源

你的脚本被当前.NET Core进程作为子进程启动,当脚本执行停止服务的命令时,父进程(.NET Core应用)退出,系统会向同进程组内的所有子进程发送SIGHUP信号,直接终止脚本运行。


解决方案一:修改脚本,使其脱离进程组

在脚本开头添加脱离进程组的逻辑,确保脚本不受父进程退出影响。示例脚本如下:

#!/bin/bash
# 让脚本脱离当前进程组与终端,后台独立运行
setsid bash -c '
# 切换到应用目录
cd /path/to/your/application
# 拉取代码
git pull origin main
# 停止.NET Core服务(根据实际服务名修改)
sudo systemctl stop your-dotnet-app.service
# 重新构建应用
dotnet build --configuration Release
# 重启服务
sudo systemctl start your-dotnet-app.service
' > /var/log/app-update.log 2>&1
  • setsid 会创建新的会话和进程组,让后续命令脱离当前父进程的控制
  • 日志重定向到文件,方便后续排查问题

解决方案二:调整.NET Core进程启动配置

修改C#代码,直接让bash启动脚本时后台运行并脱离终端:

string scriptPath = "/path/to/script.sh";
ProcessStartInfo startInfo = new ProcessStartInfo
{
    FileName = "bash",
    // 用nohup让脚本后台运行,重定向输出避免占用终端
    Arguments = $"-c \"nohup {scriptPath} > /dev/null 2>&1 &\"",
    CreateNoWindow = true,
    UseShellExecute = false,
    // 关闭输出重定向,避免父进程持有管道导致脚本无法完全脱离
    RedirectStandardOutput = false,
    RedirectStandardError = false,
    WorkingDirectory = Path.GetDirectoryName(scriptPath)
};

// 启动进程后无需等待,脚本已后台独立运行
using Process process = Process.Start(startInfo);

你当前代码的错误修正

你的代码存在两处无效操作:

  1. 重复调用process.Start():Process.Start(startInfo)已经完成进程启动,无需再次调用
  2. 多余的await process.StandardInput.WriteLineAsync(scriptPath):脚本路径已作为bash的参数传入,不需要再通过标准输入传递

内容的提问来源于stack exchange,提问作者virusivv

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 15:12:44