Reputation: 6863
I'm creating a file in C using the following code:
int outfd = open(arg,O_CREAT|O_TRUNC|O_WRONLY, f_per);
f_per
being the file permission numbers.
Setting f_per
to 0644
, executing the code and doing an ls -l gives me the (output) file permissions set as -rw-r--r--
which is expected. However, setting things to 0777 gives permissions as -rwxrwxr-x
instead of -rwxrwxrwx
. Any idea why this happens?
Upvotes: 2
Views: 279
Reputation: 881333
As per the POSIX page for the open
call, under O_CREAT
:
... the access permission bits of the file mode shall be set to the value of the argument following the oflag argument taken as type
mode_t
modified as follows: a bitwise AND is performed on the file-mode bits and the corresponding bits in the complement of the process' file mode creation mask.
The mode creation mask (or umask) can be considered a subtractive one. For example, if you attempt to create a file with permissions rwxrwxrwx/0777
when your file mode creation mask is -------w-/0002
, you'll actually end up with:
rwxrwxrwx
& rwxrwxr-x (complement of -------w-)
=========
rwxrwxr-x
This appears to be the situation you are encountering.
If you want to actually create a file of the specific permissions, you can temporarily disable the umask by setting it to zero (and restoring it afterwards), something like:
mode_t oldmask = umask(0); // needs sys/stat.h
int outfd = open(arg, O_CREAT|O_TRUNC|O_WRONLY, 0777);
umask(oldmask);
Upvotes: 1