Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to neglect the umask so as to create the file with given permission

Tags:

c++

unix

solaris

I am creating a file using open function and using O_CREAT | O_EXCEL . I have passed the mode as "0666" . But by masking finally the permission allotted to it is -rw-r--r-- and not the -rw-rw-rw- . Someone told me i can use umask (011) and then reset the original mask again . But i dont know how to pass this in c++ program. This is the small snippet of What i am doing .

   # include <iostream>
   # include <stdio.h>
   # include <conio.h>
   #include <sys/types.h>
   #include <sys/stat.h>
   #include <fcntl.h>

   using namespace std;

   int main()
   {
    int fd = open("C:\\Users\\Ritesh\\Music\\music.txt", O_CREAT | O_EXCL, 0666);   
    getch();
    return 0;   
  } 

creates file C:\Users\Ritesh\Music\music.txt with permission -rw-r--r-- . I want it to be -rw-rw-rw-

like image 373
Invictus Avatar asked Sep 18 '25 23:09

Invictus


2 Answers

mode_t old_mask;

old_mask = umask(011);
open( ... );
umask(old_mask);
like image 132
William Pursell Avatar answered Sep 20 '25 15:09

William Pursell


The only thread-safe way to set file permissions to be what you want is to set them explicitly with chmod() or fchmod() after creating the file (example without error checking):

int fd = open("C:\\Users\\Ritesh\\Music\\music.txt", O_CREAT | O_EXCL, 0666);
fchmod(fd, 0666 );

If you use umask(), you will change the umask value for the entire process. If any other threads are running you risk files getting created with unexpected permissions, which could lead to a security issue or other problems. And any child process created while your changed umask value is in effect will be created with an unexpected umask value.

like image 40
Andrew Henle Avatar answered Sep 20 '25 15:09

Andrew Henle