[Python-Dev] Assign to errno allowed?

M.-A. Lemburg mal@lemburg.com
Tue, 24 Sep 2002 16:00:38 +0200

Thomas Heller wrote:
> I'm trying to fix selectmodule.c on Windows (it raises
> bogus exceptions, because select() on Windows does not
> set errno).
> The first patch I had was this:
>    if (n < 0) {
> + #ifdef MS_WINDOWS
> +   PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());
> + #else
>     PyErr_SetFromErrno(SelectError);
> + #endif
>    }
>    else if (n == 0) {
>                   /* optimization */
> but PyErr_SetExcFromWindowsErr is not present in the 2.2
> maintainance branch. An easier fix would be this one, but
> I wonder if it is allowed/good style to set 'errno':
> *** 274,279 ****
> --- 274,282 ----
>    if (n < 0) {
> + #ifdef MS_WINDOWS
> +   errno = WSAGetLastError();
> + #endif
>     PyErr_SetFromErrno(SelectError);
>    }
>    else if (n == 0) {

Here's what the man page has to say:

        errno - number of last error

        #include <errno.h>

        extern int errno;

        The  integer errno is set by system calls (and some library functions)
        to indicate what went wrong.  Its value is significant only  when  the
        call  returned an error (usually -1), and a library function that does
        succeed is allowed to change errno.

        Sometimes, when -1 is also a legal return value one has to zero  errno
        before the call in order to detect possible errors.

        errno  is  defined  by the ISO C standard to be a modifiable lvalue of
        type int, and must not be explicitly declared; errno may be  a  macro.
        errno  is  thread-local;  setting it in one thread does not affect its
        value in any other thread.

        Valid error numbers are all non-zero; errno is never set  to  zero  by
        any  library  function.  All the error names specified by POSIX.1 must
        have distinct values.


Setting errno is allowed; in fact, it is required to set it to 0
sometimes in order to narrow down the location of an error (in a
sequence of C library calls).

Marc-Andre Lemburg
CEO eGenix.com Software GmbH
eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,...
Python Consulting:                               http://www.egenix.com/
Python Software:                    http://www.egenix.com/files/python/