如何在 C 中创建具有特定权限的 Unix 域套接字? [英] How to create Unix Domain Socket with a specific permissions in C?

查看:44
本文介绍了如何在 C 中创建具有特定权限的 Unix 域套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的代码,例如:

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

我想自动创建具有特定权限的 Unix 域套接字文件,例如:0777.该手册没有说明关于 umask 或其他任何内容的套接字文件权限.甚至,如果 umask 确实影响了套接字文件,那么它也不是原子方式 - 在多线程程序中.

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.

我希望,有一种方法可以在不使用 umask() 调用同步的情况下实现我的目标.

I hope, there is a way to achieve my goal without using synchronization of umask() calls.

推荐答案

另一种解决方案是创建一个具有所需权限的目录,然后在其中创建套接字(示例代码不考虑错误检查和缓冲区溢出):

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

这篇关于如何在 C 中创建具有特定权限的 Unix 域套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