通过Lua脚本重新启动系统

che*_*che 4 lua

我需要通过Lua脚本重启系统.我需要在Reboot发生之前编写一些字符串,并且需要在Reboot完成后在Lua脚本中编写一个字符串.

示例:

print("Before Reboot System")

Reboot the System through Lua script

print("After Reboot System")
Run Code Online (Sandbox Code Playgroud)

我怎么做到这一点?

Kev*_*eer 6

您可以使用os.execute发出系统命令.对于Windows,shutdown -r对于Posix系统来说,它就是这样reboot.因此,您的Lua代码将如下所示:

请注意,部分reboot命令正在停止活动程序,例如Lua脚本.这意味着存储在RAM中的任何数据都将丢失.您需要使用表序列化将要保留的任何数据写入磁盘.

不幸的是,如果不了解您的环境,我无法告诉您如何再次调用脚本.您可以将脚本的调用追加到末尾~/.bashrc或类似.

确保在您调用重启功能后加载此数据并从某个点开始,这是您回来时的第一件事!你不想陷入无休止的重启循环,你的计算机在打开时首先要关闭它.这样的事情应该有效:

local function is_rebooted()
    -- Presence of file indicates reboot status
    if io.open("Rebooted.txt", "r") then
        os.remove("Rebooted.txt")
        return true
    else
        return false
    end
end

local function reboot_system()
    local f = assert(io.open("Rebooted.txt", "w"))
    f:write("Restarted!  Call On_Reboot()")

    -- Do something to make sure the script is called upon reboot here

    -- First line of package.config is directory separator
    -- Assume that '\' means it's Windows
    local is_windows = string.find(_G.package.config:sub(1,1), "\\")

    if is_windows then
        os.execute("shutdown -r");
    else
        os.execute("reboot")
    end
end

local function before_reboot()
    print("Before Reboot System")
    reboot_system()
end

local function after_reboot()
    print("After Reboot System")
end

-- Execution begins here !
if not is_rebooted() then
    before_reboot()
else
    after_reboot()
end
Run Code Online (Sandbox Code Playgroud)

(警告 - 未经测试的代码.我不想重新启动.:)