umask
umask(?int $mask = null): int
读取或设置进程的权限掩码:新文件默认权限 = 0666 & ~umask,传 mask 即设置并返回旧值,不传仅查询(与 chmod 修改既有文件互补)。
C C23
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main(void) {
/* umask(2):设置掩码并返回旧值以便恢复 */
mode_t orig = umask(0002);
/* 教学规则:新文件默认权限 = 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); /* 恢复原掩码 */
return 0;
}
0666 & ~0002 = 664 0666 & ~0022 = 644 created under umask 0002 -> 664 created under umask 0022 -> 644
C++ C++26
#include <fcntl.h>
#include <cstdio>
#include <sys/stat.h>
#include <unistd.h>
int main() {
// umask(2) 在 C++ 中原样可用(sys/stat.h)
mode_t orig = umask(0002);
// 教学规则:新文件默认权限 = 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); // 恢复原掩码
return 0;
}
0666 & ~0002 = 664 0666 & ~0022 = 644 created under umask 0002 -> 664 created under umask 0022 -> 644
C# v11.0.100
// .NET 没有 umask API;.NET 7+ 提供显式 Unix 文件模式(chmod 风格)
int all666 = Convert.ToInt32("666", 8); // C# 没有八进制字面量
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"); // 经进程 umask 创建,随后显式调权
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);
0666 & ~0002 = 664 0666 & ~0022 = 644 explicit SetUnixFileMode -> 664
Go v1.27.4
package main
import (
"fmt"
"os"
"syscall"
)
func main() {
// syscall.Umask 设置掩码并返回旧值
orig := syscall.Umask(0002)
// 教学规则:新文件默认权限 = 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) // 恢复原掩码
}
0666 & ~0002 = 664 0666 & ~0022 = 644 created under umask 0002 -> 664 created under umask 0022 -> 644
Java 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 {
// JVM 不暴露 umask API——教学本身推导规则
System.out.println("0666 & ~0002 = " + String.format("%03o", 0666 & ~0002));
System.out.println("0666 & ~0022 = " + String.format("%03o", 0666 & ~0022));
// 创建文件的权限只能事后读回,无法预设
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);
}
}
0666 & ~0002 = 664 0666 & ~0022 = 644 readback in [0600, 0666]: true
JavaScript v26.13.1
import { openSync, closeSync, statSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
// Node 不暴露 umask API(process.umask 已弃用)——教学推导规则本身
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));
// 文件创建仍以 0666 经进程 umask 过滤
const path = join(tmpdir(), "a43_node_demo");
const fd = openSync(path, "w"); // 默认 mode 0o666
closeSync(fd);
console.log("readback mode is in [0600, 0666]:",
(statSync(path).mode & 0o777) >= 0o600 && (statSync(path).mode & 0o777) <= 0o666);
unlinkSync(path);
0666 & ~0002 = 664 0666 & ~0022 = 644 readback mode is in [0600, 0666]: true
PHP v8.6.0
// umask:默认权限掩码——新文件默认权限 = 0666 & ~umask
$orig = umask(0002); // 设置并返回旧值以便恢复
printf("0666 & ~0002 = %03o\n", 0666 & ~0002);
printf("0666 & ~0022 = %03o\n", 0666 & ~0022);
$f = tempnam(sys_get_temp_dir(), 'u');
unlink($f); // tempnam 已按旧掩码创建;删除后按新掩码重建
file_put_contents($f, 'x'); // 以 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); // 恢复原掩码
0666 & ~0002 = 664 0666 & ~0022 = 644 created under umask 0002 -> 664 created under umask 0022 -> 644
Python v3.15.2
import os
import stat
# os.umask 设置掩码并返回旧值以便恢复
orig = os.umask(0o002)
# 教学规则:新文件默认权限 = 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() 以 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) # 恢复原掩码
0666 & ~0002 = 664 0666 & ~0022 = 644 created under umask 0002 -> 664 created under umask 0022 -> 644
Rust v1.99.1
use std::fs::OpenOptions;
use std::io::Write;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
fn main() {
// libc::umask 设置掩码并返回旧值以便恢复
let orig = unsafe { libc::umask(0o002) };
// 教学规则:新文件默认权限 = 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) // 被掩码过滤的 mode
.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) }; // 恢复原掩码
}
0666 & ~0002 = 664 0666 & ~0022 = 644 created under umask 0002 -> 664 created under umask 0022 -> 644
TypeScript v26.13.1
import { openSync, closeSync, statSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
// Node 不暴露 umask API(process.umask 已弃用)——教学推导规则本身
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));
// 文件创建仍以 0666 经进程 umask 过滤
const path = join(tmpdir(), "a43_node_demo");
const fd = openSync(path, "w"); // 默认 mode 0o666
closeSync(fd);
console.log("readback mode is in [0600, 0666]:",
(statSync(path).mode & 0o777) >= 0o600 && (statSync(path).mode & 0o777) <= 0o666);
unlinkSync(path);
0666 & ~0002 = 664 0666 & ~0022 = 644 readback mode is in [0600, 0666]: true
语言差异说明
C:umask(2) 设置进程掩码并返回旧值——open(path, ..., 0666) 的 mode 经掩码过滤,规则恒为 0666 & ~umask;改既有文件用 chmod(2)。
C++:同 C 的 umask(2)(sys/stat.h)——无 std 封装。
C#:无 umask API;.NET 7+ 提供 File.SetUnixFileMode/GetUnixFileMode(chmod 语义,Unix-only)——显式调权替代掩码控制;C# 连八进制字面量都没有(Convert.ToInt32("666", 8))。
Go:syscall.Umask(Unix-only)设置并返回旧值;os.OpenFile 的 perm 参数即被掩码过滤的 0666。
Java:JVM 不暴露 umask——新文件默认权限只能事后用 Files.getPosixFilePermissions 读回(位开关枚举,不能用掩码预设)。
JavaScript:Node 不暴露 umask(process.umask() 已弃用 DEP0087)——openSync 的默认 mode 0o666 照样被掩码过滤,只能事后 statSync().mode 读回。
PHP:umask() 不传参查询、传参设置并返回旧值;与 chmod 分工——umask 管「新文件默认权限」(0666 & ~umask),chmod 管既有文件;多线程服务器(如 fork 前的 SAPI)慎改进程级掩码;脚本结束不会自动还原,用完务必恢复。
Python:os.umask(mask) 设置并返回旧值(原生);open() 的创建 mode 0666 被过滤;stat.S_IMODE 读回权限位。
Rust:std 无 umask——libc::umask(unsafe)设置并返回旧值;OpenOptions::mode(0o666)(OpenOptionsExt)即被掩码过滤的 mode。
TypeScript:同 JavaScript——无 umask API,规则只能教学推导,创建后读回验证。