[nanomsg] Re: When is it safe to use NN_MSG?

  • From: Eduardo Morras <emorrasg@xxxxxxxx>
  • To: nanomsg@xxxxxxxxxxxxx
  • Date: Wed, 11 Dec 2013 11:57:35 +0100

On Wed, 11 Dec 2013 03:27:55 +0100
Stefan de Konink <stefan@xxxxxxxxx> wrote:

> I'm currently using a construction where an iov contains a uint32_t and a 
> struct. It make sense that I have to manually set iov_len with the 
> appropriate sizes of these objects.
> 
> When receiving the object back, I should receive a string-like object 
> (instead of the struct). I was expecting I could use a lazy method let 
> nanomsg do my allocation like in the test.
> 
> https://github.com/nanomsg/nanomsg/blob/master/tests/msg.c#L81
> 
> For some reason I cannot get the following to work, either response side 
> remains 0x0 or it plainly hangs.
> 
> Sender>>
>         void *msg = nn_allocmsg(result_length, 0);
>         strncpy(msg, result_buf, result_length);
>         iov[0].iov_base = &sd;
>         iov[0].iov_len = sizeof(uint32_t);
>         iov[1].iov_base = &msg;
>         iov[1].iov_len = NN_MSG;
>         bzero (&hdr, sizeof (hdr));
>         hdr.msg_iov = iov;
>         hdr.msg_iovlen = 2;
>         nn_sendmsg(sock, &hdr, 0);
> 
> <<Receiver
>             char *response = NULL;
>             uint32_t sd;
>             struct nn_msghdr hdr;
>             struct nn_iovec iov [2];
>             iov [0]iov_base = &sd;
>             iov [0].iov_len = sizeof(uint32_t);
>             iov [1].iov_base = &response;
>             iov [1].iov_len = NN_MSG;
>             bzero(&hdr, sizeof (hdr));
>             hdr.msg_iov = iov;
>             hdr.msg_iovlen = 2;
>             nn_recvmsg (broker_socket, &hdr, 0);
> 
> 
> When I change the iov[1] parts on both sides to preallocated buffers, with a 
> fixed size, I do get messages around. Could someone give a hint?

First, I don't know. I'm begining to develop with nanomsg. But, from 
documentation, http://nanomsg.org/v0.2/nn_sendmsg.3.html , after the successful 
nn_sendmsg(sock, &hdr, 0); 

"Alternatively, to send a buffer allocated by nn_allocmsg(3) function set 
iov_base to point to the pointer to the buffer and iov_len to NN_MSG constant. 
In this case a successful call to nn_send will deallocate the buffer. Trying to 
deallocate it afterwards will result in undefined behaviour. Also, scatter 
array in nn_msghdr structure can contain only one element in this case."

So internal iov data becomes corrupted, perhaps because msg is deallocated and 
NN_MSG is modified.

> 
> Stefan

HTH
---   ---
Eduardo Morras <emorrasg@xxxxxxxx>

Other related posts: