sskanitk
sskanitk

Reputation: 475

Parameters of open(): Everyone should have all access to file & should be truncated on creation

I want to create a file in Unix that allows everyone all access. If the file already exists, it should be truncated to be empty.

After reading through the open man page, I have following call. Just wanted to confirm if its the right way to do it.

int fd;
int flags = O_RDWR | O_CREAT | O_TRUNC;
/* Set umask to Octal 011 */
mode_t mode = S_IXGRP | S_IXOTH;
/* umask syscall alwasy succeeds. No need to save return value (previous umask value) */
umask(mode);
/* Set mode to Octal 666. open syscall will and mode with ~umask. 
   0666 & ~0011 = 0666 i.e. the mode we want to set.
*/
mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
if ((fd = open(path.c_str(), flags, mode)) < 0) {
   return false;
} else {
  close(fd);
  return true;
}

Thanks!

Edit: As per Nikolai's comments, all access = Read & Write. I do not want everyone to be able to write to an executable file.

Upvotes: 1

Views: 196

Answers (1)

tchrist
tchrist

Reputation: 80384

The only way you can guarantee the file creation mode is to explicitly zero out your umask before calling open, because the mode argument is NANDed against your umask.

It's probably best to simply set your file mode after you creat it.

Upvotes: 2

Related Questions