'Simple way to restart application

Some library has some memory leak, and as a simple solution, I just want to restart my script frequently. My script does some long calculation but I can just save the state and then load it again, so restarting it is not a problem.

For restarting, I was just using os.execv:

os.execv(sys.executable, [sys.executable] + sys.argv)

However, now after a while, I get Too many open files.

Why is that? As far as I know, all file descriptors (fds) should have been closed after exec? I thought we always have the close-on-exec flag set? But maybe not? Or maybe not for all the libraries? Maybe I misunderstood the documentation. Can someone clarify this?

How would I close all fds before the exec? os.closerange? Maybe just:

max_fd = os.sysconf("SC_OPEN_MAX")
os.closerange(3, max_fd)
os.execv(sys.executable, [sys.executable] + sys.argv)

Does that work correctly then?

What are other simple solutions of restarting? I assume fork+exec+exit will just have the same problem then? Or spawn+exit?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source