Search code examples
c++linuxmmap

c++, linux - mmap() permission denied on file created by program, created file has all permissions open


The permission keeps being denied, but as far as I can tell, my permissions are wide open.

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

This is for a school project, we're given a 1GB file, a 4096 page size, and told we can't just use a write() system call.


Solution

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

    Two problems here:

    1. creat creates a file in write-only mode, and it's second parameter is a mode_t mask. Passing O_flags here, slapped together with S_ mode bits, results in nonsensical garbage.

    2. The parameters to the mmap call require a O_RDWR file descriptor, and as explained above the O_RDWR parameter gets interpreted as a file permission bits and not a file open mode.

    This should be replaced by open(), with three parameters:

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