I have a simple code, like:
sockaddr_un address;
address.sun_family = AF_UNIX;
strcpy(address.sun_path, path);
unlink(path);
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
bind(fd, (sockaddr*)(&address), sizeof(address));
listen(fd, 100);
I want to atomically create the Unix Domain Socket file with a specific permissions, say: 0777
. The manual doesn't say anything about socket file permissions with regard to umask
or whatever. Even, if the umask
does affect the socket file, then it's not an atomic way - in multi-threaded program.
I hope, there is a way to achieve my goal without using synchronization of umask()
calls.
I had the best luck using chmod() (NOT fchmod) using the file name for the unix domain socket after calling socket(), bind(), but, before calling listen().
. . . . .
Another solution is to create a directory with the desired permissions, and then create the socket inside it (example code without any regard for error checking and buffer overflows):
Forking, using umask and passing back the fd is the only portable way I can think of. Having a directory for the socket is better in any case, for example nobody can delete the socket if the directory doesn't ahve the proper permissions, and creating diretcories can be done atomically.
The bigger problem is that relying on permissions is not portable - many BSD-derived socket stacks simply ignore the permissions of enclosing directories and/or the socket itself.
On GNU/Linux systems, you cna do it by calling fchmod on the socket fd after socket() and before bind()