If umask seems confusing, here's some advice:
supply a creation mode of 0666 for regular files and one of 0777 for
directories and executable files. This gives users a choice: if they
want protected files, they can choose process umasks of 022, 027, or
even the particularly antisocial mask of 077. Programs should rarely
if ever make policy decisions better left to the user. One exception,
though, is files that should be kept private: mail files, web browser
cookies, .rhosts files, and so on. In short,
seldom if ever use 0644 as argument to sysopen
because that takes away the user's option to have a more permissive
umask.
Here are examples of open and
sysopen in action.
To open for reading:
open(FH, "<", $path) or die $!;
sysopen(FH, $path, O_RDONLY) or die $!;
To open for writing, create a new file if needed, or else truncate an
old one:
open(FH, ">", $path) or die $!;
sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT) or die $!;
sysopen(FH, $path, O_WRONLY|O_TRUNC|O_CREAT, 0600) or die $!;
To open for writing, create a new file, but that file must not
previously exist:
sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT) or die $!;
sysopen(FH, $path, O_WRONLY|O_EXCL|O_CREAT, 0600) or die $!;
To open for appending, creating it if necessary:
open(FH, ">>", $path) or die $!;
sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT) or die $!;
sysopen(FH, $path, O_WRONLY|O_APPEND|O_CREAT, 0600) or die $!;
To open for appending, where the file must exist:
sysopen(FH, $path, O_WRONLY|O_APPEND) or die $!;
To open for update, where the file must exist:
open(FH, "+<", $path) or die $!;
sysopen(FH, $path, O_RDWR) or die $!;
To open for update, but create a new file if necessary:
sysopen(FH, $path, O_RDWR|O_CREAT) or die $!;
sysopen(FH, $path, O_RDWR|O_CREAT, 0600) or die $!;
To open for update, where the file must not exist:
sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT) or die $!;
sysopen(FH, $path, O_RDWR|O_EXCL|O_CREAT, 0600) or die $!;
We use a creation mask of 0600 here only to show how to create a
private file. The argument is normally omitted.