Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Unix Domain Socket with a specific permissions in C?

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.

like image 889
abyss.7 Avatar asked Nov 24 '13 06:11

abyss.7


1 Answers

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):

// Create a directory with the proper permissions mkdir(path, 0700); // Append the name of the socket strcat(path, "/socket_name");  // Create the socket normally sockaddr_un address; address.sun_family = AF_UNIX; strcpy(address.sun_path, path); int fd = socket(AF_UNIX, SOCK_STREAM, 0); bind(fd, (sockaddr*)(&address), sizeof(address)); listen(fd, 100); 
like image 194
Elias Mårtenson Avatar answered Sep 18 '22 12:09

Elias Mårtenson