user9623401
user9623401

Reputation:

How does mode affect the permisson on newly created files in Linux?

I'm new to Linux, still struggling to understand how permisson control work in Linux. The open function prototype is sth like :

int open(char *filename, int flags, mode_t mode);

Let's I have the following code:

fd = open("foo.txt", O_CREAT|O_RDWR, S_IRUSR)

and let's say the file "foo.txt" didn't exist before, so the above statment will create a file called "foo.txt", and current process who executes this open statment can read and write this file. But after this process terminates, If another process starts and tries to open this file. Below is my question:

Q1-Since the file was created with S_IRUSR(owner can read this file) in the first open call, does it mean that even I as owner of the file, if I start a new process to open this file again, I can only read this file and I cannot write this file, is my understanding correct? If my understanding is correct, is it sensible/practicable that owners create sth that they cannot have full access to it later?

Q2-If my above understanding is correct, then in the second call to open by a new process. I can only call like:

fd = open("foo.txt", O_RDONLY)  // uses flags like O_WRONLY or O_RDWR will throw an error?

since the first open specified the mode as S_IRUSR, which maps to O_RDONLY in the subsequent calls, is my understanding correct?

Upvotes: 0

Views: 30

Answers (1)

Nate Eldredge
Nate Eldredge

Reputation: 58558

Correct, if you create the file with permissions S_IRUSR (often written in octal as 0400), then you will not be able to open the file for writing. Attempting to do so will fail and set errno to EACCES.

This is quite practical as it gives you a way to protect files you do not want to accidentally overwrite, as long as the permissions stay as they are. However, as the owner, you have the power to change the permissions later, using the chmod() system call. So it's not as though you have permanently lost the ability to write that file; you can give yourself back that ability whenever you want.

Upvotes: 0

Related Questions