umask

umask(?int $mask = null): int

Reads or sets the process permission mask: a new file's default mode is 0666 & ~umask; passing a mask sets it and returns the old one, omitting it only queries (complementary to chmod on existing files).

C C23

C23
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

int main(void) {
    /* umask(2): set the mask; the previous one comes back for restoring */
    mode_t orig = umask(0002);
    /* The teaching rule: a new file gets 0666 & ~umask */
    printf("0666 & ~0002 = %03o\n", 0666 & ~0002);
    printf("0666 & ~0022 = %03o\n", 0666 & ~0022);
    char path[64];
    snprintf(path, sizeof(path), "/tmp/a43_umask_demo_%d", (int)getpid());
    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    struct stat st;
    fstat(fd, &st);
    printf("created under umask 0002 -> %o\n", st.st_mode & 0777);
    close(fd);
    unlink(path);
    umask(0022);
    fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    fstat(fd, &st);
    printf("created under umask 0022 -> %o\n", st.st_mode & 0777);
    close(fd);
    unlink(path);
    umask(orig); /* restore the original mask */
    return 0;
}
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
created under umask 0002 -> 664
created under umask 0022 -> 644

C++ C++26

C++26
#include <fcntl.h>
#include <cstdio>
#include <sys/stat.h>
#include <unistd.h>

int main() {
    // umask(2) works unchanged in C++ (sys/stat.h)
    mode_t orig = umask(0002);
    // The teaching rule: a new file gets 0666 & ~umask
    std::printf("0666 & ~0002 = %03o\n", 0666 & ~0002);
    std::printf("0666 & ~0022 = %03o\n", 0666 & ~0022);
    char path[64];
    std::snprintf(path, sizeof(path), "/tmp/a43_umask_demo_cpp");
    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    struct stat st;
    fstat(fd, &st);
    std::printf("created under umask 0002 -> %o\n", st.st_mode & 0777);
    close(fd);
    unlink(path);
    umask(0022);
    fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0666);
    fstat(fd, &st);
    std::printf("created under umask 0022 -> %o\n", st.st_mode & 0777);
    close(fd);
    unlink(path);
    umask(orig); // restore the original mask
    return 0;
}
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
created under umask 0002 -> 664
created under umask 0022 -> 644

C# v11.0.100

v11.0.100
// .NET has no umask API; .NET 7+ offers explicit Unix file modes (chmod-style)
int all666 = Convert.ToInt32("666", 8); // C# has no octal literal
Console.WriteLine("0666 & ~0002 = " + Convert.ToString(all666 & ~Convert.ToInt32("2", 8), 8).PadLeft(3, '0'));
Console.WriteLine("0666 & ~0022 = " + Convert.ToString(all666 & ~Convert.ToInt32("22", 8), 8).PadLeft(3, '0'));
var path = Path.Combine(Path.GetTempPath(), "a43_mode_demo");
File.WriteAllText(path, "x"); // created via the process umask, then tuned explicitly
File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite
    | UnixFileMode.GroupRead | UnixFileMode.GroupWrite | UnixFileMode.OtherRead);
Console.WriteLine("explicit SetUnixFileMode -> " + Convert.ToString((int)File.GetUnixFileMode(path), 8).PadLeft(3, '0'));
File.Delete(path);
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
explicit SetUnixFileMode -> 664

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os"
	"syscall"
)

func main() {
	// syscall.Umask sets the mask and returns the previous one
	orig := syscall.Umask(0002)
	// The teaching rule: a new file gets 0666 & ~umask
	fmt.Printf("0666 & ~0002 = %03o\n", 0o666&^0o0002)
	fmt.Printf("0666 & ~0022 = %03o\n", 0o666&^0o0022)
	path := "/tmp/a43_umask_demo_go"
	f, _ := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	f.Close()
	st, _ := os.Stat(path)
	fmt.Printf("created under umask 0002 -> %o\n", st.Mode().Perm())
	os.Remove(path)
	syscall.Umask(0022)
	f, _ = os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	f.Close()
	st, _ = os.Stat(path)
	fmt.Printf("created under umask 0022 -> %o\n", st.Mode().Perm())
	os.Remove(path)
	syscall.Umask(orig) // restore the original mask
}
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
created under umask 0002 -> 664
created under umask 0022 -> 644

