Skip to content
Advertisement

Bad File Descriptor on recv from TCP socket

I’ve got a trouble and can’t google out solution, so I hope you’ll be able to help me.

There is a client-server application, something like text chat.
Server accepts client’s connection, makes new socket for client and sends socket descriptor to it’s child process, that broadcasts received messages to all connected clients.

server.c (error handling and tests are cuted out)

JavaScript

Next, receiver gets fd of new socket and saves it to an array. Receiver’s code looks like that:

JavaScript

Here functions lc_recv_non_block and lc_send_non_block are just normal recv and send with additional error handling for EAGAIN and EWOULDBLOCK (using select() to avoid problems).

For some reason, at this line recv() fails with errno EBADF.

JavaScript

What did I missed and why file descriptor is broken?

Advertisement

Answer

Look at the sendmsg() API for Unix domain sockets, especially the SCM_RIGHTS message type. Basically you build a message using the SCM_RIGHTS message type and an array of file descriptors. Under the covers the receiving side effectively dup()s the file descriptors enabling access to those files.

This is very Linux-specific.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement