Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bridging between two file descriptors

I have a socket I'm doing select() on it, waiting for other process to write. Once it write, I read the data, and write it to another file descriptor. My question is, if there's a way to bridge the socket to the file descriptor, so when there's data ready, it will be automatically written to the other file descriptor ?

This way, I could throw a way the buffer I'm using, and omit a thread in the system.

like image 875
stdcall Avatar asked Mar 12 '13 06:03

stdcall


People also ask

Can a file have two file descriptors?

One process can have multiple file descriptors point to the same entry (e.g., as a result of a call to dup() ) Multiple processes (e.g., a parent and child) can have file descriptors that point to the same entry.

Can file descriptors be shared between processes?

File descriptors are generally unique to each process, but they can be shared by child processes created with a fork subroutine or copied by the fcntl, dup, and dup2 subroutines.

Do Threads share the same file descriptors?

Threads in the same process share an address space and file descriptor table, so we do not need to save the page-table root pointer or the fd table.

What are the 3 standard file descriptors?

Stdin, stdout, and stderr On a Unix-like operating system, the first three file descriptors, by default, are STDIN (standard input), STDOUT (standard output), and STDERR (standard error).


2 Answers

On linux, using splice() might be more suitable, when the direction is from socket to file. Using splice() is a bit more complicated, but you get both directions. Also, I think sendfile uses splice internally these days.

There are many questions on SO already discussing the differences between splice() and sendfile(). Searching the web also reveals conflicting statements on what (sources and destinations) splice works for. The best way to know if it is suitable for your case, is to test it.

SO about compatible filesystems: Which file systems support splicing via Linux's splice(2)?

SO about old kernels not supporting splice for TCP sockets: Does Linux's splice(2) work when splicing from a TCP socket?

Splice explained: http://kerneltrap.org/node/6505

Splice source: http://lxr.linux.no/#linux+v3.8.2/fs/splice.c

like image 111
thuovila Avatar answered Oct 09 '22 01:10

thuovila


Sorry if I misunderstood your situation, but do you mean something like sendfile?

sendfile - transfer data between file descriptors

#include <sys/sendfile.h>
ssize_t sendfile(int out_fd, int in_fd, off_t * offset ", size_t" " count" );

sendfile() copies data between one file descriptor and another. Because this copying is done within the kernel, sendfile() is more efficient than the combination of read(2) and write(2), which would require transferring data to and from user space.

like image 27
Jorge Israel Peña Avatar answered Oct 09 '22 00:10

Jorge Israel Peña