如何在 Linux 上用 C# 启动服务

本文关键字:启动 服务 上用 Linux | 更新日期: 2023-09-27 17:57:15

我想通过 Mono 使用 C# 控制台应用程序在我的 Linux 服务器上启动服务。

public static void StartService(string serviceName, int timeoutMilliseconds)
{
  ServiceController service = new ServiceController(serviceName);
  try
  {
    TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
    service.Start();
    service.WaitForStatus(ServiceControllerStatus.Running, timeout);
  }
  catch
  {
    // ...
  }
}

这行得通吗?

作为替代方案,有没有办法通过 C# 将命令发送到 Linux,就像您可以在 Windows 系统上发送命令一样?

我正在尝试使用 C# 可执行文件启动 Linux 服务。

如何在 Linux 上用 C# 启动服务

您可以通过执行此操作来执行命令;

Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c 'your command here'";
proc.StartInfo.UseShellExecute = false; 
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();