问题描述
我正在编写一个模仿cp实用程序的程序.但是,我无法获得文件权限才能正常工作.我知道它们存储在结构stat
中,并使用stat
存储在st_mode
字段中.
I am writing a program to mimic the cp utility. However, I cannot get the file permissions to work correctly. I know that they are stored in the structure stat
and stored in the st_mode
field with stat
.
我的问题是我没有获得该组或其他类别的写许可权,即即使源文件是-rwxrwxrwx
,我也获得了-rwxr-xr-x
作为文件的许可权.我在其中设置权限的语句如下.
My issue is that I do not get the write permission for the group or other categories, i.e. I get -rwxr-xr-x
as the permissions for the file even though the source file is -rwxrwxrwx
. The statement where I set the permissions is below.
if ( (dest_fd = open(dest_file, O_WRONLY|O_CREAT, (stats.st_mode & S_IRUSR)|(stats.st_mode & S_IWUSR)|(stats.st_mode & S_IXUSR)|(stats.st_mode & S_IRGRP)|(stats.st_mode & S_IWGRP)|(stats.st_mode & S_IXGRP)|(stats.st_mode & S_IROTH)|(stats.st_mode & S_IWOTH)| (stats.st_mode & S_IXOTH))) < 0)
{
printf("There was a problem opening the destination file.");
exit(EXIT_FAILURE);
}//ends the if statement opening the destination file.
推荐答案
到目前为止,正确的答案是问题是umask
,而不是清除umask
(如果您的程序是多线程的,则很危险.或如果您可能正在调用创建文件的任何库函数)我将把umask
当作用户配置变量,您将不能对其进行修改,而是在创建文件后将其赋予最终权限,然后在文件上调用fchmod
你要.无论如何,授予诸如suid/sgid之类的某些权限可能是必要的,每当修改文件时,某些内核就会将其删除.我最初还将使用模式0600
创建文件,以便在打开文件和更改权限之间没有竞争条件,在此期间其他用户可以在文件上获得打开的句柄.
The answers so far are right that the problem is umask
, but rather than clearing the umask
(this is dangerous if your program is multi-threaded or if you might be calling any library functions that create files) I would treat the umask
as a user configuration variable you are not allowed to modify, and instead call fchmod
on the files after creating them to give them the final permissions you want. This may be necessary anyway to give certain permissions like suid/sgid, which some kernels remove whenever the file is modified. I would also initially create the file with mode 0600
, so that there's no race condition between opening it and changing permissions during which another user could get an open handle on the file.
这篇关于使用open()或creat()创建文件的权限位设置少于我要求的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!