0

I made a little project some weeks ago, but it somehow didn't work anymore recently (or at least, not like it previously worked).

It had to create a file with open(), and fill it with some content.

[...]
int fd=open(filename, O_RDWR | O_CREAT);
/* write content */
close(fd);
[...]

The problem was just that it recently didn't create the file with the right permissions anymore (it was created with 0110 when the problem was occurring)

I now know that I just have to specify the permissions like this :

int fd=open(filename, O_RDWR | O_CREAT, 0700); /* (for instance) */

But the project still worked on some computers (Didn't work on OSX, but did work on a Linux, on which it was created with 0640, so it still worked because I still had reading permission).

So here is my question:

  • How are those default permissions defined for open() function at file creation?

(If I don't explicitly pass it to my open() call as a parameter.)

vmonteco
  • 14,136
  • 15
  • 55
  • 86
  • 1
    What does your manual page tell you? – Jens Apr 18 '17 at 18:12
  • 2
    "[The `mode`] argument *must* be supplied when `O_CREAT` is specified in flags". (Emphasis mine) This makes it sound like it's undefined behaviour when you don't, and I do indeed get junk when I omit it (`--wS--S--T`). – ikegami Apr 18 '17 at 18:13
  • @ikegami And that undefined behavior could result in something like [this](http://stackoverflow.com/q/2245193/6850771). – MD XF Apr 18 '17 at 18:13
  • One of the wonders of undefined behaviour is that sometimes it will seem to work — and at other times, it won't. – Jonathan Leffler Apr 18 '17 at 18:17
  • @WumpusQ.Wumbley Indeed. My bad, I messed my copy-paste, I edited my post. Thank you for bringing this to my attention. – vmonteco Apr 18 '17 at 18:21

2 Answers2

4

There is no default. You must specify them when you use O_CREAT.


According to the documentation on my system,

[The mode] argument must be supplied when O_CREAT is specified in flags

(Emphasis mine)

This makes it sound like it's undefined behaviour when you don't, and I do indeed get junk when I omit it (--wS--S--T).

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • `[open()] require an additional argument mode_t mode; the file is created with mode mode as described in chmod(2) and modified by the process' umask value (see umask(2)).` It looks like you're right! My bad, I was searching for a "permissions" keyword in my man. Thank you for this answer. – vmonteco Apr 18 '17 at 18:24
0

You need to specify the mode arguments as an integer containing a set of bit flags. Something like:

 int fd=open(filename, O_RDWR | O_CREAT, S_IRWXU | S_IRWXG); 

See the man page for chmod. The call also uses the process umask to limit things.

DrC
  • 7,528
  • 1
  • 22
  • 37