Question

In my software, I'm using a PF_UNIX-socket for IPC.

Until now I need to allocate a (pre-)buffer via malloc to prepare the data before writing it via write into the buffer.

Now I was wondering:

The socket-fd already has a buffer of eg. 64kb, so why can't I simply directly prepare & write my data into that buffer like in this way:

// stupid example-code, don't copy
void *fd_buffer = get_buffer_of_fd(fd)
fd_buffer[0] = 1
fd_buffer[1] = 2
fd_buffer[2] = 3
memcpy(fd_buffer, 5, 5)
...
commit_buffer_of_fd(fd, xbytes); // xBytes is DYNAMIC and not known until this point!!

If this would be possible, I could save the roundtrip of copying into the pre-buffer, writing into the socket from the pre-buffer and even allocate the pre-buffer.

Has anyone an idea if that is possible?

Était-ce utile?

La solution

The socket buffer is owned by the kernel, you will never be allowed to write into kernel space. Never, ever. Too much of a security risk.

The only way to do zero-copy is to use vmsplice(2), but it is not officially supported for sockets and is not recommended to use for anything other then pipes.

If you do decide to use vmsplice, keep in mind that you must then commit your data in chunks of pages sysconf(_SC_PAGESIZE). Also it is a Linux only syscall and not portable.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top