Search code examples
lua

How can I use lua to start a server


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?


Solution

  • 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.