I have a problem analogous to the one described here: Prevent fork() from copying sockets
Basically, inside my Lua script I'm spawning another script which:
- doesn't require communicating with my script either way
- continues running after my script had finished
- is a 3rd party program, code of which I have no control over
The problem is that my Lua script opens a TCP socket to listen on a specific port and after it's quit and despite an explicit server:close()
the child (or more specifically its children) holds onto the socket and keeps the port open (in LISTEN state) preventing my script from running again.
Here's example code that demonstrates the problem:
require('socket')
print('listening')
s = socket.bind("*", 9999)
s:settimeout(1)
while true do
print('accepting connection')
local c = s:accept()
if c then
c:settimeout(1)
local rec = c:receive()
print('received ' .. rec)
c:close()
if rec == "quit" then break end
if rec == "exec" then
print('running ping in background')
os.execute('sleep 10s &')
break
end
end
end
print('closing server')
s:close()
If I run the above script and echo quit | nc localhost 9999
everything works well - program quits and port is closed.
However if I do echo exec | nc localhost 9999
the program quits but the port is blocked by the spawned sleep
(as confirmed by netstat -lpn
) until it exits.
How do I tackle this in the simplest possible manner, preferably without adding any extra dependencies.