Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the consequences of calling write() with zero length?

At fairly high level in the Linux write() function, it filters out requests for writing 0 length buffers. Which makes sense. Who'd want to the OS wasting its time drilling through layers only to determine there is no work to be done?

Well ... me.

It's related to I2C write acknowledge polling in Linux Kernel; and the discovery that the bit-banged I2C driver will give a potentially useful return code if the address (sent on the bus before data) will give an error if the handshaking is wrong.

One could send dummy data after the address, but not with the device I'm using. (Perhaps I'll try a read ...).

So the question is: What sort of hell would be unleashed if the kernel were to allow zero (0) length writes?

like image 824
Jamie Avatar asked Aug 10 '09 14:08

Jamie


3 Answers

What you're describing amounts to essentially the same sort of evil that infests several Windows APIs that need unpredictable amounts of memory. The practice is to call them with no buffer to place their work in, they do the work anyway, without storing the results, but counting the number of bytes they'd need along the way. Then you allocate a buffer of that size, and call the function again with the buffer, knowing the size.

This is indescribably evil. It's the computer programming equivalent of a decayed bureaucracy, where each department requires you to fill out a form that has most of the same information on it as the one you gave to the previous department, but since there is some different info on each form, they won't just take a copy of the form you gave the other guys. Ptui!

Programmer time is expensive, CPU time is cheap. Requiring programmers to write the same API call N times to suss out some world state that the API itself could work out on its own tries to flip this on its head.

Best practice, then, is to have the driver do everything it can to make sure your write() succeeds. If it's possible to predict in advance that it cannot succeed by checking some state of the world, maybe that should be an ioctl().

like image 50
Warren Young Avatar answered Nov 15 '22 08:11

Warren Young


Just for the sake of closure, I'm going with Warren Young's idea of updating the driver and publishing the patch (when I get a round tuit).

like image 30
Jamie Avatar answered Nov 15 '22 10:11

Jamie


Very little, I'd think - it might be possible that a zero-length write would block if the buffer it's writing to has zero available space as well, in some drivers. Disallowing zero-length writes could make things simpler in cases like that - as well as avoiding a lot of wasted work.

Why not just remove that check and see what kind of hell actually breaks loose? :)

like image 27
bdonlan Avatar answered Nov 15 '22 09:11

bdonlan