简体   繁体   中英

Closing a UDP Socket when using Non-Blocking IO

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM