如何忽略umask以创建具有给定权限的文件
我正在使用 open 函数并使用 O_CREAT | 创建一个文件O_EXCEL。我已将模式传递为“0666”。但通过屏蔽最终分配给它的权限是 -rw-r--r-- 而不是 -rw-rw-rw- 。有人告诉我我可以使用 umask (011),然后再次重置原始掩码。 但我不知道如何在 C++ 程序中传递它。这是我正在做的事情的一小段。
# include <iostream>
# include <stdio.h>
# include <conio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main()
{
int fd = open("C:\\Users\\Ritesh\\Music\\music.txt", O_CREAT | O_EXCL, 0666);
getch();
return 0;
}
使用权限 -rw-r--r-- 创建文件
我希望它是 C:\Users\Ritesh\Music\music.txt
。-rw -rw-rw-
I am creating a file using open function and using O_CREAT | O_EXCEL . I have passed the mode as "0666" . But by masking finally the permission allotted to it is -rw-r--r-- and not the
-rw-rw-rw- . Someone told me i can use umask (011) and then reset the original mask again .
But i dont know how to pass this in c++ program. This is the small snippet of What i am doing .
# include <iostream>
# include <stdio.h>
# include <conio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
int main()
{
int fd = open("C:\\Users\\Ritesh\\Music\\music.txt", O_CREAT | O_EXCL, 0666);
getch();
return 0;
}
creates file C:\Users\Ritesh\Music\music.txt
with permission -rw-r--r-- .
I want it to be -rw-rw-rw-
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
umask 表示默认情况下您不想授予文件的权限。因此,如果你想在创建文件时完全控制权限,请将umask设置为0,这告诉操作系统不要保留任何权限,让你做主。像这样:
umask means permissions that you don't want to give to files by default. So if you want to control the permissions completely while creating a file, set umask to 0, which tells the os don't reserve any permissions and let you call the shot. like this:
将文件权限设置为您想要的唯一线程安全方法是使用
chmod()
或fchmod()
创建文件后(示例没有错误检查):如果您使用
umask()
,您将更改整个过程的umask
值。如果任何其他线程正在运行,您将面临使用意外权限创建文件的风险,这可能会导致安全问题或其他问题。当您更改的umask
值生效时创建的任何子进程都将使用意外的umask
值创建。The only thread-safe way to set file permissions to be what you want is to set them explicitly with
chmod()
orfchmod()
after creating the file (example without error checking):If you use
umask()
, you will change theumask
value for the entire process. If any other threads are running you risk files getting created with unexpected permissions, which could lead to a security issue or other problems. And any child process created while your changedumask
value is in effect will be created with an unexpectedumask
value.