Search code examples
c#.netlinuxprocessparent-child

Don't kill process when dotnet project shut down


I'm working on a dotnet app for a Linux system (debian). I want to run commands on Linux from my app. I'm running commands using this method. I really don't want to change it if possible.

public static async Task<Process> RunCommandAsync(string command)
{
    string cmd = command.Replace("\"", "\\\"");
    Process process = new()
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = "/bin/bash",
            Arguments = $"-c \"{cmd}\"",
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
        }
    };
    process.Start();
    await process.WaitForExitAsync();
    return process;
}

My goal is to start a process within the project and not killing it when I shut down the project. I wanted to use only a command. I tried something like this sudo nohup sh -c 'ping google.com' > /dev/null &, which I though that would work but when I shut down the project the process is also terminated.

In short, in this example I wanted to continuing the ping even after I shut down the project.

Edit 1

Here, for simplicity, I gave the example of a ping. In reality the app is in a debian package and there are two apps running at the same time, both as services. At some point I want in uninstall the app, which stops both services. I stop the service responsible for this first, and then the other service is never stop and the app isn't uninstalled correctly.


Solution

  • I found a solution. I created a service (finish.service) like this:

    [Unit]
    Description=Uninstall app1 and install app2  
    
    [Service]
    Type=oneshot
    ExecStart=/opt/finish/finish.sh
    WorkingDirectory=/opt/finish/
    StandardOutput=journal
    StandardError=journal
    

    Where "/opt/finish/finish.sh": (simplified code)

    #!/bin/bash
    
    sudo apt purge app1;
    sudo apt install app2;
    

    In my app, when I want to uninstall it and install a new one I simply call

    sudo systemctl start finish.service