#!/usr/bin/env dub
/+ dub.sdl:
name "recovery-owner-probe"
targetPath "../../../build"
dependency "sparkles:base" path="../../.."
dependency "sparkles:recovery" path="../../.."
dependency "sparkles:test-utils" path="../../.."
dflags "-preview=in" "-preview=dip1000"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
/// Kill a task-owned process after its durable checkpoint and reclaim its archive.
module (module) recovery_owner_probeKill a task-owned process after its durable checkpoint and reclaim its archive.
recovery_owner_probe;
import (package) corecore.(package) core.syssys.(package) core.sys.posixposix.(module) core.sys.posix.signalD header file for POSIX.
Source
core/sys/posix/signal.d
signal : (alias constant) recovery_owner_probe.SIGKILL = int core.sys.posix.signal.SIGKILL = 9SIGKILL;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) recovery_owner_probe.readText = std.file.readText(S = string, R)(auto ref R name) if (isSomeString!S && (isSomeFiniteCharInputRange!R || is(StringTypeOf!R)))Reads and validates (using validate) a text file. S can be
an array of any character type. However, no width or endian conversions are
performed. So, if the width or endianness of the characters in the given
file differ from the width or endianness of the element type of S, then
validation will fail.
readText, (alias) recovery_owner_probe.thisExePath = string std.file.thisExePath() @trustedReturns the full path of the current executable.
thisExePath;
import (package) stdstd.(module) std.processFunctions for starting and interacting with other processes, and for
working with the current process' execution environment.
Process handling
`spawnProcess` spawns a new `process`, optionally assigning it an
arbitrary set of standard input, output, and error streams.
The function returns immediately, leaving the child process to execute
in parallel with its parent. All other functions in this module that
spawn processes are built around spawnProcess.
`wait` makes the parent `process` wait for a child `process` to
terminate. In general one should always do this, to avoid
child processes becoming "zombies" when the parent process exits.
Scope guards are perfect for this – see the spawnProcess
documentation for examples. tryWait is similar to wait,
but does not block if the process has not yet terminated.
`pipeProcess` also spawns a child `process` which runs
in parallel with its parent. However, instead of taking
arbitrary streams, it automatically creates a set of
pipes that allow the parent to communicate with the child
through the child's standard input, output, and/or error streams.
This function corresponds roughly to C's popen function.
`execute` starts a new `process` and waits for it
to complete before returning. Additionally, it captures
the process' standard output and error streams and returns
the output of these as a string.
`spawnShell`, `pipeShell` and `executeShell` work like
spawnProcess, pipeProcess and execute, respectively,
except that they take a single command string and run it through
the current user's default command interpreter.
executeShell corresponds roughly to C's system function.
`kill` attempts to terminate a running `process`.
The following table compactly summarises the different process creation
functions and how they relate to each other:
Runs program directly
Runs shell command Low-level process creation spawnProcess spawnShell Automatic input/output redirection using pipes pipeProcess pipeShell Execute and wait for completion, collect output execute executeShell
Other functionality
`pipe` is used to create unidirectional pipes.
`environment` is an interface through which the current `process`'
environment variables can be read and manipulated.
`escapeShellCommand` and `escapeShellFileName` are useful
for constructing shell command lines in a portable way.
Source
std/process.d
Note
Most of the functionality in this module is not available on iOS, tvOS
and watchOS. The only functions available on those platforms are:
environment, thisProcessID and thisThreadID.
process : (alias) recovery_owner_probe.execute = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute, (alias) recovery_owner_probe.kill = void std.process.kill(std.process.Pid pid)Attempts to terminate the process associated with pid.
The effect of this function, as well as the meaning of codeOrSignal,
is highly platform dependent. Details are given below. Common to all
platforms is that this function only initiates termination of the process,
and returns immediately. It does not wait for the process to end,
nor does it guarantee that the process does in fact get terminated.
Always call wait to wait for a process to complete, even if kill
has been called on it.
Windows specific
The process will be
forcefully and abruptly terminated. If codeOrSignal is specified, it
must be a nonnegative number which will be used as the exit code of the process.
If not, the process wil exit with code 1. Do not use codeOrSignal = 259,
as this is a special value (aka. STILL_ACTIVE)
used by Windows to signal that a process has in fact not terminated yet.
auto pid = spawnProcess("some_app");
kill(pid, 10);
assert(wait(pid) == 10);
POSIX specific
A signal will be sent to
the process, whose value is given by codeOrSignal. Depending on the
signal sent, this may or may not terminate the process. Symbolic constants
for various POSIX signals are defined in core.sys.posix.signal, which corresponds to the
signal.h POSIX header. If codeOrSignal is omitted, the
SIGTERM signal will be sent. (This matches the behaviour of the
_kill shell command.)
import core.sys.posix.signal : SIGKILL;
auto pid = spawnProcess("some_app");
kill(pid, SIGKILL);
assert(wait(pid) == -SIGKILL); // Negative return value on POSIX!
kill, (alias) recovery_owner_probe.pipeProcess = std.process.ProcessPipes std.process.pipeProcess(scope const(char[])[] args, std.process.Redirect redirect = Redirect.all, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char)[] workDir = null) @safeStarts a new process, creating pipes to redirect its standard
input, output and/or error streams.
pipeProcess and pipeShell are convenient wrappers around
spawnProcess and spawnShell, respectively, and
automate the task of redirecting one or more of the child process'
standard streams through pipes. Like the functions they wrap,
these functions return immediately, leaving the child process to
execute in parallel with the invoking process. It is recommended
to always call wait on the returned ProcessPipes.pid,
as detailed in the documentation for wait.
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
Example
// my_application writes to stdout and might write to stderr
auto pipes = pipeProcess("my_application", Redirect.stdout | Redirect.stderr);
scope(exit) wait(pipes.pid);
// Store lines of output.
string[] output;
foreach (line; pipes.stdout.byLine) output ~= line.idup;
// Store lines of errors.
string[] errors;
foreach (line; pipes.stderr.byLine) errors ~= line.idup;
// sendmail expects to read from stdin
pipes = pipeProcess(["/usr/bin/sendmail", "-t"], Redirect.stdin);
pipes.stdin.writeln("To: you");
pipes.stdin.writeln("From: me");
pipes.stdin.writeln("Subject: dlang");
pipes.stdin.writeln("");
pipes.stdin.writeln(message);
// a single period tells sendmail we are finished
pipes.stdin.writeln(".");
// but at this point sendmail might not see it, we need to flush
pipes.stdin.flush();
// sendmail happens to exit on ".", but some you have to close the file:
pipes.stdin.close();
// otherwise this wait will wait forever
wait(pipes.pid);
pipeProcess, (enum) std.process.RedirectFlags that can be passed to pipeProcess and pipeShell
to specify which of the child process' standard streams are redirected.
Use bitwise OR to combine flags.
Redirect, (alias) recovery_owner_probe.tryWait = std.typecons.Tuple!(bool, "terminated", int, "status") std.process.tryWait(std.process.Pid pid) @safeA non-blocking version of wait.
If the process associated with pid has already terminated,
tryWait has the exact same effect as wait.
In this case, it returns a tuple where the terminated field
is set to true and the status field has the same
interpretation as the return value of wait.
If the process has not yet terminated, this function differs
from wait in that does not wait for this to happen, but instead
returns immediately. The terminated field of the returned
tuple will then be set to false, while the status field
will always be 0 (zero). wait or tryWait should then be
called again on the same Pid at some later time; not only to
get the exit code, but also to avoid the process becoming a "zombie"
when it finally terminates. (See wait for details).
Example
auto pid = spawnProcess("dmd myapp.d");
scope(exit) wait(pid);
...
auto dmd = tryWait(pid);
if (dmd.terminated)
{
if (dmd.status == 0) writeln("Compilation succeeded!");
else writeln("Compilation failed");
}
else writeln("Still compiling...");
...
Note that in this example, the first wait call will have no
effect if the process has already terminated by the time tryWait
is called. In the opposite case, however, the scope statement
ensures that we always wait for the process if it hasn't terminated
by the time we reach the end of the scope.
tryWait, (alias) recovery_owner_probe.wait = int std.process.wait(std.process.Pid pid) @safeWaits for the process associated with pid to terminate, and returns
its exit status.
In general one should always wait for child processes to terminate
before exiting the parent process unless the process was spawned as detached
(that was spawned with Config.detached flag).
Otherwise, they may become "zombies"
– processes that are defunct, yet still occupy a slot in the OS process table.
You should not and must not wait for detached processes, since you don't own them.
If the process has already terminated, this function returns directly.
The exit code is cached, so that if wait() is called multiple times on
the same Pid it will always return the same value.
POSIX specific
If the process is terminated by a signal, this function returns a
negative number whose absolute value is the signal number.
Since POSIX restricts normal exit codes to the range 0-255, a
negative return value will always indicate termination by signal.
Signal codes are defined in the core.sys.posix.signal module
(which corresponds to the signal.h POSIX header).
Example
See the spawnProcess documentation.
wait;
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) recovery_owner_probe.readln = std.stdio.readln(S = string)(dchar terminator = '\n') if (isSomeString!S)Read line from stdin.
This version manages its own read buffer, which means one memory allocation per call. If you are not
retaining a reference to the read data, consider the ``readln(buf) version, which may offer
better performance as it can reuse its read buffer.
Note
String terminators are not supported due to ambiguity with readln(buf) below.
Example
Reads stdin and writes it to stdout.
import std.stdio;
void main()
{
string line;
while ((line = readln()) !is null)
write(line);
}
readln, stderr, (alias) recovery_owner_probe.stdout = std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdout"() nothrow @nogc @property ref @systemstdout, (alias template) recovery_owner_probe.writeln = std.stdio.writeln(T...)(T args)Equivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln;
import (package) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias template) recovery_owner_probe.strip = std.string.strip(Range)(Range str) if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range))Strips both leading and trailing whitespace (as defined by
isWhite) or as specified in the second argument.
strip;
import (package) sparklessparkles.(package) sparkles.recoveryrecovery.(module) sparkles.recovery.archiveNumbered immutable generation files in a recovery archive.
A generation is one opaque payload under a canonical name: 20 decimal digits
and the layout's suffix (00000000000000000007.session). An append never
replaces a file: it is a create-only atomic write through the capability VFS
that syncs the directory (VFO9), so an earlier generation stays readable
until a newer one is durably acknowledged. Reads accept only a regular file,
never through a link (VFO12). Pruning keeps the newest valid generations at
or below an acknowledged cutoff and leaves damaged, unsupported, linked and
newer entries alone. A retirement marker records that a generation was
adopted elsewhere without touching its bytes.
archive : (alias) recovery_owner_probe.appendGeneration = sparkles.base.expected.Expected!(WriteReceipt, string, Abort) sparkles.recovery.archive.appendGeneration(string directory, ulong generation, scope const(char)[] bytes, in sparkles.recovery.archive.ArchiveLayout layout = ArchiveLayout(".generation", "retired-", "SPARKLES-RECOVERY-RETIRED/1", 536870912LU)) nothrow @safeAppend bytes as generation, never replacing a file. The caller supplies an
existing private directory whose creation is already durable, and retains
earlier durable generations until this one is acknowledged durable.
appendGeneration, (alias) recovery_owner_probe.readGeneration = sparkles.base.expected.Expected!(string, string, Abort) sparkles.recovery.archive.readGeneration(string directory, ulong generation, in sparkles.recovery.archive.ArchiveLayout layout = ArchiveLayout(".generation", "retired-", "SPARKLES-RECOVERY-RETIRED/1", 536870912LU)) nothrow @safeThe payload of generation, read only from a regular file.
readGeneration;
import (package) sparklessparkles.(package) sparkles.recoveryrecovery.(module) sparkles.recovery.directoryPrivate, durable archive directories with process-shared ownership leases.
A LeasedDirectory is one archive: a private directory created under a base
directory with a random name, synced up to a durable namespace root, and held
with an exclusive flock for as long as its owner lives. Another process
claims it only after the owner closes it or dies, so a crashed session's
archive is recovered without two instances writing to it. Linux only, for
now: elsewhere every call reports unavailable.
directory : (enum) sparkles.recovery.directory.DirectoryIssueKindWhy a lease was not granted.
DirectoryIssueKind, (class) sparkles.recovery.directory.LeasedDirectoryOne archive's directory lock. Keep this owner alive until its storage work has
stopped, then close it explicitly. Other processes can claim an archive only
after its owner closes or terminates. Creation and claim serialize against
the base directory lock so a half-initialized archive cannot be claimed.
LeasedDirectory;
import (package) sparklessparkles.(package) sparkles.test_utilstest_utils.(module) sparkles.test_utils.tmpfstmpfs : (struct) sparkles.test_utils.tmpfs.TmpFSA scratch directory for a test, removed when the instance goes out of scope.
There are two ways to get one, and the difference is who owns the directory:
create makes a fresh, uniquely named directory and owns it:
the whole tree — files written through this instance or behind its back,
subdirectories, everything — is removed with the instance. This is what a
test wants almost every time.
share attaches to a directory that already exists and does
not own it: only the files this instance wrote are removed, and the
directory outlives it. This is for a test that deliberately has two
fixtures over one tree, or one that must not delete what another made.
Ownership is decided by which constructor ran, never by what a later call
happened to find on disk — so it cannot be forgotten, and a test that writes
into dir() through the code under test rather than through this fixture
still gets its tree cleaned up.
One instance is not thread-safe: writeFileAt appends to its file list and
the destructor reads it. That is the intended shape — one fixture per test,
used from the test's own thread — and create itself is safe to call
concurrently. Sharing a single instance across threads needs the caller's own
synchronization.
On POSIX, fixture writers are close-on-exec from the instant they open.
An unrelated child executing concurrently cannot retain a writer after its
exec and keep an executable fixture ETXTBSY after the parent's write has
completed. This applies to both writeFile and writeFileAt.
Removal is best effort and never throws. A destructor that throws during
unwinding replaces the assertion that actually failed with a cleanup error,
and on Windows that is not hypothetical — git leaves read-only objects behind
that make recursive removal fail.
TmpFS;
int int D main(string[] args) @systemmain((alias) object.string = stringstring[] (parameter) string[] argsargs) @system
{
if ((parameter) string[] argsargs.(field) ulong string[].lengthlength == 1)
{
auto (local variable) sparkles.test_utils.tmpfs.TmpFS fixturefixture = (struct) sparkles.test_utils.tmpfs.TmpFSA scratch directory for a test, removed when the instance goes out of scope.
There are two ways to get one, and the difference is who owns the directory:
create makes a fresh, uniquely named directory and owns it:
the whole tree — files written through this instance or behind its back,
subdirectories, everything — is removed with the instance. This is what a
test wants almost every time.
share attaches to a directory that already exists and does
not own it: only the files this instance wrote are removed, and the
directory outlives it. This is for a test that deliberately has two
fixtures over one tree, or one that must not delete what another made.
Ownership is decided by which constructor ran, never by what a later call
happened to find on disk — so it cannot be forgotten, and a test that writes
into dir() through the code under test rather than through this fixture
still gets its tree cleaned up.
One instance is not thread-safe: writeFileAt appends to its file list and
the destructor reads it. That is the intended shape — one fixture per test,
used from the test's own thread — and create itself is safe to call
concurrently. Sharing a single instance across threads needs the caller's own
synchronization.
On POSIX, fixture writers are close-on-exec from the instant they open.
An unrelated child executing concurrently cannot retain a writer after its
exec and keep an executable fixture ETXTBSY after the parent's write has
completed. This applies to both writeFile and writeFileAt.
Removal is best effort and never throws. A destructor that throws during
unwinding replaces the assertion that actually failed with a cleanup error,
and on Windows that is not hypothetical — git leaves read-only objects behind
that make recursive removal fail.
TmpFS.sparkles.test_utils.tmpfs.TmpFS sparkles.test_utils.tmpfs.TmpFS.create(string prefix = __FUNCTION__, string basePath = tempDir()) @safeCreates a fresh scratch directory and returns the fixture that owns it.
prefix names the fixture for a human reading /tmp; it does not have to
be unique. The directory actually used appends a random token and a
process-wide ordinal, which makes three problems impossible rather than
merely unlikely:
Two concurrent runs of one suite — two worktrees, two agents, a CI
matrix sharing a runner — cannot share a directory and delete each
other's fixtures mid-test.
A crashed run cannot leave a directory behind for the next run to
inherit and read a previous run's files from. The token is random
rather than the process id for exactly this case: pids are recycled,
so ``prefix-<pid>-1 recurs and would collide with the leftovers of a
run that died holding the same pid.
Two fixtures in one test function cannot collide, so neither needs
an artificial prefix to tell them apart.
The directory exists when this returns, so a test may hand dir() to the
code under test immediately; whatever that code puts there is removed
with the fixture.
prefix defaults to the calling function. That is a good name when the
call sits in the test; from a shared helper it names the helper, which is
merely less informative — no longer a correctness problem.
create();
const (local variable) const(string) sourcesource = (local variable) sparkles.test_utils.tmpfs.TmpFS fixturefixture.string sparkles.test_utils.tmpfs.TmpFS.writeFile(string contents, uint suffix = 0u) @safewriteFile("disk bytes");
auto (local variable) std.process.ProcessPipes ownerowner = std.process.ProcessPipes std.process.pipeProcess(scope const(char[])[] args, std.process.Redirect redirect = Redirect.all, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char)[] workDir = null) @safeStarts a new process, creating pipes to redirect its standard
input, output and/or error streams.
pipeProcess and pipeShell are convenient wrappers around
spawnProcess and spawnShell, respectively, and
automate the task of redirecting one or more of the child process'
standard streams through pipes. Like the functions they wrap,
these functions return immediately, leaving the child process to
execute in parallel with the invoking process. It is recommended
to always call wait on the returned ProcessPipes.pid,
as detailed in the documentation for wait.
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
Example
// my_application writes to stdout and might write to stderr
auto pipes = pipeProcess("my_application", Redirect.stdout | Redirect.stderr);
scope(exit) wait(pipes.pid);
// Store lines of output.
string[] output;
foreach (line; pipes.stdout.byLine) output ~= line.idup;
// Store lines of errors.
string[] errors;
foreach (line; pipes.stderr.byLine) errors ~= line.idup;
// sendmail expects to read from stdin
pipes = pipeProcess(["/usr/bin/sendmail", "-t"], Redirect.stdin);
pipes.stdin.writeln("To: you");
pipes.stdin.writeln("From: me");
pipes.stdin.writeln("Subject: dlang");
pipes.stdin.writeln("");
pipes.stdin.writeln(message);
// a single period tells sendmail we are finished
pipes.stdin.writeln(".");
// but at this point sendmail might not see it, we need to flush
pipes.stdin.flush();
// sendmail happens to exit on ".", but some you have to close the file:
pipes.stdin.close();
// otherwise this wait will wait forever
wait(pipes.pid);
pipeProcess([string std.file.thisExePath() @trustedReturns the full path of the current executable.
Examples
import std.path : isAbsolute;
auto path = thisExePath();
assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);
thisExePath, "owner", (local variable) sparkles.test_utils.tmpfs.TmpFS fixturefixture.string sparkles.test_utils.tmpfs.TmpFS.dir() const pure nothrow @nogc @safeThe scratch directory's path. It exists for as long as the instance
does (and, for share, for as long as its real owner keeps it).
dir],
(enum) std.process.RedirectFlags that can be passed to pipeProcess and pipeShell
to specify which of the child process' standard streams are redirected.
Use bitwise OR to combine flags.
Redirect.(enum value) std.process.Redirect.stdin = 1Redirect the standard input, output or error streams, respectively.
stdin | (enum) std.process.RedirectFlags that can be passed to pipeProcess and pipeShell
to specify which of the child process' standard streams are redirected.
Use bitwise OR to combine flags.
Redirect.(enum value) std.process.Redirect.stdout = 2Redirect the standard input, output or error streams, respectively.
stdout);
scope (exit)
{
if (!std.typecons.Tuple!(bool, "terminated", int, "status") std.process.tryWait(std.process.Pid pid) @safeA non-blocking version of wait.
If the process associated with pid has already terminated,
tryWait has the exact same effect as wait.
In this case, it returns a tuple where the terminated field
is set to true and the status field has the same
interpretation as the return value of wait.
If the process has not yet terminated, this function differs
from wait in that does not wait for this to happen, but instead
returns immediately. The terminated field of the returned
tuple will then be set to false, while the status field
will always be 0 (zero). wait or tryWait should then be
called again on the same Pid at some later time; not only to
get the exit code, but also to avoid the process becoming a "zombie"
when it finally terminates. (See wait for details).
Example
auto pid = spawnProcess("dmd myapp.d");
scope(exit) wait(pid);
...
auto dmd = tryWait(pid);
if (dmd.terminated)
{
if (dmd.status == 0) writeln("Compilation succeeded!");
else writeln("Compilation failed");
}
else writeln("Still compiling...");
...
Note that in this example, the first wait call will have no
effect if the process has already terminated by the time tryWait
is called. In the opposite case, however, the scope statement
ensures that we always wait for the process if it hasn't terminated
by the time we reach the end of the scope.
tryWait((local variable) std.process.ProcessPipes ownerowner.std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safeThe Pid of the child process.
pid).terminated) void std.process.kill(std.process.Pid pid, int codeOrSignal)kill((local variable) std.process.ProcessPipes ownerowner.std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safeThe Pid of the child process.
pid, (constant) int core.sys.posix.signal.SIGKILL = 9SIGKILL);
int std.process.wait(std.process.Pid pid) @safeWaits for the process associated with pid to terminate, and returns
its exit status.
In general one should always wait for child processes to terminate
before exiting the parent process unless the process was spawned as detached
(that was spawned with Config.detached flag).
Otherwise, they may become "zombies"
– processes that are defunct, yet still occupy a slot in the OS process table.
You should not and must not wait for detached processes, since you don't own them.
If the process has already terminated, this function returns directly.
The exit code is cached, so that if wait() is called multiple times on
the same Pid it will always return the same value.
POSIX specific
If the process is terminated by a signal, this function returns a
negative number whose absolute value is the signal number.
Since POSIX restricts normal exit codes to the range 0-255, a
negative return value will always indicate termination by signal.
Signal codes are defined in the core.sys.posix.signal module
(which corresponds to the signal.h POSIX header).
Example
See the spawnProcess documentation.
wait((local variable) std.process.ProcessPipes ownerowner.std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safeThe Pid of the child process.
pid);
}
const (local variable) const(string) pathpath = (local variable) std.process.ProcessPipes ownerowner.std.stdio.File std.process.ProcessPipes.stdout() nothrow @property @safeAn File that allows reading from the child process'
standard output stream.
stdout.string std.stdio.File.readln!string(dchar terminator = '\n') @safeRead line from the file handle and return it as a specified type.
This version manages its own read buffer, which means one memory allocation per call. If you are not
retaining a reference to the read data, consider the File.readln(buf) version, which may offer
better performance as it can reuse its read buffer.
Note
String terminators are not supported due to ambiguity with readln(buf) below.
Example
// Reads `stdin` and writes it to `stdout`.
import std.stdio;
void main()
{
string line;
while ((line = stdin.readln()) !is null)
write(line);
}
readln().string std.string.strip!string(string str) pure nothrow @nogc @safeStrips both leading and trailing whitespace (as defined by
isWhite) or as specified in the second argument.
Examples
import std.uni : lineSep, paraSep;
assert(strip(" hello world ") ==
"hello world");
assert(strip("\n\t\v\rhello world\n\t\v\r") ==
"hello world");
assert(strip("hello world") ==
"hello world");
assert(strip([lineSep] ~ "hello world" ~ [lineSep]) ==
"hello world");
assert(strip([paraSep] ~ "hello world" ~ [paraSep]) ==
"hello world");
strip;
assert((local variable) const(string) pathpath.(field) ulong const(string).lengthlength, "Owner exited before acknowledging its checkpoint.");
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) busybusy = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute([string std.file.thisExePath() @trustedReturns the full path of the current executable.
Examples
import std.path : isAbsolute;
auto path = thisExePath();
assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);
thisExePath, "claim", (local variable) const(string) pathpath]);
assert((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) busybusy.status == 3, (field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0busy.output);
void std.process.kill(std.process.Pid pid, int codeOrSignal)kill((local variable) std.process.ProcessPipes ownerowner.std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safeThe Pid of the child process.
pid, (constant) int core.sys.posix.signal.SIGKILL = 9SIGKILL);
int std.process.wait(std.process.Pid pid) @safeWaits for the process associated with pid to terminate, and returns
its exit status.
In general one should always wait for child processes to terminate
before exiting the parent process unless the process was spawned as detached
(that was spawned with Config.detached flag).
Otherwise, they may become "zombies"
– processes that are defunct, yet still occupy a slot in the OS process table.
You should not and must not wait for detached processes, since you don't own them.
If the process has already terminated, this function returns directly.
The exit code is cached, so that if wait() is called multiple times on
the same Pid it will always return the same value.
POSIX specific
If the process is terminated by a signal, this function returns a
negative number whose absolute value is the signal number.
Since POSIX restricts normal exit codes to the range 0-255, a
negative return value will always indicate termination by signal.
Signal codes are defined in the core.sys.posix.signal module
(which corresponds to the signal.h POSIX header).
Example
See the spawnProcess documentation.
wait((local variable) std.process.ProcessPipes ownerowner.std.process.Pid std.process.ProcessPipes.pid() nothrow @property @safeThe Pid of the child process.
pid);
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) reclaimedreclaimed = std.typecons.Tuple!(int, "status", string, "output") std.process.execute(scope const(char[])[] args, const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), ulong maxOutput = 18446744073709551615LU, scope const(char)[] workDir = null) @safeExecutes the given program or shell command and returns its exit
code and output.
execute and executeShell start a new process using
spawnProcess and spawnShell, respectively, and wait
for the process to complete before returning. The functions capture
what the child process prints to both its standard output and
standard error streams, and return this together with its exit code.
auto dmd = execute(["dmd", "myapp.d"]);
if (dmd.status != 0) writeln("Compilation failed:\n", dmd.output);
auto ls = executeShell("ls -l");
if (ls.status != 0) writeln("Failed to retrieve file listing");
else writeln(ls.output);
The args/program/command, env and config
parameters are forwarded straight to the underlying spawn functions,
and we refer to their documentation for details.
POSIX specific
If the process is terminated by a signal, the status field of
the return value will contain a negative number whose absolute
value is the signal number. (See wait for details.)
execute([string std.file.thisExePath() @trustedReturns the full path of the current executable.
Examples
import std.path : isAbsolute;
auto path = thisExePath();
assert(path.exists);
assert(path.isAbsolute);
assert(path.isFile);
thisExePath, "claim", (local variable) const(string) pathpath]);
assert((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) reclaimedreclaimed.status == 0, (field) int std.typecons.Tuple!(int, "status", string, "output").__expand_field_0reclaimed.output);
assert(string std.file.readText!(string, const(string))(ref const(string) name) @safeReads and validates (using validate) a text file. S can be
an array of any character type. However, no width or endian conversions are
performed. So, if the width or endianness of the characters in the given
file differ from the width or endianness of the element type of S, then
validation will fail.
Examples
Read file with UTF-8 text.
write(deleteme, "abc"); // deleteme is the name of a temporary file
scope(exit) remove(deleteme);
string content = readText(deleteme);
assert(content == "abc");
readText((local variable) const(string) sourcesource) == "disk bytes");
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("active lease refused; killed owner reclaimed; durable payload recovered");
return 0;
}
if ((parameter) string[] argsargs[1] == "owner")
{
assert((parameter) string[] argsargs.(field) ulong string[].lengthlength == 3);
auto (local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory = (class) sparkles.recovery.directory.LeasedDirectoryOne archive's directory lock. Keep this owner alive until its storage work has
stopped, then close it explicitly. Other processes can claim an archive only
after its owner closes or terminates. Creation and claim serialize against
the base directory lock so a half-initialized archive cannot be claimed.
LeasedDirectory.sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) sparkles.recovery.directory.LeasedDirectory.create(string base, string durableRoot) nothrow @safeMake a private archive under an existing, already durable namespace root.
Sync the created subtree up to that root before publishing it. A platform
supplies the root: initialization must not open inaccessible ancestors
outside an Android application's private namespace.
create((parameter) string[] argsargs[2], (parameter) string[] argsargs[2]);
assert((local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.bool sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).hasValue!()() const pure nothrow @nogc @property @safeChecks if Expected has value
hasValue);
scope (exit) (local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
Note
Value is returned by reference only when hook provides onAccessEmptyValue.
Otherwise the T.init fallback forces it to be returned by value (a copy).
value.void sparkles.recovery.directory.LeasedDirectory.close() nothrow @nogc @safeReleases the lease; idempotent.
close();
const (local variable) const(sparkles.base.expected.Expected!(WriteReceipt, string, Abort)) writtenwritten = sparkles.base.expected.Expected!(WriteReceipt, string, Abort) sparkles.recovery.archive.appendGeneration(string directory, ulong generation, scope const(char)[] bytes, in sparkles.recovery.archive.ArchiveLayout layout = ArchiveLayout(".generation", "retired-", "SPARKLES-RECOVERY-RETIRED/1", 536870912LU)) nothrow @safeAppend bytes as generation, never replacing a file. The caller supplies an
existing private directory whose creation is already durable, and retains
earlier durable generations until this one is acknowledged durable.
appendGeneration((local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
Note
Value is returned by reference only when hook provides onAccessEmptyValue.
Otherwise the T.init fallback forces it to be returned by value (a copy).
value.string sparkles.recovery.directory.LeasedDirectory.path() const pure nothrow @nogc @safeThe archive's absolute path.
path, 1, "unsaved text");
assert((local variable) const(sparkles.base.expected.Expected!(WriteReceipt, string, Abort)) writtenwritten.bool sparkles.base.expected.Expected!(sparkles.recovery.archive.WriteReceipt, string, sparkles.base.expected.Abort).hasValue!()() const pure nothrow @nogc @property @safeChecks if Expected has value
hasValue && (local variable) const(sparkles.base.expected.Expected!(WriteReceipt, string, Abort)) writtenwritten.inout(sparkles.recovery.archive.WriteReceipt) sparkles.base.expected.Expected!(sparkles.recovery.archive.WriteReceipt, string, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
Note
Value is returned by reference only when hook provides onAccessEmptyValue.
Otherwise the T.init fallback forces it to be returned by value (a copy).
value.(field) bool sparkles.recovery.archive.WriteReceipt.durablethe directory sync after the commit succeeded
durable);
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln((local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
Note
Value is returned by reference only when hook provides onAccessEmptyValue.
Otherwise the T.init fallback forces it to be returned by value (a copy).
value.string sparkles.recovery.directory.LeasedDirectory.path() const pure nothrow @nogc @safeThe archive's absolute path.
path);
std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdout"() nothrow @nogc @property ref @systemstdout.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdout"() nothrow @nogc @property ref @systemflush();
string std.stdio.readln!string(dchar terminator = '\n') @systemRead line from stdin.
This version manages its own read buffer, which means one memory allocation per call. If you are not
retaining a reference to the read data, consider the ``readln(buf) version, which may offer
better performance as it can reuse its read buffer.
Note
String terminators are not supported due to ambiguity with readln(buf) below.
Example
Reads stdin and writes it to stdout.
import std.stdio;
void main()
{
string line;
while ((line = readln()) !is null)
write(line);
}
readln(); // Parent holds this pipe open until killing this task-owned process.
return 0;
}
assert((parameter) string[] argsargs[1] == "claim" && (parameter) string[] argsargs.(field) ulong string[].lengthlength == 3);
auto (local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory = (class) sparkles.recovery.directory.LeasedDirectoryOne archive's directory lock. Keep this owner alive until its storage work has
stopped, then close it explicitly. Other processes can claim an archive only
after its owner closes or terminates. Creation and claim serialize against
the base directory lock so a half-initialized archive cannot be claimed.
LeasedDirectory.sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) sparkles.recovery.directory.LeasedDirectory.claim(string path) nothrow @safeClaim an abandoned archive; an active archive returns a typed busy outcome.
claim((parameter) string[] argsargs[2]);
if ((local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.bool sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError)
{
if ((local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.inout(sparkles.recovery.directory.DirectoryIssue) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).error() inout pure nothrow @nogc @property ref @safeReturns the error value. May only be called when hasValue returns false.
If there is no error value, it calls hook's onAccessEmptyError.
It returns E.init when hook doesn't provide onAccessEmptyError.
Note
Error is returned by reference only when hook provides onAccessEmptyError.
Otherwise the E.init fallback forces it to be returned by value (a copy).
error.(field) sparkles.recovery.directory.DirectoryIssueKind sparkles.recovery.directory.DirectoryIssue.kindkind == (enum) sparkles.recovery.directory.DirectoryIssueKindWhy a lease was not granted.
DirectoryIssueKind.(enum value) sparkles.recovery.directory.DirectoryIssueKind.busy = cast(ubyte)0uanother live owner holds it
busy) return 3;
stderr.std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stderr"() nothrow @nogc @property ref @systemwriteln((local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.inout(sparkles.recovery.directory.DirectoryIssue) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).error() inout pure nothrow @nogc @property ref @safeReturns the error value. May only be called when hasValue returns false.
If there is no error value, it calls hook's onAccessEmptyError.
It returns E.init when hook doesn't provide onAccessEmptyError.
Note
Error is returned by reference only when hook provides onAccessEmptyError.
Otherwise the E.init fallback forces it to be returned by value (a copy).
error.(field) string sparkles.recovery.directory.DirectoryIssue.messagemessage);
return 2;
}
scope (exit) (local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
Note
Value is returned by reference only when hook provides onAccessEmptyValue.
Otherwise the T.init fallback forces it to be returned by value (a copy).
value.void sparkles.recovery.directory.LeasedDirectory.close() nothrow @nogc @safeReleases the lease; idempotent.
close();
assert(sparkles.base.expected.Expected!(string, string, Abort) sparkles.recovery.archive.readGeneration(string directory, ulong generation, in sparkles.recovery.archive.ArchiveLayout layout = ArchiveLayout(".generation", "retired-", "SPARKLES-RECOVERY-RETIRED/1", 536870912LU)) nothrow @safeThe payload of generation, read only from a regular file.
readGeneration((local variable) sparkles.base.expected.Expected!(LeasedDirectory, DirectoryIssue, Abort) directorydirectory.inout(sparkles.recovery.directory.LeasedDirectory) sparkles.base.expected.Expected!(sparkles.recovery.directory.LeasedDirectory, sparkles.recovery.directory.DirectoryIssue, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
Note
Value is returned by reference only when hook provides onAccessEmptyValue.
Otherwise the T.init fallback forces it to be returned by value (a copy).
value.string sparkles.recovery.directory.LeasedDirectory.path() const pure nothrow @nogc @safeThe archive's absolute path.
path, 1).inout(string) sparkles.base.expected.Expected!(string, string, sparkles.base.expected.Abort).value!()() inout pure nothrow @nogc @property ref @safeReturns the expected value if there is one.
With default Abort hook, it asserts when there is no value.
It calls hook's onAccessEmptyValue otherwise.
It returns T.init when hook doesn't provide onAccessEmptyValue.
Note
Value is returned by reference only when hook provides onAccessEmptyValue.
Otherwise the T.init fallback forces it to be returned by value (a copy).
value == "unsaved text");
return 0;
}