Hind Forsum Hind Forsum - 3 years ago 175
C Question

Unix domain socket error, sendmsg: No buffer space available

I've got a very simple code snippet, try to know how unix domain socket works, I've written the sender function, not yet having receiver function, it 's like below:

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#define ERR_EXIT(m) { \
perror(m); \
exit(EXIT_FAILURE); \
}

void send_fd(int sock_fd, int number){
iovec vec;
vec.iov_base = &number;
vec.iov_len = sizeof(number);

msghdr msg;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &vec;
msg.msg_iovlen = 1;
msg.msg_flags = 0;

int ret = sendmsg(sock_fd, &msg, 0);
if (ret != 1)
ERR_EXIT("sendmsg");
}

int main(void){
int sockfds[2];
if (socketpair(PF_UNIX, SOCK_STREAM, 0, sockfds) < 0)
ERR_EXIT("socketpair");
send_fd(sockfds[1], 20);
return 0;
}


Compile and run it on linux, it prints:

sendmsg: No buffer space available


Well I didn't print this message myself, guess it's printed by sendmsg itself. Where does my program get wrong? I've googled for sometime and check this site, didn't find good clue.

How to fix it? Thanks.



Yes, should add
msghrd msg={0}; to initialize, problem solved!

Answer Source

You need to add a memset after the msghdr initialization:

msghdr msg;
memset(&msg, 0, sizeof(msg));

The problem is that local variables in C (and C++, unless they have constructors) are not initialized. You only initialized some of the fields, but not all of them. The result is that some others (I suspect msg_control) had junk in them, causing the error you witnessed.

In addition to that problem, what other people have said in the comments is also true. The code for error is -1 (or, better, <0).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download