Java v27.0.1

v27.0.1
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermission;
import java.util.Set;

public class Main {
    public static void main(String[] args) throws Exception {
        // The JVM exposes no umask API - teach the derivation rule itself
        System.out.println("0666 & ~0002 = " + String.format("%03o", 0666 & ~0002));
        System.out.println("0666 & ~0022 = " + String.format("%03o", 0666 & ~0022));
        // A created file's permissions can only be read back, not pre-set
        Path path = Path.of(System.getProperty("java.io.tmpdir"), "a43_java_demo");
        Files.createFile(path);
        Set<PosixFilePermission> perms = Files.getPosixFilePermissions(path);
        int mode = 0;
        for (PosixFilePermission p : perms) {
            mode |= switch (p) {
                case OWNER_READ -> 0400; case OWNER_WRITE -> 0200; case OWNER_EXECUTE -> 0100;
                case GROUP_READ -> 0040; case GROUP_WRITE -> 0020; case GROUP_EXECUTE -> 0010;
                case OTHERS_READ -> 0004; case OTHERS_WRITE -> 0002; case OTHERS_EXECUTE -> 0001;
            };
        }
        System.out.println("readback in [0600, 0666]: " + (mode >= 0600 && mode <= 0666));
        Files.delete(path);
    }
}
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
readback in [0600, 0666]: true

JavaScript v26.13.1

v26.13.1
import { openSync, closeSync, statSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

// Node exposes no umask API (process.umask is deprecated) - teach the rule
const rule = (mode, mask) => (mode & ~mask).toString(8).padStart(3, "0");
console.log("0666 & ~0002 =", rule(0o666, 0o002));
console.log("0666 & ~0022 =", rule(0o666, 0o022));
// Files are still created with 0666 filtered by the process umask
const path = join(tmpdir(), "a43_node_demo");
const fd = openSync(path, "w"); // default mode 0o666
closeSync(fd);
console.log("readback mode is in [0600, 0666]:",
  (statSync(path).mode & 0o777) >= 0o600 && (statSync(path).mode & 0o777) <= 0o666);
unlinkSync(path);
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
readback mode is in [0600, 0666]: true

PHP v8.6.0

v8.6.0
// umask: default permission mask - a new file gets 0666 & ~umask
$orig = umask(0002); // set; the previous mask comes back for restoring
printf("0666 & ~0002 = %03o\n", 0666 & ~0002);
printf("0666 & ~0022 = %03o\n", 0666 & ~0022);
$f = tempnam(sys_get_temp_dir(), 'u');
unlink($f); // tempnam already applied the old mask; recreate under the new one
file_put_contents($f, 'x'); // created via mode 0666
printf("created under umask 0002 -> %o\n", fileperms($f) & 0777);
unlink($f);
umask(0022);
file_put_contents($f, 'x');
printf("created under umask 0022 -> %o\n", fileperms($f) & 0777);
unlink($f);
umask($orig); // restore the original mask
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
created under umask 0002 -> 664
created under umask 0022 -> 644

Python v3.15.2

v3.15.2
import os
import stat

# os.umask sets the mask and returns the previous one for restoring
orig = os.umask(0o002)
# The teaching rule: a new file gets 0666 & ~umask
print("0666 & ~0002 =", f"{0o666 & ~0o002:03o}")
print("0666 & ~0022 =", f"{0o666 & ~0o022:03o}")
path = "/tmp/a43_umask_demo_py"
with open(path, "w") as f:  # open() creates with mode 0666
    pass
print("created under umask 0002 ->", f"{stat.S_IMODE(os.stat(path).st_mode):03o}")
os.unlink(path)
os.umask(0o022)
with open(path, "w") as f:
    pass
print("created under umask 0022 ->", f"{stat.S_IMODE(os.stat(path).st_mode):03o}")
os.unlink(path)
os.umask(orig)  # restore the original mask
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
created under umask 0002 -> 664
created under umask 0022 -> 644

Rust v1.99.1

v1.99.1
use std::fs::OpenOptions;
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};

