[Pythonmac-SIG] urllib2.urlopen fails in a forked daemon with a CoreFoundation error

Bill Janssen janssen at parc.com
Mon Mar 16 18:26:33 CET 2009


Jarkko Laiho <jarkko.laiho at iki.fi> wrote:

> So ultimately the question is: how should the forking code in the
> recipe be modified, so that it satisfies the requirements of OS X?
> What does an actual, concrete exec() call look like in this case, and
> at what point in the code should it occur?

I don't know -- you didn't post your entire program.  Read the Wikipedia
page and follow the refs.  Here's an example:

def daemon ():

    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)     # parent
    except OSError, e:
        msg = "fork #1 failed: (%d) %s\n" % (e.errno, e.strerror)
        sys.stderr.write(msg)
        sys.exit(1)

    os.umask(0)
    # now create a new session
    os.setsid()
    # and fork into the new session

    try:
        pid = os.fork()
        if pid > 0:
            sys.exit(0)     # session leader exits here
    except OSError, e:
        msg = "fork #2 failed: (%d) %s\n" % (e.errno, e.strerror)
        sys.stderr.write(msg)
        sys.exit(1)

    # here you could make any changes you need to the "env", like setting "PYTHONPATH"
    env = os.environ.copy()
    # figure out how to invoke the actual program
    args = [sys.executable, "-c",
            "import mycode;" +
            "mycode.realmain()"
            ]
    os.execve(sys.executable, args, env)

                               
def realmain():

    start_server()

    # the real "main"...
    # this is basically just an event-handling loop

    while True:
        try:
            asyncore.loop()
        except (KeyboardInterrupt, SystemExit), x:
            note(4, "Exited from main loop due to exception:\n%s", ''.join(traceback.format_exception(*sys.exc_info())))
            raise
        except:
            note(0, "Exited from main loop due to exception:\n%s", ''.join(traceback.format_exception(*sys.exc_info())))


if __name__ == "__main__" and (not sys.platform.lower().startswith("win")):
    daemon()


More information about the Pythonmac-SIG mailing list