Subject: Usage of errno and thread-safety

Usage of errno and thread-safety

From: Sebastien Fricker <Sebastien.Fricker_at_ipetronik.com>
Date: Fri, 11 Mar 2011 17:28:07 +0100

Hi,
I saw in the daily snapshot that errno is only used in _libssh2_send()
and _libssh2_recv().
That's good because it permits to better adapt libssh2 to other
platforms.

But I'm guessing if it is not possible to get rid of errno:
errno is a global error information that contain an error code but not
systematically from the actual socket.
Using this variable makes libssh2 not thread safe.

In fact _libssh2_send()/_libssh2_recv() returns only 3 values:
 1) >=0: number of bytes transmitted/received
 2) -EAGAIN: special error which indicates that the read/write
operation should be re-executed.
 3) <0 (but not -EAGAIN): real error.

Would it not be possible to use select to generate such error code?
This would made the _libssh2_send()/_libssh2_recv() thread safe.

For example:
ssize_t _libssh2_recv(libssh2_socket_t sock, void *buffer, size_t
length, int flags)
{
    ssize_t rc = recv(sock, buffer, length, flags);
    if (rc < 0 )
        return -errno;
    return rc;
}

would be rewritten something like:
ssize_t _libssh2_recv(libssh2_socket_t sock, void *buffer, size_t
length, int flags)
{
    ssize_t rc = recv(sock, buffer, length, flags);
    if (rc < 0 )
    {
      int res;
      fd_set sready;
      struct timeval nowait;

      FD_ZERO(&sready);
      FD_SET((unsigned int)sock,&sready);
      memset((char *)&nowait,0,sizeof(nowait));

      res = select(sock+1,&sready,NULL,NULL,&nowait); /* select without
timeout */
      if (res<0)
        return -EIO; /* Select gives an error */
      else if( FD_ISSET(sock,&sready) )
        return -EAGAIN; /* this should not occurs often: recv does not
receive, but just after it does */
      else
        return -EAGAIN; /* socket not ready */
    }
    return rc;
}

I'm not sure if this code works.

I'm waiting for comments.
Sébastien

 

-- 
------------------------------------------------------------
Ipetronik GmbH & Co.KG
Jaegerweg 1
D-76532 Baden-Baden
 
Phone-No. +49 - (0)7221/9922-467
Fax-No. +49 - (0)7221/9922-153
 
mailto: sebastien.fricker_at_ipetronik.com
web: http://www.ipetronik.com 
 
------------------------------------------------------------
Kommanditgesellschaft mit Sitz in Baden-Baden, Registergericht HRA
Nr.201313
Persoenlich haftende Gesellschaft ist die IPETRONIK Verwaltungs GmbH 
mit Sitz in Baden-Baden, Registergericht Mannheim HRB Nr.202089, 
Geschäftsführer: J.Abromeit, E.Rudolf, A. Wocke
-------------------------------------------------------------
 
 
_______________________________________________
libssh2-devel http://cool.haxx.se/cgi-bin/mailman/listinfo/libssh2-devel
Received on 2011-03-11