1

I would like to let a independent C++ process be called by Flask and Flask should keep on running. It starts the c++ process and if I kill Flask it keeps on running (good). My problem is, if I re-start Flask, it will say port in use running and I can't relaunch. So it seems that this process still somehow relates to Flask. How can avoid this? Thanks

import os
pid=os.fork()
if pid==0: # new process
    os.system("nohup /path/myc++ &")

Launch a completely independent process

Error:

sudo python server.py 
 * Serving Flask app "server" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
Traceback (most recent call last):
  File "server.py", line 1046, in <module>
    app.run(debug=True, use_reloader=True)
  File "/home/user/.local/lib/python2.7/site-packages/flask/app.py", line 943, in run
    run_simple(host, port, self, **options)
  File "/home/user/.local/lib/python2.7/site-packages/werkzeug/serving.py", line 795, in run_simple
    s.bind(get_sockaddr(hostname, port, address_family))
  File "/usr/lib/python2.7/socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
zer02
  • 3,963
  • 4
  • 31
  • 66
  • I believe if you shut down workzeug the port should reopen. http://flask.pocoo.org/snippets/67/ What you probably actually want is a message queue, like ZeroMQ or RabbitMQ, which can pass data to totally separate processes. – Alex Weavers Dec 11 '18 at 09:50
  • `if __name__ == "__main__": app.run(debug=True, use_reloader=True)` I use and then I press Strg+C in console. – zer02 Dec 11 '18 at 09:53

1 Answers1

2

It's because of your child process (myc++) inherited all file opened descriptors (socket included) from the parent (Flask) after the fork() call. When the parent process exits, these descriptors remain in opened stats and at the next launch, Flask would be unable to bind a socket at an already opened port.

After the fork, in the child process, parent file descriptors must be closed before the system() command starts.

You should try this code :

    import os
    pid=os.fork()
    if pid==0: # new process
            for fd in xrange(0, 1024):
                try:
                    os.close(fd)
                except OSError:
                    pass
            os.system("nohup /path/myc++ &")
tunglt
  • 1,022
  • 1
  • 9
  • 16