2.7. Restricting Access Permissions for New Files on Unix
Problem
You want to restrict the initial access permissions assigned to a file created by your program.
Solution
On Unix, the operating system stores a value known as the umask for each process it uses when creating new files on behalf of the process. The umask is used to disable permission bits that may be specified by the system call used to create files.
Discussion
Warning
Remember that umasks apply only on file or directory
creation. Calls to chmod(
) and
fchmod( ) are not modified by umask
settings.
When a process creates a new file, it specifies the access
permissions to assign the new file as a parameter to the system call
that creates the file. The operating system modifies the access
permissions by computing the intersection of the inverse of the umask
and the permissions requested by the process. The access permission
bits that remain after the intersection is computed are what the
operating system actually uses for the new file. In other words, in
the following example code, if the variable
requested_permissions contained the permissions
passed to the operating system to create a new file, the variable
actual_permissions would be the actual permissions
that the operating system would use to create the file.
requested_permissions = 0666; actual_permissions = requested_permissions & ~umask( );
A process inherits the value of its umask from its parent process when the process is created. Normally, the shell sets a default ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access