nanomsg
Home Download Documentation Development Community Support
NOTE: This documentation is for version 1.0.0 of nanomsg, but the latest released version is 1.1.5. Please see the documentation for 1.1.5 for the most up-to-date information.
nn_recv(3)

SYNOPSIS

#include <nanomsg/nn.h>

int nn_recv (int s, void *buf, size_t len, int flags);

DESCRIPTION

Receive a message from the socket s and store it in the buffer referenced by the buf argument. Any bytes exceeding the length specified by the len argument will be truncated.

Alternatively, nanomsg can allocate the buffer for you. To do so, let the buf parameter be a pointer to a void* variable (pointer to pointer) to the receive buffer and set the len parameter to NN_MSG. If the call is successful the user is responsible for deallocating the message using the nn_freemsg(3) function.

The flags argument is a combination of the flags defined below:

NN_DONTWAIT

Specifies that the operation should be performed in non-blocking mode. If the message cannot be received straight away, the function will fail with errno set to EAGAIN.

RETURN VALUE

If the function succeeds number of bytes in the message is returned. Otherwise, -1 is returned and errno is set to to one of the values defined below.

ERRORS

EBADF

The provided socket is invalid.

ENOTSUP

The operation is not supported by this socket type.

EFSM

The operation cannot be performed on this socket at the moment because socket is not in the appropriate state. This error may occur with socket types that switch between several states.

EAGAIN

Non-blocking mode was requested and there’s no message to receive at the moment.

EINTR

The operation was interrupted by delivery of a signal before the message was received.

ETIMEDOUT

Individual socket types may define their own specific timeouts. If such timeout is hit this error will be returned.

ETERM

The library is terminating.

EXAMPLES

Receiving a message into a buffer allocated by the user

This example code will retrieve a message of either 100 bytes or less. If a larger message was sent it will be truncated to 100 bytes.

char buf [100];
nbytes = nn_recv (s, buf, sizeof (buf), 0);
Receiving a message into a buffer allocated by nanomsg

The following will get a message from the pipe with a buffer allocated by the system. It is large enough to accommodate the entire message. This is a good way to get the entire message without truncating if the size of the message is unknown. It is the user’s responsibility to call nn_freemsg(3) after processing the message.

void *buf = NULL;
nbytes = nn_recv (s, &buf, NN_MSG, 0);

if (nbytes < 0) {
    /* handle error */
    ...
}
else {
    /* process message */
    ...
    nn_freemsg (buf);
}

Note that this can be more efficient than manually allocating a buffer since it is a zero-copy operation.

SEE ALSO

AUTHORS

"nanomsg" is a trademark of Garrett D'Amore.