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

Linux下C#如何实现父进程退出时不终止子进程?

解决Linux下C#父进程退出导致子进程终止的问题

在Linux系统中,子进程默认会和父进程处于同一个进程组与会话中,当父进程退出时,会话首进程终止,子进程会收到SIGHUP信号从而被终止。要让子进程独立运行,核心是让它脱离原进程组和会话,成为不受父进程退出影响的孤儿进程。

以下是几种可行的解决方案:

方案一:使用setsid命令启动子进程

setsid可以创建一个新的会话,并让子进程成为会话首进程,彻底脱离原进程组。修改代码如下:

var procStartInfo = new ProcessStartInfo("setsid", $"{program} {arguments}")
{
    UseShellExecute = false,
    WorkingDirectory = workingDir,
    CreateNoWindow = true
};

_ = Process.Start(procStartInfo);

如果需要忽略子进程的输出(避免占用IO导致父进程退出受阻),可以将输出重定向到/dev/null:

var procStartInfo = new ProcessStartInfo("/bin/sh", $"-c \"setsid {program} {arguments} > /dev/null 2>&1 &\"")
{
    UseShellExecute = false,
    WorkingDirectory = workingDir,
    CreateNoWindow = true
};

_ = Process.Start(procStartInfo);

方案二:使用nohup命令启动子进程

nohup会让进程忽略SIGHUP信号,同时默认将输出写入nohup.out(也可以重定向),配合后台运行符号&实现独立运行:

var procStartInfo = new ProcessStartInfo("/bin/sh", $"-c \"nohup {program} {arguments} > /dev/null 2>&1 &\"")
{
    UseShellExecute = false,
    WorkingDirectory = workingDir,
    CreateNoWindow = true
};

_ = Process.Start(procStartInfo);

方案三:调整ProcessStartInfo基础配置(需配合脱离会话操作)

将UseShellExecute设为false,并切断子进程与父进程的标准输入输出关联,避免IO依赖导致的进程关联:

var procStartInfo = new ProcessStartInfo(program, arguments)
{
    UseShellExecute = false,
    WorkingDirectory = workingDir,
    CreateNoWindow = true,
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};

var process = Process.Start(procStartInfo);
// 关闭输入流,避免子进程等待父进程输入而挂起
process.StandardInput.Close();

注意:这种方式若不配合setsid或nohup,部分场景下子进程仍可能收到SIGHUP信号,因此更推荐前两种方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:14:49