On Sep 18, 2009, at 2:36 PM, Peter Stuge wrote:

Mikhail Gusarov wrote:
PS> Sure, but why does that matter? fds that would block just shouldn't
PS> be processed at that time?

* select() returns 'ok, you can write to fd N'.
* You call write(N, buf, size).
* It blocks after writing size/2.
* ...
* PROFIT

Do a lot of systems actually block there instead of having write()
return size/2?

It depends on the blocking mode. If it's a non-blocking socket, it [obviously] never blocks, it may do what it can and then return EAGAIN to avoid blocking. So if it can write size/2, it will, then you subtract byes sent from size, increment the ptr by bytes sent, then loop around and keep trying until you have no data left to send -- the select() call is used to block while you're waiting on the socket to be ready.

For blocking sockets, I don't think there's any guarantee that it'll block or not. It may write size/2 and then it'll block the next time around. Or it may block until it can write the entire amount. In either case, I always code a loop that assuming that write()/send() may not actually send the entire buffer -- the man pages (at least on the Mac) aren't really clear. Same goes for read()/recv(), you ask for 256 bytes, you may only get 64, so you must loop (you may have always gotten 256 bytes in testing, but on site, fragmentation may cause the packet to get broken up).

As far as I'm aware, the reasons for using non-blocking socket are two fold:

1) Multiplexing: you can wait on a number of sockets at once and process them in a timely fashion 2) Timeouts: TCP stacks vary in their timeouts, if you want to fail after a 30s delay, then you can specify a timeout with select() -- connect() is a good example of this, you may not want your users to sit waiting on 'ssh' to timeout for 2-3 minutes because they mistyped the IP address.

Also, I think in some OS's, you may get better performance with non- blocking sockets vs blocking ones. But using non-blocking sockets does also complicate the code a little (this is where the Stevens book comes in handy!).

_______________________________________________
libssh2-devel http://cool.haxx.se/cgi-bin/mailman/listinfo/libssh2-devel

Reply via email to