This commit is contained in:
ge
2026-01-08 04:30:38 +03:00
commit 7f6e1cd414
6 changed files with 130 additions and 0 deletions

61
pidfile.v Normal file
View File

@@ -0,0 +1,61 @@
module pidfile
import os
import strconv
fn runtime_dir() string {
if dir := os.getenv_opt('XDG_RUNTIME_DIR') {
return dir
}
euid := os.geteuid()
if euid > 0 {
return '/run/user/${euid}'
}
return '/run'
}
@[params]
pub struct CreateFileConfig {
pub:
// Path prefix for pid-file, e.g. `/run/1000`. Defaults to XDG_RUNTIME_DIR if set or
// to `/run/user/${EUID}` for normal users and `/run` for root user.
prefix string
// Path that will be created inside the prefix. Has no default value.
// For example `myapp` subpath with `/run/1000` prefix becomes to `/run/1000/myapp` path.
subpath string
// If true omit the file extension. Otherwise append the `.pid` extension to filename.
no_extension bool
}
// create creates the new pid-file and returns path to it.
pub fn create(name string, pid int, config CreateFileConfig) !string {
mut filename := name
if !name.ends_with('.pid') && !config.no_extension {
filename += '.pid'
}
mut path := runtime_dir()
if config.prefix != '' {
path = config.prefix
}
path = os.join_path_single(path, config.subpath)
os.mkdir_all(path)!
path = os.join_path_single(path, filename)
os.write_file(path, pid.str())!
return path
}
// write writes the pid into file specified in path.
//
// If directories in `path` do not exist, they will be created.
pub fn write(path string, pid int) ! {
os.mkdir_all(os.dir(path))!
os.write_file(path, pid.str())!
}
// read reads the pid-file and returns its content as integer.
pub fn read(path string) !int {
s := os.read_file(path)!
return strconv.atoi(s.trim_space())!
}