0

I have non-blocking socket (TCP or UPD socket) with using kqueue/epoll (FreeBSD/Linux). When I want to transmit bytes to other side I can use write/send/sendto. Each of them take char* buffer to transmit, but I don`t understand when I have to free memory of buffer after calling write/send/sendto.

  1. Is it correct that if write/send/sendto return the number of bytes accepted and this number equals buffer size, I can free memory of buffer immediately? Or I have to wait EVFILT_WRITE (kqueue) or EPOLLOUT (Linux) events to free memory of buffer?
  2. Is it correct that if write/send/sendto return the number of bytes accepted and this number doesn't equal buffer size, I can free only bytes accepted immediately and I have to wait EVFILT_WRITE (kqueue) or EPOLLOUT (Linux) events to continue transmit not accepted bytes and next bytes? Or I have to wait EVFILT_WRITE (kqueue) or EPOLLOUT (Linux) events to free memory of buffer and transmit next bytes?
  3. Is it correct that if write/send/sendto return EAGAIN (kqueue) or EAGAIN || EWOULDBLOCK (Linux), I can`t free memory of buffer and I have to wait EVFILT_WRITE (kqueue) or EPOLLOUT (Linux) events to retransmit the same bytes?
sribin
  • 1,736
  • 1
  • 13
  • 21
  • Are you asking if the OS is still using your `const void *msg` buffer after the `send(2)` system call returns? – Richard Smith Oct 23 '19 at 11:03
  • @RichardSmith yes, with non-blocking socket. – sribin Oct 23 '19 at 11:44
  • I am pretty sure that the first task of a system call is to copy the buffers from user space to kernel space so it is always safe to free the buffer as soon as the system call returns. Of course, if the message is not completely transmitted, you will still need to make another system call with the remaining part of the message. – Richard Smith Oct 23 '19 at 12:05

1 Answers1

0

Although you are using non-blocking sockets, the write/send/sendto calls are still synchronous. It means that you can free the buffer right after it tells you that the call is success.

1. YES

When write/send/sendto returns the complete buffer size, it means the whole content of buffer has been copied to socket send buffer, you can free the buffer right away.

2. YES

When write/send/sendto returns partial size, you should wait for next writable event to send remaining bytes.

3. YES

EAGAIN or EWOULDBLOCK means the writing buffer is full when writing to non-blocking sockets. You should send those bytes again.

NitroMelon
  • 36
  • 3