[cs631apue] File permission Control use oflag and mode

Jan Schaumann jschauma at stevens.edu
Sat Sep 14 15:47:44 EDT 2013


Hongyi Shen <hshen4 at stevens.edu> wrote:
 
> int open(const char *pathname, int oflag, ... /* mode_t mode */ );
> 
> 
> Both *oflag* and *mode could *control the file's permission. So both of
> them call stat() inside?

Not quite in the way you seem to think.

As we will see in our next class, stat(2) retrieves the meta information
about a file.  When we open(2) a file, we may in fact be requesting
permissions not granted to us (such as when we attempt to open a file in
read-write mode that has permissions that do not allow the user in
question to write to the file), and the open(2) call will check these
permissions and then fail.  It does not, however, make an extra call to
stat(2).

> *Question: What if they are conflict with each other? (like O_RDONLY and
> mode 0777 together)*

Those are two different things.  The second argument to open(2),
(O_RDONLY, O_RDWR, O_WRONLY) refers to what you want to do with the
filehandle once you have it.  The existing permissions on an existing
fail may prevent you from opening the file in a given mode.

The third argument to open(2) only comes into play when you are creating
a _new_ file.  In that case, the new file will need to be given certain
permissions, which are independent of what you currently do with the
file handle you create

What's more, the mode passed is used in combination with the process's
umask value (which we will cover in a future class in more detail), as
noted in the manual page:

,----[ from open(2) on linux-lab ]
|
| mode specifies the permissions to use in case a new file is created.
| This argument must be supplied when O_CREAT is specified in flags;  if
| O_CREAT is not specified, then mode is ignored.  The effective
| permissions are modified by the process's umask in the usual way: The
| permissions of the created file are (mode & ~umask). Note that this mode
| only applies to future accesses of the newly created file; the open()
| call that creates a read-only file may well return a read/write file
| descriptor.
|
`----

-Jan


More information about the cs631apue mailing list