问题描述
权限一直被拒绝,但据我所知,我的权限是广泛开放的。
//snip
int outfile = creat("outFile.txt",O_RDWR | O_CREAT | S_IRWXU | S_IRWXG | S_IRWXO);
if (outfile < 0)
{
cout << "\n" << "output file cannot be opened,error" << "\n";
cout << strerror(errno) << "\n";
exit(1);
}
int pagesize = getpagesize();
for (int i=0; i<pagesize; i++)
{
write(outfile,"-",1);
}
//there is code here that outFile.txt has read and write permissions,and it always says read and write are OK
char* target = (char*)mmap(NULL,pagesize,PROT_READ | PROT_WRITE,MAP_SHARED,outfile,0);
if (target == MAP_FAILED)
{
cout << "\n" << "output mapping did not succeed" << "\n";
cout << strerror(errno) << "\n";
exit(1);
}
else
{
cout << "\n" << "output mapping succeeded" << "\n";
}
//snip
这是一个学校项目,我们得到了一个 1GB 的文件,一个 4096 的页面大小,并被告知我们不能只使用 write() 系统调用。
解决方法
int outfile = creat("outFile.txt",O_RDWR | O_CREAT | S_IRWXU | S_IRWXG | S_IRWXO);
这里有两个问题:
-
creat
创建一个只写模式的文件,它的第二个参数是一个mode_t
掩码。在此处传递O_
标志,与S_
模式位一起拍打,会导致无意义的垃圾。 -
mmap
调用的参数需要O_RDWR
文件描述符,并且如上所述,O_RDWR
参数被解释为 文件权限位 而不是文件打开模式。
这应该用open()
代替,带三个参数:
int outfile = open("outFile.txt",O_CREAT | O_TRUNC | O_RDWR,S_IRWXU | S_IRWXG | S_IRWXO);