How to get atexit hooks to run in the presence of execv?

Mark Wooding mdw at distorted.org.uk
Thu Jan 29 14:04:16 CET 2009


rocky at panix.com (R. Bernstein) writes:

> Recently, I added remote debugging via TCP sockets. (Well, also FIFO's
> as well but closing sockets before restarting is what's of concern.)
>
> I noticed that execv in Python 2.5.2 doesn't arrange exit hooks to get
> called. Should it?

I'd consider that to be highly unusual.  Certainly, the C atexit(3)
function is called only in response to a call to exit(3) (possibly
implicitly by returning from main), and not by execve(2) or any of its
little friends.

Your specific problem is to do with file descriptors, so it's probably
best dealt with using the close-on-exec flag:

        from fcntl import fcntl, F_GETFD, F_SETFD, F_CLOEXEC

        sk = socket(...)
        ## ...
        fcntl(sk.fileno(), F_SETFD,
              fcntl(sk.fileno(), F_GETFD) | FD_CLOEXEC)

Now the socket will be magically closed when you exec.. another program.

Finally, can I urge against TCP sockets in an application like this?
Certainly without adequate authentication, it will simply be insecure
even within a single multiuser host (e.g., using localhost only) -- and
assuming that even a home machine has only a single user is becoming
less realistic.  Unix-domain sockets live in the filesystem, and access
to them is limited using the standard filesystem mechanisms.

If you're expecting inter-host communications (e.g., remote debugging),
it's a good idea to protect the session using TLS or something (much as
I dislike the TLS certification/public-key- distribution model it's way
better than nothing at all).

-- [mdw]



More information about the Python-list mailing list