使用open()或creat()创建文件的权限位设置少于我要求的 [英] Creating a file with open() or creat() has fewer permission bits set than I asked for

查看:163
本文介绍了使用open()或creat()创建文件的权限位设置少于我要求的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个模仿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()创建文件的权限位设置少于我要求的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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