c ++,linux - 程序创建的文件的 mmap() 权限被拒绝,创建的文件已打开所有权限

问题描述

权限一直被拒绝,但据我所知,我的权限是广泛开放的。

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

这里有两个问题:

  1. creat 创建一个只写模式的文件,它的第二个参数是一个 mode_t 掩码。在此处传递 O_ 标志,与 S_ 模式位一起拍打,会导致无意义的垃圾。

  2. mmap 调用的参数需要 O_RDWR 文件描述符,并且如上所述,O_RDWR 参数被解释为 文件权限位 而不是文件打开模式。

这应该用open()代替,带三个参数:

int outfile = open("outFile.txt",O_CREAT | O_TRUNC | O_RDWR,S_IRWXU | S_IRWXG | S_IRWXO);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...