如何使用Lua启动服务器

huangapple go评论75阅读模式
英文:

How can I use lua to start a server

问题

我有一个测试服务器,它是一个循环。我想要使用 lua 启动这个服务器。
服务器的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    for(int i = 0; i<5; i++) {
        sleep(1);
        printf("wait %d s\n", 5 - i);
    }
}

我已经编译了它:

g++ server.cpp -o server

然后我编写了一个名为 start.lua 的文件,内容如下:

local executable = "./server"
local exitcode = os.execute(executable)
if exitcode == 0 then
  print("Executable executed successfully.")
else
  print("Failed to execute the executable. Exit code: " .. exitcode)
end

-- 我不想等待服务器结束,我应该在服务器启动后执行其他操作

然后我使用 lua start.lua 启动服务器,我发现只有当 server 结束时,lua 才会打印出 "Executable executed successfully."。如何让 os.execute 立即返回而不影响服务器继续执行呢?

英文:

I have a test server, it is a loop. I want to start this server use lua.
The server is like this :

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;unistd.h&gt;
int main()
{
    for(int i = 0; i&lt;5; i++) {
        sleep(1);
        printf(&quot;wait %d s\n&quot;, 5 - i);
    }
}

and I have have compiled it

g++ server.cpp -o server

And I write a start.lua file like this

local executable = &quot;./server&quot;
local exitcode = os.execute(executable)
if exitcode == 0 then
  print(&quot;Executable executed successfully.&quot;)
else
  print(&quot;Failed to execute the executable. Exit code: &quot; .. exitcode)
end

# I do not want to wait the server ends, I should do other things after the server starts

then I use lua start.lua to start the server, I find only when the server ends, there will be lua printing Executable executed successfully.. How to let os.execute return immediately without affecting the server to continue to execute?

答案1

得分: 1

尝试使用 Lua 的 posix 库(https://github.com/luaposix/luaposix),可以使用 luarocks 安装。另外,你可以尝试使用 io.popen,它是非阻塞的。

英文:

Try using lua posix library (https://github.com/luaposix/luaposix) that can be installed using luarocks. Also, you can try io.popen, which is non-blocking.

答案2

得分: 0

根据@ESkri所说,我使用本地可执行文件 = "./server &"。

英文:

As @ESkri said, I use local executable = "./server &"

huangapple
  • 本文由 发表于 2023年7月27日 18:20:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76778767.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定