fn main() {
    // libc::umask sets the mask; the previous one comes back for restoring
    let orig = unsafe { libc::umask(0o002) };
    // The teaching rule: a new file gets 0666 & ~umask
    println!("0666 & ~0002 = {:03o}", 0o666 & !0o002);
    println!("0666 & ~0022 = {:03o}", 0o666 & !0o0022);
    let path = "/tmp/a43_umask_demo_rs";
    let mut f = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o666) // the mode the mask filters
        .open(path)
        .unwrap();
    writeln!(f, "x").unwrap();
    drop(f);
    let mode = std::fs::metadata(path).unwrap().permissions().mode();
    println!("created under umask 0002 -> {:03o}", mode & 0o777);
    std::fs::remove_file(path).unwrap();
    unsafe { libc::umask(0o022) };
    let mut f = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .mode(0o666)
        .open(path)
        .unwrap();
    writeln!(f, "x").unwrap();
    drop(f);
    let mode = std::fs::metadata(path).unwrap().permissions().mode();
    println!("created under umask 0022 -> {:03o}", mode & 0o777);
    std::fs::remove_file(path).unwrap();
    unsafe { libc::umask(orig) }; // restore the original mask
}
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
created under umask 0002 -> 664
created under umask 0022 -> 644

TypeScript v26.13.1

v26.13.1
import { openSync, closeSync, statSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

// Node exposes no umask API (process.umask is deprecated) - teach the rule
const rule = (mode: number, mask: number): string => (mode & ~mask).toString(8).padStart(3, "0");
console.log("0666 & ~0002 =", rule(0o666, 0o002));
console.log("0666 & ~0022 =", rule(0o666, 0o022));
// Files are still created with 0666 filtered by the process umask
const path = join(tmpdir(), "a43_node_demo");
const fd = openSync(path, "w"); // default mode 0o666
closeSync(fd);
console.log("readback mode is in [0600, 0666]:",
  (statSync(path).mode & 0o777) >= 0o600 && (statSync(path).mode & 0o777) <= 0o666);
unlinkSync(path);
Output
0666 & ~0002 = 664
0666 & ~0022 = 644
readback mode is in [0600, 0666]: true

Language differences

C: umask(2) sets the process mask and returns the old one - the open(path, ..., 0666) mode gets filtered by the mask; the rule is always 0666 & ~umask; chmod(2) changes existing files.

C++: same umask(2) as C (sys/stat.h) - no std wrapper.

C#: no umask API; .NET 7+ offers File.SetUnixFileMode/GetUnixFileMode (chmod semantics, Unix-only) - explicit tuning replaces mask control; C# lacks even octal literals (Convert.ToInt32("666", 8)).

Go: syscall.Umask (Unix-only) sets and returns the old mask; os.OpenFile's perm argument is the 0666 that gets filtered.

Java: the JVM exposes no umask - a new file's default permissions can only be read back afterwards with Files.getPosixFilePermissions (bit-flag enum, no mask pre-setting).

JavaScript: Node exposes no umask (process.umask() is deprecated, DEP0087) - openSync's default mode 0o666 is filtered by the mask all the same; only a post-creation statSync().mode readback works.

PHP: umask() queries without an argument, sets and returns the old mask with one; division of labor with chmod - umask governs new-file defaults (0666 & ~umask), chmod governs existing files; be careful changing the process-wide mask under threaded server APIs; it is not restored automatically at script end, so always restore it.

Python: os.umask(mask) sets and returns the old value (native); open()'s creation mode 0666 gets filtered; stat.S_IMODE reads the permission bits back.

Rust: no umask in std - libc::umask (unsafe) sets and returns the old mask; OpenOptions::mode(0o666) (OpenOptionsExt) is the mode that gets filtered.

TypeScript: same as JavaScript - no umask API, the rule can only be taught by derivation, verified with a post-creation readback.