1. Perl
  2. builtin functions
  3. here

umask function - limit permissions with bitmask

Use the umask function to specify the bitmask.

# Specified in octal
umask 0022;

To specify the bitmask, use the umask function. Permissions is specified in 3-digit octal. In Perl, you can represent an octal number by prefixing it with 0.

The permissions when creating the file are affected by the bitmask. A bitmask is a bit string that limits permissions when creating a file or directory. The following is an example to specify the bitmask.

What is a bit mask?

Bitmasks affect the permissions when creating files and directories with sysopen function and mkdir functions.

For example, if the permission specified in the sysopen function is 666 and the bitmask setting is 022, the permission of the created file will be 644.

When creating a file programmatically, it is better to set the permission value to 666 for files and 777 for executables and directories. By doing this, the user of the program can freely change the permissions created by specifying the bitmask.

(However, in the case of a file that should never be written to another person, create it with permissions such as 644.)

Bitmask operation

The bitmask calculation is as follows.

Permission created = Specified permission & negation of bitmask

It is difficult to understand, so I will explain it with an example. Suppose the permissions you specify are 666 in octal and the bitmask is 022.

Since bit operations are performed, consider converting it to a binary number. The octal number 666 is binary 110110110 and the octal number 022 is binary 000001010.

Negation is the inversion of a bit. & Is the logical product of the bits, which is 1 when both are 1 and 0 otherwise.

1 | 1 | 0 | 1 | 1 | 0 |

0 | 1 | 0 | 0 | 1 | 0 |

1 | 0 | 1 | 1 | 0 | 1 |

1 | 0 | 0 | 1 | 0 | 0 |

File permissions 1 1 0
(Bit mask) 0 0 0
Bitmask denial 1 1 1
Permission created 1 1 0

The logical product of "file permission" and "negation of bitmask" is "permission to be created".

Example

This is an example to set the bit mask.

use strict;
use warnings;

# Import constants for specifying file mode
use Fcntl;

# Bitmask setting Specify in octal
umask 0022;

# Be careful as it will be overwritten
my $file = "file_20080824_ $$";

# The permission value is 644, affected by the bitmask.
sysopen(my $fh, $file, O_CREAT | O_WRONLY, 0666)
  or die "Cannot open $file:$!";
    
close $fh
  or die "Cannnot close $file";

# The permission value is affected by the bitmask and becomes 755.
# Be careful as it will be overwritten
my $dir = "dir_20080824_ $$";
mkdir($dir, 0777)
  or die "Cannot make $dir";

Related Informatrion