Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose to set SOCK_CLOEXEC flag with accept4() same as O_CLOEXEC

Basically, I need to know what is the purpose of setting the SOCK_CLOEXEC when sitting it with accept4(). how can I check the functionality of this flag with the returned file descriptor from the accept.

accepted_fd =   accept4(sd, (struct sockaddr *)& tcp_remote, &size,  SOCK_CLOEXEC);
like image 835
Hatem Mashaqi Avatar asked Mar 10 '14 15:03

Hatem Mashaqi


1 Answers

The reason for SOCK_CLOEXEC to exist is to avoid a race condition between getting a new socket from accept and setting the FD_CLOEXEC flag afterwards.

Normally if you want the file descriptor to be close-on-exec you'd first obtain the file descriptor in some way, then call fcntl(fd, F_SETFD, FD_CLOEXEC). But in a threaded program there is a possibility for a race condition between getting that file descriptor (in this case from accept) and setting the CLOEXEC flag. Therefore Linux has recently changed most (if not all) system calls that return new file descriptors to also accept flags that tell the kernel to atomically set the close-on-exec flag before making the file descriptor valid. That way the race condition is closed.

If you wonder why close on exec exists, it's because in some cases, especially when you're executing non-privileged programs from a privileged one, you don't want some file descriptors to leak to that program.

like image 132
Art Avatar answered Sep 19 '22 05:09

Art