0

I want to write lua daemon that listens to TCP socket and allows to handle some user data. I'm using copas library to make my server works with multiply clients simultaneously, but don't know how to daemonize this server. It seems copas doesn't provide such functionality. Does anybody know how to create daemon process in Lua?

Here is a part of code where I define my server:

function handler(c, host, port)
    local peer = host .. ":" .. port
    print("connection from ", peer)
    while 1 do
        command = c:receive"*l"
        c:send(router(command))
    end
end


copas.addserver(assert(socket.bind("127.0.0.1", 8888)),
                        function(c) return handler(copas.wrap(c), c:getpeername()) end
)


copas.loop()

Thanks in advance!

Marc Balmer
  • 1,780
  • 1
  • 11
  • 18
  • Have you considered not demonizing in the code? It depends on which machine you want to run it, but for instance systemd prefers processes which do not demonize by themselves. Even with other init systems / OSs you can use Unix tools such as daemon (http://www.libslack.org/daemon/) to turn a process into a daemon. – catwell Jul 01 '17 at 15:37

2 Answers2

1

Take a look at these two modules, they can do exactly what you want (and yes, we use them for exactly that):

https://github.com/arcapos/luaunix https://github.com/arcapos/luanet

Marc Balmer
  • 1,780
  • 1
  • 11
  • 18
  • Thank you. I didn't use your modules but thanks to your answer I realized the direction:) To solve my task I used lua-posix library. In the end my code looks: `local posix = require("posix")` `pid = posix.fork()` `if pid == 0 then` ` loop = copas.loop()` `else` ` os.exit()` `end` – Leopold Stotch Jul 01 '17 at 15:31
1

Thanks for responding. I've done it with lua-posix library and it turned out easier than I expected. Now it looks like:

local posix = require("posix")

--some code here

pid = posix.fork()
if pid == 0 then
    print("PID: " .. posix.getpid('pid'))
    loop = copas.loop()
else
    os.exit()
end

P.S. I realize this is very simple solution and may be used only as an example.

  • I haven't used fork in Lua, but based on experience elsewhere, you probably want a double-fork. Parent forks, child forks, grandchild is the daemon, child exits(0), parent waits for child then exits(0). This leaves the grandchild fully detached from your terminal, which is what you want for a daemon. https://stackoverflow.com/a/16317668/1695906 – Michael - sqlbot Jul 01 '17 at 20:49
  • @Michael-sqlbot indeed; I've run into the same issue, but to make things complete, I'd also have to calls setsid(), which luaposix's interface to unistd doesn't offer – Daniel Aug 21 '21 at 21:27