Reputation: 35483
The following code opens a socket, sets it to be non-blocking and sends some data over it using UDP, then closes the socket:
int fd = socket(PF_INET, SOCK_DGRAM, 0);
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
sendto(fd, str.c_str(), str.length(), 0,
(struct sockaddr*)&addr, sizeof(addr));
close(fd);
Is there any issue associated with closing the file descriptor as soon as the call to sendto() has completed given that it's non-blocking?
I'm also interested in any thread-safety considerations with doing the above in multiple threads concurrently?
Upvotes: 0
Views: 487
Reputation: 73219
Is there any issue associated with closing the file descriptor as soon as the call to sendto() has completed given that it's non-blocking?
No problems there -- once sendto()
has returned (with a non-error return value), your data has been copied into a system buffer and can be considered "sent". Closing the socket will not prevent the data from going out.
I'm also interested in any thread-safety considerations with doing the above in multiple threads concurrently?
No problems there either -- since there is no data-sharing across threads, there are no race conditions possible.
Upvotes: 3