Protv recv ()

By introducing man recv() into my system, I get:

  ssize_t recv(int socket, void *buffer, size_t length, int flags); โ€ฆ RETURN VALUES These calls return the number of bytes received, or -1 if an error occurred. 

Note that length is of unsigned type size_t , and the result of the function is signed ssize_t .

If the SSIZE_MAX value for length exceeds the value of SSIZE_MAX , how theoretical is the situation when recv() fills the memory indicated by buffer and returns a negative value other than -1 ? Are there types of sockets that allow very long messages (Unix domain?)? What about MSG_WAITALL ?

+6
source share
1 answer

Here is what the Posix 2008 explanation has to say about ssize_t (extracted from B.2.12 Data Types ):

ssize_t
This is supposed to be a signed counterpart to size_t. The wording is that an implementation can either choose a longer type, or simply use a signed version of the type underlying size_t. All functions returning ssize_t (read () and write ()) are described as "implementation-defined" results of input greater than {SSIZE_MAX}.

Actually, this is not entirely true, since the socket functions returning ssize_t , including recv , do not say anything about SSIZE_MAX input SSIZE_MAX . Therefore, I take this as an expression of intent, implying that the missing wording in recv is a mistake that can be fixed some day.

In short, if you want to write portable code, you need to make sure that the I / O segments do not exceed SSIZE_MAX . In addition, SSIZE_MAX may be 32767. Therefore, portable code should not assume that it could be larger.

However, not everyone cares about portability. You may know something about the implementation of your code. Posix continues:

It is known that some implementations may have ints that are smaller than size_t. The corresponding application would be limited to not perform I / O operations on chunks larger than {SSIZE_MAX}, but the corresponding application using the extensions could use the full range if the implementation provided an extended range, while there was still one type-compatible interface .

Posix ensures that the only values โ€‹โ€‹returned by recv are -1, 0, or the number of bytes received. The corresponding implementation in accordance with the above formulation may display values โ€‹โ€‹greater than SSIZE_MAX , but less than or equal to 2*SSIZE_MAX for negative integers other than -1 . (How this can be done remains as an exercise for the interested reader :)). Linux, as far as I know, does not document any such extension.

+6
source

Source: https://habr.com/ru/post/947778/


All Articles