英文:
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 <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);
}
}
and I have have compiled it
g++ server.cpp -o server
And I write a start.lua
file like this
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
# 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 &"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论