Search code examples
pythoncdistutilscpython

What on earth...? File permissions from files created by Python C code


If I have the following C code:

int main(int argc, char **arg)
{
    int x = open("testfilefromc", O_RDWR | O_CREAT);
    return 0;
}

which when I compile and run not unreasonably creates this:

-rw-r-----   1 joewass  staff     0B 31 Jan 21:17 testfilefromc

But the following C code, compiled into a Python module:

const char *filename = "testfilefrompython";
context->fd = open(filename, O_RDWR | O_CREAT);

does this:

----------   1 joewass  staff   165B 31 Jan 21:09 testfilefrompython

And not surprisingly the code that created the file can't open it next time round!

Why on earth would the file be created with zero permissions? And why would the behaviour be different in C compiled into a Python module? I'm running the python program that runs the code as me.

For what it's worth, I'm mmaping the file later on.

Thanks!

Joe

EDIT :I know I can chmod to fix this, the question is why?

EDIT 2: Thanks to Rosh Oxymoron for pointing out that I missed the not-so-optional optional argument. TRWTF is that the first example worked at all!


Solution

  • The function open takes three arguments. If you specify the O_CREAT flag, you need to call it with this signature:

    int open(const char *pathname, int flags, mode_t mode);
    

    Otherwise the behaviour is undefined. It's very unlikely for the creation of the file in your first example to work at all. Also take a look at umask which is always ANDed with the mode that you specify.