如何从Linux上运行的.NET核心应用程序关闭计算机

sg24os4d  于 2023-02-11  发布在  Linux
关注(0)|答案(3)|浏览(160)

我有一个运行在Linux(Ubuntu服务器16.04 LTS)上的. net核心2.0程序。
我正在尝试通过使用以下命令调用进程来关闭计算机:sudo shutdown -h now,但当程序作为守护程序服务在后台运行时,关闭过程不起作用。
下面是代码:

var process = new Process
{
    StartInfo =
    {
        CreateNoWindow = true,
        RedirectStandardError = true,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        UseShellExecute = false,
        FileName = Environment.GetEnvironmentVariable("SHELL"),
        Arguments = "-s"
    },
    EnableRaisingEvents = true
};

if (process.Start())
{
    process.BeginErrorReadLine();
    process.BeginOutputReadLine();
    process.StandardInput.WriteLine("sudo shutdown -h now");
}

我的假设是服务作为一个单独的会话运行,所以它没有任何控制权。当应用程序作为Linux守护进程运行时,我如何让它关闭计算机?

iqjalb3h

iqjalb3h1#

我建议更改代码,使用P/Invoke直接调用Linux的reboot函数,如果失败,这也会提供更多细节。
虽然调用其他可执行文件来执行任务是Unix/Linux上的惯例(特别是从shell脚本),但. NET程序确实不适合,而且所需的代码非常脆弱(例如,您在sudo中看到的),特别是在. NET世界中,处理来自其他进程的标准IO(stdinstdoutstderr)非常困难。

internal static class NativeMethods
{
    [DllImport( "libc.so", SetLastError = true)] // You may need to change this to "libc.so.6" or "libc.so.7" depending on your platform)
    public static extern Int32 reboot(Int32 magic, Int32 magic2, Int32 cmd, IntPtr arg);

    public const Int32 LINUX_REBOOT_MAGIC1 = unchecked((int)0xfee1dead);
    public const Int32 LINUX_REBOOT_MAGIC2 = 672274793;
    public const Int32 LINUX_REBOOT_MAGIC2A = 85072278;
    public const Int32 LINUX_REBOOT_MAGIC2B = 369367448;
    public const Int32 LINUX_REBOOT_MAGIC2C = 537993216;

    public const Int32 LINUX_REBOOT_CMD_RESTART = 0x01234567;
    public const Int32 LINUX_REBOOT_CMD_HALT = unchecked((int)0xCDEF0123);
    public const Int32 LINUX_REBOOT_CMD_CAD_ON = unchecked((int)0x89ABCDEF);
    public const Int32 LINUX_REBOOT_CMD_CAD_OFF = 0x00000000;
    public const Int32 LINUX_REBOOT_CMD_POWER_OFF = 0x4321FEDC;
    public const Int32 LINUX_REBOOT_CMD_RESTART2 = unchecked((int)0xA1B2C3D4);
    public const Int32 LINUX_REBOOT_CMD_SW_SUSPEND = unchecked((int)0xD000FCE2);
    public const Int32 LINUX_REBOOT_CMD_KEXEC = 0x45584543;

    public const Int32 EPERM  =  1;
    public const Int32 EFAULT = 14;
    public const Int32 EINVAL = 22;
}

用法:

using static NativeMethods;

public static void Shutdown()
{
    Int32 ret = reboot( LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, LINUX_REBOOT_CMD_POWER_OFF, IntPtr.Zero );

    // `reboot(LINUX_REBOOT_CMD_POWER_OFF)` never returns if it's successful, so if it returns 0 then that's weird, we should treat it as an error condition instead of success:
    if( ret == 0 ) throw new InvalidOperationException( "reboot(LINUX_REBOOT_CMD_POWER_OFF) returned 0.");

    // ..otherwise we expect it to return -1 in the event of failure, so any other value is exceptional:
    if( ret != -1 ) throw new InvalidOperationException( "Unexpected reboot() return value: " + ret );

    // At this point, ret == -1, which means check `errno`!
    // `errno` is accessed via Marshal.GetLastWin32Error(), even on non-Win32 platforms and especially even on Linux

    Int32 errno = Marshal.GetLastWin32Error();
    switch( errno )
    {
    case EPERM:
        throw new UnauthorizedAccessException( "You do not have permission to call reboot()" );

    case EINVAL:
        throw new ArgumentException( "Bad magic numbers (stray cosmic-ray?)" );

    case EFAULT:
    default:
        throw new InvalidOperationException( "Could not call reboot():" + errno.ToString() );
    }
}

请注意,对reboot()的成功调用将永远不会返回。

ivqmmu1c

ivqmmu1c2#

另外,对于运行在Raspberry Pi上的.net核心,我们需要使用另一个答案,但请按照用户Tom的评论,将DllImport更改为:

[DllImport( "libc.so.6", SetLastError = true)]
public static extern Int32 reboot(Int32 cmd, IntPtr arg);

然后关闭电源,我们可以调用:

reboot(LINUX_REBOOT_CMD_POWER_OFF, IntPtr.Zero);

或重新启动:

reboot(LINUX_REBOOT_CMD_RESTART, IntPtr.Zero);
qaxu7uf2

qaxu7uf23#

这在AWS EC2和Ubuntu服务器上工作,在守护进程中使用。只在那里测试过,在其他地方也可以工作。

Process process = new Process();
process.StartInfo.FileName = "/usr/bin/sudo";
process.StartInfo.Arguments = "/sbin/shutdown -h now";
process.Start();

相关问题