c++,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);

最新更新