#!/usr/bin/env dub
/+ dub.sdl:
name "editor-native-close-probe"
dependency "sparkles:wsi" path="../../.."
dependency "sparkles:ui" path="../../.."
dependency "sparkles:wired" path="../../.."
dependency "sparkles:recovery" path="../../.."
dflags "-I$PACKAGE_DIR/../src" "-i=session_archive" "-i=session_record" "-i=document_files"
targetPath "../build"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
/// Exercise native process recovery and dirty-close decisions on a private X11 server.
module (module) editor_native_close_probeExercise native process recovery and dirty-close decisions on a private X11 server.
editor_native_close_probe;
import (module) xcb_nativexcb_native;
import (package) corecore.(package) core.stdcstdc.(module) core.stdc.stdlibD header file for C99.
pubs.opengroup.org/onlinepubs/009695399/basedefs/stdlib.h.html, stdlib.h
Source
core/stdc/stdlib.d
stdlib : (alias) editor_native_close_probe.free = void core.stdc.stdlib.free(void* ptr) nothrow @nogcfree;
import (package) corecore.(module) core.threadThe thread module provides support for thread creation and management.
Source
core/thread/package.d
thread : (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread;
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) editor_native_close_probe.SIGKILL = int core.sys.posix.signal.SIGKILL = 9SIGKILL;
import (package) corecore.(module) core.timeModule containing core time functionality, such as Duration (which
represents a duration of time) or MonoTime (which represents a
timestamp of the system's monotonic clock).
Various functions take a string (or strings) to represent a unit of time
(e.g. convert!("days", "hours")(numDays)). The valid strings to use
with such functions are "years", "months", "weeks", "days", "hours",
"minutes", "seconds", "msecs" (milliseconds), "usecs" (microseconds),
"hnsecs" (hecto-nanoseconds - i.e. 100 ns) or some subset thereof. There
are a few functions that also allow "nsecs", but very little actually
has precision greater than hnsecs.
Symbol Description Types Duration Represents a duration of time of weeks or less (kept internally as hnsecs). (e.g. 22 days or 700 seconds). TickDuration DEPRECATED Represents a duration of time in system clock ticks, using the highest precision that the system provides. MonoTime Represents a monotonic timestamp in system clock ticks, using the highest precision that the system provides. Functions convert Generic way of converting between two time units. dur Allows constructing a Duration from the given time units with the given length. weeks days hours
minutes seconds msecs
usecs hnsecs nsecs |
Convenience aliases for dur. |
| abs | Returns the absolute value of a duration. |
From Duration
From TickDuration
From units
To Duration tickDuration.to, std,conv!Duration() dur!"msecs"(5) or 5.msecs()
| To TickDuration |
duration.to, std,conv!TickDuration() |
|
TickDuration.from!"msecs"(msecs) |
| To units |
duration.total!"days" |
tickDuration.msecs |
convert!("days", "msecs")(msecs) |
Source
core/time.d
time : (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime, seconds, msecs;
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 : (struct) std.process.ConfigOptions that control the behaviour of process creation functions in this
module. Most options only apply to spawnProcess and
spawnShell.
Example
auto logFile = File("myapp_error.log", "w");
// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
Config.retainStderr | Config.suppressConsole);
scope(exit)
{
auto exitCode = wait(pid);
logFile.writeln("myapp exited with code ", exitCode);
logFile.close();
}
Config, (alias) editor_native_close_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) editor_native_close_probe.spawnProcess = std.process.Pid std.process.spawnProcess(scope const(char[])[] args, std.stdio.File stdin = makeGlobal(), std.stdio.File stdout = makeGlobal(), std.stdio.File stderr = makeGlobal(), const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char[]) workDir = null) @safeSpawns 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. It is recommended to always call wait
on the returned Pid unless the process was spawned with
Config.detached flag, as detailed in the documentation for wait.
Command line
There are four overloads of this function. The first two take an array
of strings, args, which should contain the program name as the
zeroth element and any command-line arguments in subsequent elements.
The third and fourth versions are included for convenience, and may be
used when there are no command-line arguments. They take a single string,
program, which specifies the program name.
Unless a directory is specified in args[0] or program,
spawnProcess will search for the program in a platform-dependent
manner. On POSIX systems, it will look for the executable in the
directories listed in the PATH environment variable, in the order
they are listed. On Windows, it will search for the executable in
the following sequence:
The directory from which the application loaded.
The current directory for the parent process.
The 32-bit Windows system directory.
The 16-bit Windows system directory.
The Windows directory.
The directories listed in the PATH environment variable.
// Run an executable called "prog" located in the current working
// directory:
auto pid = spawnProcess("./prog");
scope(exit) wait(pid);
// We can do something else while the program runs. The scope guard
// ensures that the process is waited for at the end of the scope.
...
// Run DMD on the file "myprog.d", specifying a few compiler switches:
auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
if (wait(dmdPid) != 0)
writeln("Compilation failed!");
Environment variables
By default, the child process inherits the environment of the parent
process, along with any additional variables specified in the env
parameter. If the same variable exists in both the parent's environment
and in env, the latter takes precedence.
If the Config.newEnv flag is set in config, the child
process will not inherit the parent's environment. Its entire
environment will then be determined by env.
wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv));
Standard streams
The optional arguments stdin, stdout and stderr may
be used to assign arbitrary File objects as the standard
input, output and error streams, respectively, of the child process. The
former must be opened for reading, while the latter two must be opened for
writing. The default is for the child process to inherit the standard
streams of its parent.
// Run DMD on the file myprog.d, logging any error messages to a
// file named errors.log.
auto logFile = File("errors.log", "w");
auto pid = spawnProcess(["dmd", "myprog.d"],
std.stdio.stdin,
std.stdio.stdout,
logFile);
if (wait(pid) != 0)
writeln("Compilation failed. See errors.log for details.");
Note that if you pass a File object that is not
one of the standard input/output/error streams of the parent process,
that stream will by default be closed in the parent process when
this function returns. See the Config documentation below for
information about how to disable this behaviour.
Beware of buffering issues when passing File objects to
spawnProcess. The child process will inherit the low-level raw
read/write offset associated with the underlying file descriptor, but
it will not be aware of any buffered data. In cases where this matters
(e.g. when a file should be aligned before being passed on to the
child process), it may be a good idea to use unbuffered streams, or at
least ensure all relevant buffers are flushed.
spawnProcess, (alias) editor_native_close_probe.thisProcessID = int std.process.thisProcessID() nothrow @nogc @property @trustedReturns the process ID of the current process,
which is guaranteed to be unique on the system.
Example
writefln("Current process ID: %d", thisProcessID);
thisProcessID, (alias) editor_native_close_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) editor_native_close_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) editor_native_close_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 : (struct) std.stdio.FileEncapsulates a FILE*. Generally D does not attempt to provide
thin wrappers over equivalent functions in the C standard library, but
manipulating FILE* values directly is unsafe and error-prone in
many ways. The File type ensures safe manipulation, automatic
file closing, and a lot of convenience.
The underlying FILE* handle is maintained in a reference-counted
manner, such that as soon as the last File variable bound to a
given FILE* goes out of scope, the underlying FILE* is
automatically closed.
Example
// test.d
import std.stdio;
void main(string[] args)
{
auto f = File("test.txt", "w"); // open for writing
f.write("Hello");
if (args.length > 1)
{
auto g = f; // now g and f write to the same file
// internal reference count is 2
g.write(", ", args[1]);
// g exits scope, reference count decreases to 1
}
f.writeln("!");
// f exits scope, reference count falls to zero,
// underlying `FILE*` is closed.
}
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% _
File, stdin, (alias template) editor_native_close_probe.write = std.stdio.write(T...)(T args) if (!is(T[0] : File))Writes its arguments in text format to standard output (without a trailing newline).
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++)
{
write("Input ", count, ": ", line, "\n");
}
}
write, (alias template) editor_native_close_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.pathThis module is used to manipulate path strings.
All functions, with the exception of expandTilde (and in some
cases absolutePath and relativePath), are pure
string manipulation functions; they don't depend on any state outside
the program, nor do they perform any actual file system actions.
This has the consequence that the module does not make any distinction
between a path that points to a directory and a path that points to a
file, and it does not know whether or not the object pointed to by the
path actually exists in the file system.
To differentiate between these cases, use isDir and
exists.
Note that on Windows, both the backslash (\) and the slash (/)
are in principle valid directory separators. This module treats them
both on equal footing, but in cases where a new separator is
added, a backslash will be used. Furthermore, the buildNormalizedPath
function will replace all slashes with backslashes on that platform.
In general, the functions in this module assume that the input paths
are well-formed. (That is, they should not contain invalid characters,
they should follow the file system's path format, etc.) The result
of calling a function on an ill-formed path is undefined. When there
is a chance that a path or a file name is invalid (for instance, when it
has been input by the user), it may sometimes be desirable to use the
isValidFilename and isValidPath functions to check
this.
Most functions do not perform any memory allocations, and if a string is
returned, it is usually a slice of an input string. If a function
allocates, this is explicitly mentioned in the documentation.
Category Functions Normalization absolutePath asAbsolutePath asNormalizedPath asRelativePath buildNormalizedPath buildPath chainPath expandTilde Partitioning baseName dirName dirSeparator driveName pathSeparator pathSplitter relativePath rootName stripDrive Validation isAbsolute isDirSeparator isRooted isValidFilename isValidPath Extension defaultExtension extension setExtension stripExtension withDefaultExtension withExtension Other filenameCharCmp filenameCmp globMatch CaseSensitive
Source
std/path.d
path : (alias template) editor_native_close_probe.baseName = std.path.baseName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && isSomeChar!(ElementType!R) && !isSomeString!R)Note
This function only strips away the specified suffix, which
doesn't necessarily have to represent an extension.
To remove the extension from a path, regardless of what the extension
is, use stripExtension.
To obtain the filename without leading directories and without
an extension, combine the functions like this:
assert(baseName(stripExtension("dir/file.ext")) == "file");
baseName, (alias template) editor_native_close_probe.buildPath = std.path.buildPath(Range)(scope Range segments) if (isInputRange!Range && !isInfinite!Range && isSomeString!(ElementType!Range))Combines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
buildPath, (alias template) editor_native_close_probe.dirName = std.path.dirName(R)(return scope R path) if (isRandomAccessRange!R && hasSlicing!R && hasLength!R && isSomeChar!(ElementType!R) && !isSomeString!R)Returns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
dirName;
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) editor_native_close_probe.dirEntries = std.file.dirEntries(bool useDIP1000 = dip1000Enabled)(string path, SpanMode mode, bool followSymlink = true)Returns an input range
of DirEntry that lazily iterates a given directory,
also provides two ways of foreach iteration. The iteration variable can be of
type string if only the name is needed, or DirEntry
if additional details are needed. The span mode dictates how the
directory is traversed. The name of each iterated directory entry
contains the absolute or relative path (depending on pathname).
Note
The order of returned directory entries is as it is provided by the
operating system / filesystem, and may not follow any particular sorting.
Example
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
remove(name);
}
// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
writeln(name);
}
// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
writeln(e.name, "\t", e.size);
}
// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
writeln(d.name);
// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
string cmd = "dmd -c " ~ d.name;
writeln(cmd);
std.process.executeShell(cmd);
}
// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
writeln(d.name);
To handle subdirectories with denied read permission, use SpanMode.shallow:
void scan(string path)
{
foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
{
try
{
writeln(entry.name);
if (entry.isDir)
scan(entry.name);
}
catch (FileException fe) { continue; } // ignore
}
}
scan("");
dirEntries, (alias template) editor_native_close_probe.mkdir = std.file.mkdir(R)(R pathname) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Make a new directory pathname.
mkdir, (alias template) editor_native_close_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) editor_native_close_probe.rmdirRecurse = void std.file.rmdirRecurse(scope const(char)[] pathname) @safeRemove directory and all of its content and subdirectories,
recursively.
rmdirRecurse, (enum) std.file.SpanModeDictates directory spanning policy for dirEntries (see below).
Examples
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;
auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;
root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;
alias removeRoot = (return scope e) => e.relativePath(root);
assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
[buildPath("animals", "cat"), "animals"]));
assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
["animals", buildPath("animals", "cat")]));
root.buildPath("plants").mkdir;
assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
["animals", "plants"]));
SpanMode, (alias) editor_native_close_probe.tempDir = string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/usr/tmp/
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
tempfile.tempdir.
tempDir, (alias) editor_native_close_probe.thisExePath = string std.file.thisExePath() @trustedReturns the full path of the current executable.
thisExePath;
import (package) stdstd.(module) std.uuidA UUID, or
Universally unique identifier,
is intended to uniquely identify information in a distributed environment
without significant central coordination. It can be
used to tag objects with very short lifetimes, or to reliably identify very
persistent objects across a network.
Category Functions
| Parsing UUIDs |
parseUUID
UUID
UUIDParsingException
uuidRegex
|
| Generating UUIDs |
sha1UUID
randomUUID
md5UUID
timestampRandomUUID
|
| Using UUIDs |
<a href="#uuidVersion">UUID.uuidVersion</a>
<a href="#variant">UUID.variant</a>
<a href="#toString">UUID.toString</a>
<a href="#data">UUID.data</a>
<a href="#swap">UUID.swap</a>
<a href="#opEquals">UUID.opEquals</a>
<a href="#opCmp">UUID.opCmp</a>
<a href="#toHash">UUID.toHash</a>
|
| UUID namespaces |
dnsNamespace
urlNamespace
oidNamespace
x500Namespace
|
UUIDs have many applications. Some examples follow: Databases may use UUIDs to identify
rows or records in order to ensure that they are unique across different
databases, or for publication/subscription services. Network messages may be
identified with a UUID to ensure that different parts of a message are put back together
again. Distributed computing may use UUIDs to identify a remote procedure call.
Transactions and classes involved in serialization may be identified by UUIDs.
Microsoft's component object model (COM) uses UUIDs to distinguish different software
component interfaces. UUIDs are inserted into documents from Microsoft Office programs.
UUIDs identify audio or video streams in the Advanced Systems Format (ASF). UUIDs are
also a basis for OIDs (object identifiers), and URNs (uniform resource name).
An attractive feature of UUIDs when compared to alternatives is their relative small size,
of 128 bits, or 16 bytes. Another is that the creation of UUIDs does not require
a centralized authority.
When UUIDs are generated by one of the defined mechanisms, they are either guaranteed
to be unique, different from all other generated UUIDs (that is, it has never been
generated before and it will never be generated again), or it is extremely likely
to be unique (depending on the mechanism).
For efficiency, UUID is implemented as a struct. UUIDs are therefore empty if not explicitly
initialized. An UUID is empty if <a href="#empty">UUID.empty</a> is true. Empty UUIDs are equal to
UUID.init, which is a UUID with all 16 bytes set to 0.
Use UUID's constructors or the UUID generator functions to get an initialized UUID.
This is a port of boost.uuid from the Boost project with some minor additions and API
changes for a more D-like API.
Source
std/uuid.d
Examples
import std.uuid;
UUID[] ids;
ids ~= randomUUID();
ids ~= md5UUID("test.name.123");
ids ~= sha1UUID("test.name.123");
foreach (entry; ids)
{
assert(entry.variant == UUID.Variant.rfc4122);
}
assert(ids[0].uuidVersion == UUID.Version.randomNumberBased);
assert(ids[1].toString() == "22390768-cced-325f-8f0f-cfeaa19d0ccd");
assert(ids[1].data == [34, 57, 7, 104, 204, 237, 50, 95, 143, 15, 207,
234, 161, 157, 12, 205]);
UUID id;
assert(id.empty);
uuid : (alias) editor_native_close_probe.randomUUID = std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safeThis function generates a random number based UUID from a random
number generator.
This function is not supported at compile time.
Warning
This function must not be used for cryptographic purposes.
UUIDs generated by this function do not have sufficient randomness
for all use cases.
This especially applies to the overload that accepts a caller-provided RNG.
At the moment, Phobos does not provide a cryptographically-secure
pseudo-random number generator (CSPRNG) that could be supplied to this
function.
While the function overload with no parameters will attempt to use the
system CSPRNG where available and implemented, there are no guarantees.
See unpredictableSeed for details.
randomUUID;
import (package) stdstd.(module) std.convA one-stop shop for converting values from one type to another.
Category Functions Generic asOriginalType castFrom parse to toChars bitCast Strings text wtext dtext writeText writeWText writeDText hexString Numeric octal roundTo signed unsigned Exceptions ConvException ConvOverflowException
Source
std/conv.d
conv : (alias template) editor_native_close_probe.text = std.conv.text(T...)(T args) if (T.length > 0)Convenience functions for converting one or more arguments
of any type into text (the three character widths).
text;
import (module) session_archiveThe editor's session generations: its record schema over sparkles:recovery's
numbered immutable archive. The layout keeps the names archives already on
disk use (<20 digits>.session, adopted-<20 digits>).
session_archive : (alias) editor_native_close_probe.readSessionGeneration = sparkles.base.expected.Expected!(SessionRecord, string, Abort) session_archive.readSessionGeneration(string directory, ulong generation) nothrow @safeValidate the complete immutable record and its identity before returning recovered contents.
readSessionGeneration, (alias) editor_native_close_probe.sessionGenerationOfName = ulong session_archive.sessionGenerationOfName(scope const(char)[] name) pure nothrow @nogc @safeRecognize a canonical positive generation filename; zero means an unrelated entry.
sessionGenerationOfName;
int int D main(string[] args) @systemmain((alias) object.string = stringstring[] (parameter) string[] argsargs) @system
{
if ((parameter) string[] argsargs.(field) ulong string[].lengthlength == 1 || ((parameter) string[] argsargs.(field) ulong string[].lengthlength == 2
&& ((parameter) string[] argsargs[1] == "--clipboard" || (parameter) string[] argsargs[1] == "--clipboard-withdrawal")))
{
auto (local variable) string[] commandcommand = ["xvfb-run", "-a", 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, "--private-server"];
if ((parameter) string[] argsargs.(field) ulong string[].lengthlength == 2) (local variable) string[] commandcommand ~= (parameter) string[] argsargs[1];
const (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult = 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((local variable) string[] commandcommand);
void std.stdio.write!string(string __param_0) @safeWrites its arguments in text format to standard output (without a trailing newline).
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++)
{
write("Input ", count, ": ", line, "\n");
}
}
write((local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.output);
return (local variable) const(std.typecons.Tuple!(int, "status", string, "output")) resultresult.status;
}
assert(((parameter) string[] argsargs.(field) ulong string[].lengthlength == 2 || (parameter) string[] argsargs.(field) ulong string[].lengthlength == 3) && (parameter) string[] argsargs[1] == "--private-server");
auto (local variable) _error_ connectionconnection = xcb_connect(null, null);
assert(connection !is null && !xcb_connection_has_error(connection));
scope (exit) xcb_disconnect(connection);
const (local variable) const(_error_) rootroot = xcb_setup_roots_iterator(xcb_get_setup(connection)).data.(field) _error_ xcb_setup_roots_iterator(xcb_get_setup(connection)).data.rootroot;
uint uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @systematom((alias) object.string = stringstring (parameter) string namename) @system
{
auto (local variable) _error_ replyreply = xcb_intern_atom_reply(connection,
xcb_intern_atom(connection, 0, cast(ushort) name.name.lengthlength, name.ptr), null);
assert(reply !is null);
scope (exit) void core.stdc.stdlib.free(void* ptr) nothrow @nogcfree(reply);
return reply.(field) _error_ reply.atomatom;
}
const (local variable) const(uint) nameAtomnameAtom = uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @systematom("_NET_WM_NAME");
const (local variable) const(string) statestate = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath(string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/usr/tmp/
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
tempfile.tempdir.
Examples
import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;
// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;
myFile.write("hello");
assert(myFile.readText == "hello");
tempDir, "editor-native-state-" ~ std.uuid.UUID std.uuid.randomUUID() nothrow @nogc @safeThis function generates a random number based UUID from a random
number generator.
This function is not supported at compile time.
Warning
This function must not be used for cryptographic purposes.
UUIDs generated by this function do not have sufficient randomness
for all use cases.
This especially applies to the overload that accepts a caller-provided RNG.
At the moment, Phobos does not provide a cryptographically-secure
pseudo-random number generator (CSPRNG) that could be supplied to this
function.
While the function overload with no parameters will attempt to use the
system CSPRNG where available and implemented, there are no guarantees.
See unpredictableSeed for details.
randomUUID().string std.uuid.UUID.toString() const pure nothrow @trustedReturn the UUID as a string in the canonical form.
Examples
immutable str = "8ab3060e-2cba-4f23-b74c-b52db3bdfb46";
auto id = UUID(str);
assert(id.toString() == str);
toString());
void std.file.mkdir!string(string pathname) @safeMake a new directory pathname.
mkdir((local variable) const(string) statestate);
scope (exit) void std.file.rmdirRecurse(scope const(char)[] pathname) @safeRemove directory and all of its content and subdirectories,
recursively.
rmdirRecurse((local variable) const(string) statestate);
auto (local variable) std.stdio.File loglog = (struct) std.stdio.FileEncapsulates a FILE*. Generally D does not attempt to provide
thin wrappers over equivalent functions in the C standard library, but
manipulating FILE* values directly is unsafe and error-prone in
many ways. The File type ensures safe manipulation, automatic
file closing, and a lot of convenience.
The underlying FILE* handle is maintained in a reference-counted
manner, such that as soon as the last File variable bound to a
given FILE* goes out of scope, the underlying FILE* is
automatically closed.
Example
// test.d
import std.stdio;
void main(string[] args)
{
auto f = File("test.txt", "w"); // open for writing
f.write("Hello");
if (args.length > 1)
{
auto g = f; // now g and f write to the same file
// internal reference count is 2
g.write(", ", args[1]);
// g exits scope, reference count decreases to 1
}
f.writeln("!");
// f exits scope, reference count falls to zero,
// underlying `FILE*` is closed.
}
% rdmd test.d Jimmy
% cat test.txt
Hello, Jimmy!
% _
File(std.stdio.File std.stdio.File.this(string name, scope const(char)[] stdioOpenmode = "rb") ref @safeConstructor taking the name of the file to open and the open mode.
Copying one File object to another results in the two File
objects referring to the same underlying file.
The destructor automatically closes the file as soon as no File
object refers to it anymore.
buildPath(string std.file.tempDir() @trustedReturns the path to a directory for temporary files.
On POSIX platforms, it searches through the following list of directories
and returns the first one which is found to exist:
The directory given by the TMPDIR environment variable.
The directory given by the TEMP environment variable.
The directory given by the TMP environment variable.
/tmp/
/var/tmp/
/usr/tmp/
On all platforms, tempDir returns the current working directory on failure.
The return value of the function is cached, so the procedures described
below will only be performed the first time the function is called. All
subsequent runs will return the same string, regardless of whether
environment variables and directory structures have changed in the
meantime.
The POSIX tempDir algorithm is inspired by Python's
tempfile.tempdir.
Examples
import std.ascii : letters;
import std.conv : to;
import std.path : buildPath;
import std.random : randomSample;
import std.utf : byCodeUnit;
// random id with 20 letters
auto id = letters.byCodeUnit.randomSample(20).to!string;
auto myFile = tempDir.buildPath(id ~ "my_tmp_file");
scope(exit) myFile.remove;
myFile.write("hello");
assert(myFile.readText == "hello");
tempDir, string std.conv.text!(string, int, string)(string __param_0, int __param_1, string __param_2) pure nothrow @safeConvenience functions for converting one or more arguments
of any type into text (the three character widths).
text("editor-native-close-", int std.process.thisProcessID() nothrow @nogc @property @trustedReturns the process ID of the current process,
which is guaranteed to be unique on the system.
Example
writefln("Current process ID: %d", thisProcessID);
thisProcessID, ".log")), "w");
const (local variable) const(string) editoreditor = string std.path.buildPath!char(const(char)[][] paths...) pure nothrow @safeCombines one or more path segments.
This function takes a set of path segments, given as an input
range of string elements or as a set of string arguments,
and concatenates them with each other. Directory separators
are inserted between segments if necessary. If any of the
path segments are absolute (as defined by isAbsolute), the
preceding segments will be dropped.
On Windows, if one of the path segments are rooted, but not absolute
(e.g. \foo), all preceding path segments down to the previous
root will be dropped. (See below for an example.)
This function always allocates memory to hold the resulting path.
The variadic overload is guaranteed to only perform a single
allocation, as is the range version if paths is a forward
range.
Examples
version (Posix)
{
assert(buildPath("foo", "bar", "baz") == "foo/bar/baz");
assert(buildPath("/foo/", "bar/baz") == "/foo/bar/baz");
assert(buildPath("/foo", "/bar") == "/bar");
}
version (Windows)
{
assert(buildPath("foo", "bar", "baz") == `foo\bar\baz`);
assert(buildPath(`c:\foo`, `bar\baz`) == `c:\foo\bar\baz`);
assert(buildPath("foo", `d:\bar`) == `d:\bar`);
assert(buildPath("foo", `\bar`) == `\bar`);
assert(buildPath(`c:\foo`, `\bar`) == `c:\bar`);
}
buildPath(__FILE_FULL_PATH__.string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safeReturns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
Examples
assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");
version (Windows)
{
assert(dirName(`dir\`) == `.`);
assert(dirName(`dir\\\`) == `.`);
assert(dirName(`dir\file`) == `dir`);
assert(dirName(`dir\\\file`) == `dir`);
assert(dirName(`dir\subdir\`) == `dir`);
assert(dirName(`\dir\file`) == `\dir`);
assert(dirName(`\file`) == `\`);
assert(dirName(`\`) == `\`);
assert(dirName(`\\\`) == `\`);
assert(dirName(`d:`) == `d:`);
assert(dirName(`d:file`) == `d:`);
assert(dirName(`d:\`) == `d:\`);
assert(dirName(`d:\file`) == `d:\`);
assert(dirName(`d:\dir\file`) == `d:\dir`);
assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
assert(dirName(`\\server\share\file`) == `\\server\share`);
assert(dirName(`\\server\share\`) == `\\server\share`);
assert(dirName(`\\server\share`) == `\\server\share`);
}
dirName.string std.path.dirName!(immutable(char))(return scope string path) pure nothrow @nogc @safeReturns the parent directory of path. On Windows, this
includes the drive letter if present. If path is a relative path and
the parent directory is the current working directory, returns ".".
Examples
assert(dirName("") == ".");
assert(dirName("file"w) == ".");
assert(dirName("dir/"d) == ".");
assert(dirName("dir///") == ".");
assert(dirName("dir/file"w.dup) == "dir");
assert(dirName("dir///file"d.dup) == "dir");
assert(dirName("dir/subdir/") == "dir");
assert(dirName("/dir/file"w) == "/dir");
assert(dirName("/file"d) == "/");
assert(dirName("/") == "/");
assert(dirName("///") == "/");
version (Windows)
{
assert(dirName(`dir\`) == `.`);
assert(dirName(`dir\\\`) == `.`);
assert(dirName(`dir\file`) == `dir`);
assert(dirName(`dir\\\file`) == `dir`);
assert(dirName(`dir\subdir\`) == `dir`);
assert(dirName(`\dir\file`) == `\dir`);
assert(dirName(`\file`) == `\`);
assert(dirName(`\`) == `\`);
assert(dirName(`\\\`) == `\`);
assert(dirName(`d:`) == `d:`);
assert(dirName(`d:file`) == `d:`);
assert(dirName(`d:\`) == `d:\`);
assert(dirName(`d:\file`) == `d:\`);
assert(dirName(`d:\dir\file`) == `d:\dir`);
assert(dirName(`\\server\share\dir\file`) == `\\server\share\dir`);
assert(dirName(`\\server\share\file`) == `\\server\share`);
assert(dirName(`\\server\share\`) == `\\server\share`);
assert(dirName(`\\server\share`) == `\\server\share`);
}
dirName, "build", "editor");
auto (local variable) std.process.Pid childchild = std.process.Pid std.process.spawnProcess(scope const(char[])[] args, std.stdio.File stdin = makeGlobal(), std.stdio.File stdout = makeGlobal(), std.stdio.File stderr = makeGlobal(), const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char[]) workDir = null) @safeSpawns 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. It is recommended to always call wait
on the returned Pid unless the process was spawned with
Config.detached flag, as detailed in the documentation for wait.
Command line
There are four overloads of this function. The first two take an array
of strings, args, which should contain the program name as the
zeroth element and any command-line arguments in subsequent elements.
The third and fourth versions are included for convenience, and may be
used when there are no command-line arguments. They take a single string,
program, which specifies the program name.
Unless a directory is specified in args`[0]` or `program`,
spawnProcess`` will search for the program in a platform-dependent
manner. On POSIX systems, it will look for the executable in the
directories listed in the PATH environment variable, in the order
they are listed. On Windows, it will search for the executable in
the following sequence:
The directory from which the application loaded.
The current directory for the parent process.
The 32-bit Windows system directory.
The 16-bit Windows system directory.
The Windows directory.
The directories listed in the PATH environment variable.
// Run an executable called "prog" located in the current working
// directory:
auto pid = spawnProcess("./prog");
scope(exit) wait(pid);
// We can do something else while the program runs. The scope guard
// ensures that the process is waited for at the end of the scope.
...
// Run DMD on the file "myprog.d", specifying a few compiler switches:
auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
if (wait(dmdPid) != 0)
writeln("Compilation failed!");
Environment variables
By default, the child process inherits the environment of the parent
process, along with any additional variables specified in the env
parameter. If the same variable exists in both the parent's environment
and in env, the latter takes precedence.
If the Config.newEnv flag is set in config, the child
process will not inherit the parent's environment. Its entire
environment will then be determined by env.
wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv));
Standard streams
The optional arguments stdin, stdout and stderr may
be used to assign arbitrary File objects as the standard
input, output and error streams, respectively, of the child process. The
former must be opened for reading, while the latter two must be opened for
writing. The default is for the child process to inherit the standard
streams of its parent.
// Run DMD on the file myprog.d, logging any error messages to a
// file named errors.log.
auto logFile = File("errors.log", "w");
auto pid = spawnProcess(["dmd", "myprog.d"],
std.stdio.stdin,
std.stdio.stdout,
logFile);
if (wait(pid) != 0)
writeln("Compilation failed. See errors.log for details.");
Note that if you pass a File object that is not
one of the standard input/output/error streams of the parent process,
that stream will by default be closed in the parent process when
this function returns. See the Config documentation below for
information about how to disable this behaviour.
Beware of buffering issues when passing File objects to
spawnProcess. The child process will inherit the low-level raw
read/write offset associated with the underlying file descriptor, but
it will not be aware of any buffered data. In cases where this matters
(e.g. when a file should be aligned before being passed on to the
child process), it may be a good idea to use unbuffered streams, or at
least ensure all relevant buffers are flushed.
spawnProcess([(local variable) const(string) editoreditor,
"--gui", "--window-system", "x11", "--state-dir", (local variable) const(string) statestate], stdin, std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdin"() nothrow @nogc @property ref @systemlog, (local variable) std.stdio.File loglog,
null, (struct) std.process.ConfigOptions that control the behaviour of process creation functions in this
module. Most options only apply to spawnProcess and
spawnShell.
Example
auto logFile = File("myapp_error.log", "w");
// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
Config.retainStderr | Config.suppressConsole);
scope(exit)
{
auto exitCode = wait(pid);
logFile.writeln("myapp exited with code ", exitCode);
logFile.close();
}
Config.(constant) std.process.Config std.process.Config.retainStdout = Config(Flags.retainStdout, null, null)For backwards compatibility, and cases when only flags need to
be specified in the Config, these allow building Config
instances using flag names only.
retainStdout | std.process.Config std.process.Config.opBinary!"|"(std.process.Config other) pure nothrow @nogc @safeFor backwards compatibility, and cases when only flags need to
be specified in the Config, these allow building Config
instances using flag names only.
Config.(constant) std.process.Config std.process.Config.retainStderr = Config(Flags.retainStderr, null, null)For backwards compatibility, and cases when only flags need to
be specified in the Config, these allow building Config
instances using flag names only.
retainStderr);
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.Pid childchild).terminated) 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((local variable) std.process.Pid childchild);
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.Pid childchild);
}
uint (local variable) uint windowwindow;
void void editor_native_close_probe.main.findWindow() nothrow @systemfindWindow() @system
{
(local variable) uint windowwindow = 0;
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 15.seconds;
while (!(local variable) uint windowwindow && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
deadline)
{
auto (local variable) _error_ replyreply = xcb_query_tree_reply(connection, xcb_query_tree(connection, root), null);
assert(reply !is null);
scope (exit) void core.stdc.stdlib.free(void* ptr) nothrow @nogcfree(reply);
foreach ((parameter) candidatecandidate; xcb_query_tree_children(reply)[0 .. xcb_query_tree_children_length(reply)])
{
auto _error_ propertyproperty = xcb_get_property_reply(connection,
xcb_get_property(connection, 0, candidate, nameAtom, XCB_GET_PROPERTY_TYPE_ANY, 0, 100), null);
if (property is null) continue;
scope (exit) free(property);
const _error_ lengthlength = xcb_get_property_value_length(property);
const _error_ namename = (cast(const(char)*) xcb_get_property_value(property))[0 .. length];
if (name == "Sparkles Editor") { window = candidate; break; }
}
assert(!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.Pid childchild).terminated, "Editor exited before its window appeared: " ~ string std.file.readText!(string, string)(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) std.stdio.File loglog.string std.stdio.File.name() const pure nothrow @property return @safeReturns the name last used to initialize this File, if any.
Some functions that create or initialize the File set the name field to null.
Examples include tmpfile, wrapFile, and fdopen. See the
documentation of those functions for details.
name));
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(20.msecs);
}
assert((local variable) uint windowwindow, "Editor window did not appear.");
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(400.msecs);
}
void editor_native_close_probe.main.findWindow() nothrow @systemfindWindow();
void void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(ubyte (parameter) ubyte codecode, ushort (parameter) ushort modifiersmodifiers = 0) @system
{
xcb_key_press_event_t (local variable) _error_ eventevent;
event.response_type = XCB_KEY_PRESS;
event.detail = code;
event.event.rootroot = root;
event.event.eventevent = window;
event.same_screen = 1;
event.event.statestate = modifiers;
xcb_send_event(connection, 0, window, XCB_EVENT_MASK_KEY_PRESS, cast(const(char)*) &event);
event.response_type = XCB_KEY_RELEASE;
xcb_send_event(connection, 0, window, XCB_EVENT_MASK_KEY_RELEASE, cast(const(char)*) &event);
xcb_flush(connection);
}
void void editor_native_close_probe.main.closeWindow() pure nothrow @nogc @systemcloseWindow() @system
{
xcb_client_message_event_t (local variable) _error_ eventevent;
event.response_type = XCB_CLIENT_MESSAGE;
event.format = 32;
event.event.windowwindow = window;
event.type = atom("WM_PROTOCOLS");
event.data.data32[0] = atom("WM_DELETE_WINDOW");
xcb_send_event(connection, 0, window, XCB_EVENT_MASK_NO_EVENT, cast(const(char)*) &event);
xcb_flush(connection);
}
(alias) object.string = stringstring (local variable) string latestDraftslatestDrafts;
ulong (local variable) ulong observedGenerationobservedGeneration;
bool bool editor_native_close_probe.main.hasDraft(string expected) @systemhasDraft((alias) object.string = stringstring (parameter) string expectedexpected) @system
{
foreach ((local variable) std.file.DirEntry archivearchive; std.file._DirIterator!true std.file.dirEntries!true(string path, std.file.SpanMode mode, bool followSymlink = true) @safeReturns an input range
of DirEntry that lazily iterates a given directory,
also provides two ways of foreach iteration. The iteration variable can be of
type string if only the name is needed, or DirEntry
if additional details are needed. The span mode dictates how the
directory is traversed. The name of each iterated directory entry
contains the absolute or relative path (depending on pathname).
Note
The order of returned directory entries is as it is provided by the
operating system / filesystem, and may not follow any particular sorting.
Example
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
remove(name);
}
// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
writeln(name);
}
// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
writeln(e.name, "\t", e.size);
}
// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
writeln(d.name);
// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
string cmd = "dmd -c " ~ d.name;
writeln(cmd);
std.process.executeShell(cmd);
}
// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
writeln(d.name);
To handle subdirectories with denied read permission, use SpanMode.shallow:
void scan(string path)
{
foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
{
try
{
writeln(entry.name);
if (entry.isDir)
scan(entry.name);
}
catch (FileException fe) { continue; } // ignore
}
}
scan("");
Examples
Duplicate functionality of D1's std.file.listdir():
string[] listdir(string pathname)
{
import std.algorithm.iteration : map, filter;
import std.array : array;
import std.path : baseName;
return dirEntries(pathname, SpanMode.shallow)
.filter!(a => a.isFile)
.map!((return a) => baseName(a.name))
.array;
}
// Can be safe only with -preview=dip1000
@safe void main(string[] args)
{
import std.stdio : writefln;
string[] files = listdir(args[1]);
writefln("%s", files);
}
dirEntries((local variable) const(string) statestate, (enum) std.file.SpanModeDictates directory spanning policy for dirEntries (see below).
Examples
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;
auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;
root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;
alias removeRoot = (return scope e) => e.relativePath(root);
assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
[buildPath("animals", "cat"), "animals"]));
assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
["animals", buildPath("animals", "cat")]));
root.buildPath("plants").mkdir;
assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
["animals", "plants"]));
SpanMode.(enum value) std.file.SpanMode.shallow = 0Only spans one directory.
shallow))
{
if (!(local variable) std.file.DirEntry archivearchive.bool std.file.DirEntry.isDir() @property scope @safeisDir || (local variable) std.file.DirEntry archivearchive.bool std.file.DirEntry.isSymlink() @property scope @safeisSymlink) continue;
foreach ((local variable) std.file.DirEntry filefile; std.file._DirIterator!true std.file.dirEntries!true(string path, std.file.SpanMode mode, bool followSymlink = true) @safeReturns an input range
of DirEntry that lazily iterates a given directory,
also provides two ways of foreach iteration. The iteration variable can be of
type string if only the name is needed, or DirEntry
if additional details are needed. The span mode dictates how the
directory is traversed. The name of each iterated directory entry
contains the absolute or relative path (depending on pathname).
Note
The order of returned directory entries is as it is provided by the
operating system / filesystem, and may not follow any particular sorting.
Example
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
remove(name);
}
// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
writeln(name);
}
// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
writeln(e.name, "\t", e.size);
}
// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
writeln(d.name);
// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
string cmd = "dmd -c " ~ d.name;
writeln(cmd);
std.process.executeShell(cmd);
}
// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
writeln(d.name);
To handle subdirectories with denied read permission, use SpanMode.shallow:
void scan(string path)
{
foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
{
try
{
writeln(entry.name);
if (entry.isDir)
scan(entry.name);
}
catch (FileException fe) { continue; } // ignore
}
}
scan("");
Examples
Duplicate functionality of D1's std.file.listdir():
string[] listdir(string pathname)
{
import std.algorithm.iteration : map, filter;
import std.array : array;
import std.path : baseName;
return dirEntries(pathname, SpanMode.shallow)
.filter!(a => a.isFile)
.map!((return a) => baseName(a.name))
.array;
}
// Can be safe only with -preview=dip1000
@safe void main(string[] args)
{
import std.stdio : writefln;
string[] files = listdir(args[1]);
writefln("%s", files);
}
dirEntries((local variable) std.file.DirEntry archivearchive.string std.file.DirEntry.name() const pure nothrow @property return scope @safename, (enum) std.file.SpanModeDictates directory spanning policy for dirEntries (see below).
Examples
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;
auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;
root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;
alias removeRoot = (return scope e) => e.relativePath(root);
assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
[buildPath("animals", "cat"), "animals"]));
assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
["animals", buildPath("animals", "cat")]));
root.buildPath("plants").mkdir;
assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
["animals", "plants"]));
SpanMode.(enum value) std.file.SpanMode.shallow = 0Only spans one directory.
shallow))
{
const (local variable) const(ulong) generationgeneration = ulong session_archive.sessionGenerationOfName(scope const(char)[] name) pure nothrow @nogc @safeRecognize a canonical positive generation filename; zero means an unrelated entry.
sessionGenerationOfName(string std.path.baseName!(immutable(char))(return scope string path) pure nothrow @nogc @safeNote
This function only strips away the specified suffix, which
doesn't necessarily have to represent an extension.
To remove the extension from a path, regardless of what the extension
is, use stripExtension.
To obtain the filename without leading directories and without
an extension, combine the functions like this:
assert(baseName(stripExtension("dir/file.ext")) == "file");
baseName((local variable) std.file.DirEntry filefile.string std.file.DirEntry.name() const pure nothrow @property return scope @safename));
if (!(local variable) const(ulong) generationgeneration) continue;
const (local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord = sparkles.base.expected.Expected!(SessionRecord, string, Abort) session_archive.readSessionGeneration(string directory, ulong generation) nothrow @safeValidate the complete immutable record and its identity before returning recovered contents.
Examples
A newer generation and a refused duplicate leave earlier dirty contents recoverable.
version (Posix) {}
else
{
import sparkles.test_runner.skip : skipTest;
skipTest("The native POSIX archive adapter is not available.");
}
import sparkles.test_utils.tmpfs : TmpFS;
import std.file : readText;
auto fixture = TmpFS.create();
const source = fixture.writeFile("disk");
SessionRecord record;
record.generation = 1;
record.active = 7;
record.tabs = [SessionTab(id: 7, path: source, name: "draft", content: "dirty\r\n",
savedContent: "disk", selections: [SessionSelection(0, 0)])];
const first = appendSessionGeneration(fixture.dir, record);
assert(first.hasValue && first.value.durable);
record.generation = 2;
record.tabs[0].content = "newer\r\n";
const second = appendSessionGeneration(fixture.dir, record);
assert(second.hasValue && second.value.durable);
record.generation = 1;
assert(appendSessionGeneration(fixture.dir, record).hasError);
const old = readSessionGeneration(fixture.dir, 1);
const latest = readSessionGeneration(fixture.dir, 2);
assert(old.hasValue && old.value.tabs[0].content == "dirty\r\n");
assert(latest.hasValue && latest.value.tabs[0].content == "newer\r\n");
assert((() @trusted => readText(source))() == "disk");
Retention preserves damaged and future generations while bounding older valid files.
version (linux) {}
else
{
import sparkles.test_runner.skip : skipTest;
skipTest("The native recovery archive currently requires Linux.");
}
import sparkles.recovery.directory : SessionDirectory = LeasedDirectory;
import sparkles.test_utils.tmpfs : TmpFS;
import std.conv : text;
import std.file : write;
auto fixture = TmpFS.create();
auto directory = SessionDirectory.create(buildPath(fixture.dir, "archives"), fixture.dir);
assert(directory.hasValue);
scope (exit) directory.value.close();
SessionRecord record;
record.active = 7;
record.tabs = [SessionTab(id: 7, name: "draft", selections: [SessionSelection(0, 0)])];
foreach (generation; 1UL .. 6UL)
{
record.generation = generation;
record.tabs[0].content = text(generation);
assert(appendSessionGeneration(directory.value.path, record).hasValue);
}
(() @trusted { write(buildPath(directory.value.path, "00000000000000000002.session"), "damaged"); })();
const report = pruneSessionArchive(directory.value, 4);
assert(report.removed.length == 1 && report.removed[0] == 1 && report.issues.length == 1);
assert(readSessionGeneration(directory.value.path, 1).hasError);
assert(readSessionGeneration(directory.value.path, 3).hasValue);
assert(readSessionGeneration(directory.value.path, 4).hasValue);
assert(readSessionGeneration(directory.value.path, 5).hasValue);
import std.file : readText;
assert((() @trusted => readText(buildPath(directory.value.path, "00000000000000000002.session")))() == "damaged");
readSessionGeneration((local variable) std.file.DirEntry archivearchive.string std.file.DirEntry.name() const pure nothrow @property return scope @safename, (local variable) const(ulong) generationgeneration);
if ((local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord.bool sparkles.base.expected.Expected!(session_record.SessionRecord, string, sparkles.base.expected.Abort).hasError!()() const pure nothrow @nogc @property @safeChecks if Expected has error
hasError) continue;
if ((local variable) const(ulong) generationgeneration >= (local variable) ulong observedGenerationobservedGeneration)
{
(local variable) ulong observedGenerationobservedGeneration = (local variable) const(ulong) generationgeneration;
(local variable) string latestDraftslatestDrafts = "";
foreach ((parameter) const(session_record.SessionTab) tabtab; (local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord.inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabstabs) (local variable) string latestDraftslatestDrafts ~= "[" ~ (local variable) const(session_record.SessionTab) tabtab.(field) string session_record.SessionTab.contentcontent ~ "]";
}
foreach ((parameter) const(session_record.SessionTab) tabtab; (local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord.inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabstabs) if ((local variable) const(session_record.SessionTab) tabtab.(field) string session_record.SessionTab.contentcontent == (parameter) string expectedexpected) return true;
}
}
return false;
}
void void editor_native_close_probe.main.awaitDraft(string expected) @systemawaitDraft((alias) object.string = stringstring (parameter) string expectedexpected) @system
{
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (!bool editor_native_close_probe.main.hasDraft(string expected) @systemhasDraft((parameter) string expectedexpected) && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
deadline)
{
assert(!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.Pid childchild).terminated, (field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0readText((local variable) std.stdio.File loglog.string std.stdio.File.name() const pure nothrow @property return @safeReturns the name last used to initialize this File, if any.
Some functions that create or initialize the File set the name field to null.
Examples include tmpfile, wrapFile, and fdopen. See the
documentation of those functions for details.
name));
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(10.msecs);
}
assert(bool editor_native_close_probe.main.hasDraft(string expected) @systemhasDraft((parameter) string expectedexpected), "Expected recovery contents were not checkpointed: " ~ (parameter) string expectedexpected
~ "; latest private-fixture tabs: " ~ (local variable) string latestDraftslatestDrafts ~ "\n" ~ string std.file.readText!(string, string)(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) std.stdio.File loglog.string std.stdio.File.name() const pure nothrow @property return @safeReturns the name last used to initialize this File, if any.
Some functions that create or initialize the File set the name field to null.
Examples include tmpfile, wrapFile, and fdopen. See the
documentation of those functions for details.
name));
}
if ((parameter) string[] argsargs.(field) ulong string[].lengthlength == 3 && ((parameter) string[] argsargs[2] == "--clipboard" || (parameter) string[] argsargs[2] == "--clipboard-withdrawal"))
{
const (local variable) const(uint) clipboardclipboard = uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @systematom("CLIPBOARD"), (local variable) const(uint) targetstargets = uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @systematom("TARGETS"), (local variable) const(uint) utf8utf8 = uint editor_native_close_probe.main.atom(string name) pure nothrow @nogc @systematom("UTF8_STRING");
const (local variable) const(_error_) ownerowner = xcb_generate_id(connection);
xcb_create_window(connection, 0, owner, root, -1, -1, 1, 1, 0,
XCB_WINDOW_CLASS_INPUT_ONLY, XCB_COPY_FROM_PARENT, 0, null);
xcb_set_selection_owner(connection, owner, clipboard, XCB_CURRENT_TIME);
xcb_flush(connection);
xcb_selection_request_event_t[] (local variable) _error_ requestsrequests;
bool (local variable) bool advertisedadvertised;
void editor_native_close_probe.main.answeranswer(in xcb_selection_request_event_t (parameter) xcb_selection_request_event_t requestrequest, (alias) object.string = stringstring (parameter) string valuevalue, bool advertise = false)
{
const _error_ propertyproperty = request.request.propertyproperty == XCB_NONE ? request.target : request.request.propertyproperty;
if (advertise)
{
uint[2] _error_ supportedsupported = [targets, utf8];
xcb_change_property(connection, XCB_PROP_MODE_REPLACE, request.requestor,
property, XCB_ATOM_ATOM, 32, 2, supported.ptr);
}
else xcb_change_property(connection, XCB_PROP_MODE_REPLACE, request.requestor,
property, utf8, 8, cast(uint) value.value.lengthlength, value.ptr);
xcb_selection_notify_event_t _error_ responseresponse;
response.response_type = XCB_SELECTION_NOTIFY;
response.response.timetime = request.request.timetime;
response.requestor = request.requestor;
response.selection = request.selection;
response.target = request.target;
response.response.propertyproperty = property;
xcb_send_event(connection, 0, request.requestor, XCB_EVENT_MASK_NO_EVENT,
cast(const(char)*) &response);
xcb_flush(connection);
}
void void editor_native_close_probe.main.pump() pure nothrow @nogc @safepump()
{
while (auto (local variable) _error_ eventevent = xcb_poll_for_event(connection))
{
scope (exit) void core.stdc.stdlib.free(void* ptr) nothrow @nogcfree(event);
if ((event.response_type & 0x7F) != XCB_SELECTION_REQUEST) continue;
const (local variable) const(_error_) requestrequest = *cast(xcb_selection_request_event_t*) event;
if (request.target == (local variable) const(uint) targetstargets) { answer(request, "", true); (local variable) bool advertisedadvertised = true; }
else { assert(request.target == (local variable) const(uint) utf8utf8); requests ~= request; }
}
}
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) offerDeadlineofferDeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (!(local variable) bool advertisedadvertised && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
offerDeadline) { void editor_native_close_probe.main.pump() pure nothrow @nogc @safepump(); (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(10.msecs); }
assert((local variable) bool advertisedadvertised, "The native backend did not discover the private clipboard offer.");
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs);
void void editor_native_close_probe.main.awaitRequest(ulong count) nothrow @safeawaitRequest((alias) object.size_t = ulongsize_t (parameter) ulong countcount)
{
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (requests.(field) _error_ requests.lengthlength < (parameter) ulong countcount && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline)
{
assert(!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.Pid childchild).terminated, (field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0readText((local variable) std.stdio.File loglog.string std.stdio.File.name() const pure nothrow @property return @safeReturns the name last used to initialize this File, if any.
Some functions that create or initialize the File set the name field to null.
Examples include tmpfile, wrapFile, and fdopen. See the
documentation of those functions for details.
name));
void editor_native_close_probe.main.pump() pure nothrow @nogc @safepump();
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(10.msecs);
}
assert(requests.(field) _error_ requests.lengthlength == (parameter) ulong countcount, text("Expected ", count,
" native clipboard requests, received ", requests.requests.lengthlength, '.'));
}
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(55, XCB_MOD_MASK_CONTROL); // Ctrl+V in the first tab; hold its reply.
void editor_native_close_probe.main.awaitRequest(ulong count) nothrow @safeawaitRequest(1);
const (local variable) const(bool) withdrawnwithdrawn = (parameter) string[] argsargs[2] == "--clipboard-withdrawal";
if ((local variable) const(bool) withdrawnwithdrawn)
foreach ((local variable) int iterationiteration; 0 .. 8)
{
const (local variable) const(_error_) replacementreplacement = xcb_generate_id(connection);
xcb_create_window(connection, 0, replacement, root, -1, -1, 1, 1, 0,
XCB_WINDOW_CLASS_INPUT_ONLY, XCB_COPY_FROM_PARENT, 0, null);
(local variable) bool advertisedadvertised = false;
xcb_set_selection_owner(connection, replacement, clipboard, XCB_CURRENT_TIME);
xcb_flush(connection);
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) replacementDeadlinereplacementDeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (!(local variable) bool advertisedadvertised && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
replacementDeadline)
{ void editor_native_close_probe.main.pump() pure nothrow @nogc @safepump(); (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(10.msecs); }
assert((local variable) bool advertisedadvertised, "The replacement provider was not discovered.");
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs);
if ((local variable) int iterationiteration != 7)
{
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(55, XCB_MOD_MASK_CONTROL);
void editor_native_close_probe.main.awaitRequest(ulong count) nothrow @safeawaitRequest((local variable) int iterationiteration + 2);
}
}
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(57, XCB_MOD_MASK_CONTROL); // Ctrl+N creates a second tab.
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(55, XCB_MOD_MASK_CONTROL);
void editor_native_close_probe.main.awaitRequest(ulong count) nothrow @safeawaitRequest((local variable) const(bool) withdrawnwithdrawn ? 9 : 2);
if ((local variable) const(bool) withdrawnwithdrawn)
{
answer(requests[0], "STALE PROVIDER");
answer(requests[1], "ANOTHER STALE PROVIDER");
// This later key is an X11 ordering barrier. Its checkpoint must
// not contain bytes from the withdrawn transfer, even briefly.
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(53); // x
void editor_native_close_probe.main.awaitDraft(string expected) @systemawaitDraft("x");
answer(requests[$ - 1], "from B");
void editor_native_close_probe.main.awaitDraft(string expected) @systemawaitDraft("xfrom B");
}
else
{
answer(requests[1], "from B");
void editor_native_close_probe.main.awaitDraft(string expected) @systemawaitDraft("from B");
answer(requests[0], "from A");
}
bool (local variable) bool pairedpaired;
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) pairDeadlinepairDeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (!(local variable) bool pairedpaired && (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
pairDeadline)
{
foreach ((local variable) std.file.DirEntry archivearchive; std.file._DirIterator!true std.file.dirEntries!true(string path, std.file.SpanMode mode, bool followSymlink = true) @safeReturns an input range
of DirEntry that lazily iterates a given directory,
also provides two ways of foreach iteration. The iteration variable can be of
type string if only the name is needed, or DirEntry
if additional details are needed. The span mode dictates how the
directory is traversed. The name of each iterated directory entry
contains the absolute or relative path (depending on pathname).
Note
The order of returned directory entries is as it is provided by the
operating system / filesystem, and may not follow any particular sorting.
Example
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
remove(name);
}
// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
writeln(name);
}
// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
writeln(e.name, "\t", e.size);
}
// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
writeln(d.name);
// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
string cmd = "dmd -c " ~ d.name;
writeln(cmd);
std.process.executeShell(cmd);
}
// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
writeln(d.name);
To handle subdirectories with denied read permission, use SpanMode.shallow:
void scan(string path)
{
foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
{
try
{
writeln(entry.name);
if (entry.isDir)
scan(entry.name);
}
catch (FileException fe) { continue; } // ignore
}
}
scan("");
Examples
Duplicate functionality of D1's std.file.listdir():
string[] listdir(string pathname)
{
import std.algorithm.iteration : map, filter;
import std.array : array;
import std.path : baseName;
return dirEntries(pathname, SpanMode.shallow)
.filter!(a => a.isFile)
.map!((return a) => baseName(a.name))
.array;
}
// Can be safe only with -preview=dip1000
@safe void main(string[] args)
{
import std.stdio : writefln;
string[] files = listdir(args[1]);
writefln("%s", files);
}
dirEntries((local variable) const(string) statestate, (enum) std.file.SpanModeDictates directory spanning policy for dirEntries (see below).
Examples
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;
auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;
root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;
alias removeRoot = (return scope e) => e.relativePath(root);
assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
[buildPath("animals", "cat"), "animals"]));
assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
["animals", buildPath("animals", "cat")]));
root.buildPath("plants").mkdir;
assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
["animals", "plants"]));
SpanMode.(enum value) std.file.SpanMode.shallow = 0Only spans one directory.
shallow))
{
if (!(local variable) std.file.DirEntry archivearchive.bool std.file.DirEntry.isDir() @property scope @safeisDir) continue;
foreach ((local variable) std.file.DirEntry filefile; std.file._DirIterator!true std.file.dirEntries!true(string path, std.file.SpanMode mode, bool followSymlink = true) @safeReturns an input range
of DirEntry that lazily iterates a given directory,
also provides two ways of foreach iteration. The iteration variable can be of
type string if only the name is needed, or DirEntry
if additional details are needed. The span mode dictates how the
directory is traversed. The name of each iterated directory entry
contains the absolute or relative path (depending on pathname).
Note
The order of returned directory entries is as it is provided by the
operating system / filesystem, and may not follow any particular sorting.
Example
// Iterate a directory in depth
foreach (string name; dirEntries("destroy/me", SpanMode.depth))
{
remove(name);
}
// Iterate the current directory in breadth
foreach (string name; dirEntries("", SpanMode.breadth))
{
writeln(name);
}
// Iterate a directory and get detailed info about it
foreach (DirEntry e; dirEntries("dmd-testing", SpanMode.breadth))
{
writeln(e.name, "\t", e.size);
}
// Iterate over all *.d files in current directory and all its subdirectories
auto dFiles = dirEntries("", SpanMode.depth).filter!(f => f.name.endsWith(".d"));
foreach (d; dFiles)
writeln(d.name);
// Hook it up with std.parallelism to compile them all in parallel:
foreach (d; parallel(dFiles, 1)) //passes by 1 file to each thread
{
string cmd = "dmd -c " ~ d.name;
writeln(cmd);
std.process.executeShell(cmd);
}
// Iterate over all D source files in current directory and all its
// subdirectories
auto dFiles = dirEntries("","*.{d,di}",SpanMode.depth);
foreach (d; dFiles)
writeln(d.name);
To handle subdirectories with denied read permission, use SpanMode.shallow:
void scan(string path)
{
foreach (DirEntry entry; dirEntries(path, SpanMode.shallow))
{
try
{
writeln(entry.name);
if (entry.isDir)
scan(entry.name);
}
catch (FileException fe) { continue; } // ignore
}
}
scan("");
Examples
Duplicate functionality of D1's std.file.listdir():
string[] listdir(string pathname)
{
import std.algorithm.iteration : map, filter;
import std.array : array;
import std.path : baseName;
return dirEntries(pathname, SpanMode.shallow)
.filter!(a => a.isFile)
.map!((return a) => baseName(a.name))
.array;
}
// Can be safe only with -preview=dip1000
@safe void main(string[] args)
{
import std.stdio : writefln;
string[] files = listdir(args[1]);
writefln("%s", files);
}
dirEntries((local variable) std.file.DirEntry archivearchive.string std.file.DirEntry.name() const pure nothrow @property return scope @safename, (enum) std.file.SpanModeDictates directory spanning policy for dirEntries (see below).
Examples
import std.algorithm.comparison : equal;
import std.algorithm.iteration : map;
import std.algorithm.sorting : sort;
import std.array : array;
import std.path : buildPath, relativePath;
auto root = deleteme ~ "root";
scope(exit) root.rmdirRecurse;
root.mkdir;
root.buildPath("animals").mkdir;
root.buildPath("animals", "cat").mkdir;
alias removeRoot = (return scope e) => e.relativePath(root);
assert(root.dirEntries(SpanMode.depth).map!removeRoot.equal(
[buildPath("animals", "cat"), "animals"]));
assert(root.dirEntries(SpanMode.breadth).map!removeRoot.equal(
["animals", buildPath("animals", "cat")]));
root.buildPath("plants").mkdir;
assert(root.dirEntries(SpanMode.shallow).array.sort.map!removeRoot.equal(
["animals", "plants"]));
SpanMode.(enum value) std.file.SpanMode.shallow = 0Only spans one directory.
shallow))
{
const (local variable) const(ulong) generationgeneration = ulong session_archive.sessionGenerationOfName(scope const(char)[] name) pure nothrow @nogc @safeRecognize a canonical positive generation filename; zero means an unrelated entry.
sessionGenerationOfName(string std.path.baseName!(immutable(char))(return scope string path) pure nothrow @nogc @safeNote
This function only strips away the specified suffix, which
doesn't necessarily have to represent an extension.
To remove the extension from a path, regardless of what the extension
is, use stripExtension.
To obtain the filename without leading directories and without
an extension, combine the functions like this:
assert(baseName(stripExtension("dir/file.ext")) == "file");
baseName((local variable) std.file.DirEntry filefile.string std.file.DirEntry.name() const pure nothrow @property return scope @safename));
if (!(local variable) const(ulong) generationgeneration) continue;
const (local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord = sparkles.base.expected.Expected!(SessionRecord, string, Abort) session_archive.readSessionGeneration(string directory, ulong generation) nothrow @safeValidate the complete immutable record and its identity before returning recovered contents.
Examples
A newer generation and a refused duplicate leave earlier dirty contents recoverable.
version (Posix) {}
else
{
import sparkles.test_runner.skip : skipTest;
skipTest("The native POSIX archive adapter is not available.");
}
import sparkles.test_utils.tmpfs : TmpFS;
import std.file : readText;
auto fixture = TmpFS.create();
const source = fixture.writeFile("disk");
SessionRecord record;
record.generation = 1;
record.active = 7;
record.tabs = [SessionTab(id: 7, path: source, name: "draft", content: "dirty\r\n",
savedContent: "disk", selections: [SessionSelection(0, 0)])];
const first = appendSessionGeneration(fixture.dir, record);
assert(first.hasValue && first.value.durable);
record.generation = 2;
record.tabs[0].content = "newer\r\n";
const second = appendSessionGeneration(fixture.dir, record);
assert(second.hasValue && second.value.durable);
record.generation = 1;
assert(appendSessionGeneration(fixture.dir, record).hasError);
const old = readSessionGeneration(fixture.dir, 1);
const latest = readSessionGeneration(fixture.dir, 2);
assert(old.hasValue && old.value.tabs[0].content == "dirty\r\n");
assert(latest.hasValue && latest.value.tabs[0].content == "newer\r\n");
assert((() @trusted => readText(source))() == "disk");
Retention preserves damaged and future generations while bounding older valid files.
version (linux) {}
else
{
import sparkles.test_runner.skip : skipTest;
skipTest("The native recovery archive currently requires Linux.");
}
import sparkles.recovery.directory : SessionDirectory = LeasedDirectory;
import sparkles.test_utils.tmpfs : TmpFS;
import std.conv : text;
import std.file : write;
auto fixture = TmpFS.create();
auto directory = SessionDirectory.create(buildPath(fixture.dir, "archives"), fixture.dir);
assert(directory.hasValue);
scope (exit) directory.value.close();
SessionRecord record;
record.active = 7;
record.tabs = [SessionTab(id: 7, name: "draft", selections: [SessionSelection(0, 0)])];
foreach (generation; 1UL .. 6UL)
{
record.generation = generation;
record.tabs[0].content = text(generation);
assert(appendSessionGeneration(directory.value.path, record).hasValue);
}
(() @trusted { write(buildPath(directory.value.path, "00000000000000000002.session"), "damaged"); })();
const report = pruneSessionArchive(directory.value, 4);
assert(report.removed.length == 1 && report.removed[0] == 1 && report.issues.length == 1);
assert(readSessionGeneration(directory.value.path, 1).hasError);
assert(readSessionGeneration(directory.value.path, 3).hasValue);
assert(readSessionGeneration(directory.value.path, 4).hasValue);
assert(readSessionGeneration(directory.value.path, 5).hasValue);
import std.file : readText;
assert((() @trusted => readText(buildPath(directory.value.path, "00000000000000000002.session")))() == "damaged");
readSessionGeneration((local variable) std.file.DirEntry archivearchive.string std.file.DirEntry.name() const pure nothrow @property return scope @safename, (local variable) const(ulong) generationgeneration);
if ((local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord.bool sparkles.base.expected.Expected!(session_record.SessionRecord, string, sparkles.base.expected.Abort).hasValue!()() const pure nothrow @nogc @property @safeChecks if Expected has value
hasValue && (local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord.inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabstabs.(field) ulong const(session_record.SessionTab[]).lengthlength == 2
&& (local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord.inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabstabs[0].(field) string session_record.SessionTab.contentcontent == ((local variable) const(bool) withdrawnwithdrawn ? "" : "from A")
&& (local variable) const(sparkles.base.expected.Expected!(SessionRecord, string, Abort)) recordrecord.inout(session_record.SessionRecord) sparkles.base.expected.Expected!(session_record.SessionRecord, 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) session_record.SessionTab[] session_record.SessionRecord.tabstabs[1].(field) string session_record.SessionTab.contentcontent == ((local variable) const(bool) withdrawnwithdrawn ? "xfrom B" : "from B")) (local variable) bool pairedpaired = true;
}
}
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(10.msecs);
}
assert((local variable) bool pairedpaired, "Out-of-order native clipboard replies did not retain their requesting tabs.");
void editor_native_close_probe.main.closeWindow() pure nothrow @nogc @systemcloseWindow();
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs);
if (!(local variable) const(bool) withdrawnwithdrawn) void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(40);
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(40);
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (!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.Pid childchild).terminated && (field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
deadline) (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(10.msecs);
assert(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.Pid childchild).terminated && (field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0tryWait((local variable) std.process.Pid childchild).status == 0, (field) int std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_1readText((local variable) std.stdio.File loglog.string std.stdio.File.name() const pure nothrow @property return @safeReturns the name last used to initialize this File, if any.
Some functions that create or initialize the File set the name field to null.
Examples include tmpfile, wrapFile, and fdopen. See the
documentation of those functions for details.
name));
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) const(bool) withdrawnwithdrawn ? "withdrawn X11 clipboard replies did not reach a replacement transfer"
: "out-of-order native X11 clipboard replies retained their requesting tabs");
return 0;
}
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(38); // Xvfb's default XKB map: a.
void editor_native_close_probe.main.awaitDraft(string expected) @systemawaitDraft("a");
void std.process.kill(std.process.Pid pid, int codeOrSignal)kill((local variable) std.process.Pid childchild, (constant) int core.sys.posix.signal.SIGKILL = 9SIGKILL); // Only the process owned by this probe.
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.Pid childchild);
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs);
(local variable) std.process.Pid childchild = std.process.Pid std.process.spawnProcess(scope const(char[])[] args, std.stdio.File stdin = makeGlobal(), std.stdio.File stdout = makeGlobal(), std.stdio.File stderr = makeGlobal(), const(string[string]) env = cast(const(string[string]))null, std.process.Config config = Config(Flags.none, null, null), scope const(char[]) workDir = null) @safeSpawns 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. It is recommended to always call wait
on the returned Pid unless the process was spawned with
Config.detached flag, as detailed in the documentation for wait.
Command line
There are four overloads of this function. The first two take an array
of strings, args, which should contain the program name as the
zeroth element and any command-line arguments in subsequent elements.
The third and fourth versions are included for convenience, and may be
used when there are no command-line arguments. They take a single string,
program, which specifies the program name.
Unless a directory is specified in args`[0]` or `program`,
spawnProcess`` will search for the program in a platform-dependent
manner. On POSIX systems, it will look for the executable in the
directories listed in the PATH environment variable, in the order
they are listed. On Windows, it will search for the executable in
the following sequence:
The directory from which the application loaded.
The current directory for the parent process.
The 32-bit Windows system directory.
The 16-bit Windows system directory.
The Windows directory.
The directories listed in the PATH environment variable.
// Run an executable called "prog" located in the current working
// directory:
auto pid = spawnProcess("./prog");
scope(exit) wait(pid);
// We can do something else while the program runs. The scope guard
// ensures that the process is waited for at the end of the scope.
...
// Run DMD on the file "myprog.d", specifying a few compiler switches:
auto dmdPid = spawnProcess(["dmd", "-O", "-release", "-inline", "myprog.d" ]);
if (wait(dmdPid) != 0)
writeln("Compilation failed!");
Environment variables
By default, the child process inherits the environment of the parent
process, along with any additional variables specified in the env
parameter. If the same variable exists in both the parent's environment
and in env, the latter takes precedence.
If the Config.newEnv flag is set in config, the child
process will not inherit the parent's environment. Its entire
environment will then be determined by env.
wait(spawnProcess("myapp", ["foo" : "bar"], Config.newEnv));
Standard streams
The optional arguments stdin, stdout and stderr may
be used to assign arbitrary File objects as the standard
input, output and error streams, respectively, of the child process. The
former must be opened for reading, while the latter two must be opened for
writing. The default is for the child process to inherit the standard
streams of its parent.
// Run DMD on the file myprog.d, logging any error messages to a
// file named errors.log.
auto logFile = File("errors.log", "w");
auto pid = spawnProcess(["dmd", "myprog.d"],
std.stdio.stdin,
std.stdio.stdout,
logFile);
if (wait(pid) != 0)
writeln("Compilation failed. See errors.log for details.");
Note that if you pass a File object that is not
one of the standard input/output/error streams of the parent process,
that stream will by default be closed in the parent process when
this function returns. See the Config documentation below for
information about how to disable this behaviour.
Beware of buffering issues when passing File objects to
spawnProcess. The child process will inherit the low-level raw
read/write offset associated with the underlying file descriptor, but
it will not be aware of any buffered data. In cases where this matters
(e.g. when a file should be aligned before being passed on to the
child process), it may be a good idea to use unbuffered streams, or at
least ensure all relevant buffers are flushed.
spawnProcess([(local variable) const(string) editoreditor,
"--gui", "--window-system", "x11", "--state-dir", (local variable) const(string) statestate], stdin, std.stdio.File std.stdio.makeGlobal!"core.stdc.stdio.stdin"() nothrow @nogc @property ref @systemlog, (local variable) std.stdio.File loglog,
null, (struct) std.process.ConfigOptions that control the behaviour of process creation functions in this
module. Most options only apply to spawnProcess and
spawnShell.
Example
auto logFile = File("myapp_error.log", "w");
// Start program, suppressing the console window (Windows only),
// redirect its error stream to logFile, and leave logFile open
// in the parent process as well.
auto pid = spawnProcess("myapp", stdin, stdout, logFile,
Config.retainStderr | Config.suppressConsole);
scope(exit)
{
auto exitCode = wait(pid);
logFile.writeln("myapp exited with code ", exitCode);
logFile.close();
}
Config.(constant) std.process.Config std.process.Config.retainStdout = Config(Flags.retainStdout, null, null)For backwards compatibility, and cases when only flags need to
be specified in the Config, these allow building Config
instances using flag names only.
retainStdout | std.process.Config std.process.Config.opBinary!"|"(std.process.Config other) pure nothrow @nogc @safeFor backwards compatibility, and cases when only flags need to
be specified in the Config, these allow building Config
instances using flag names only.
Config.(constant) std.process.Config std.process.Config.retainStderr = Config(Flags.retainStderr, null, null)For backwards compatibility, and cases when only flags need to
be specified in the Config, these allow building Config
instances using flag names only.
retainStderr);
void editor_native_close_probe.main.findWindow() nothrow @systemfindWindow();
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(70); // F4, R: the shared Restore command.
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(27);
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(36); // Enter accepts the offer.
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(100.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(56); // b continues editing at the restored caret.
void editor_native_close_probe.main.awaitDraft(string expected) @systemawaitDraft("ab");
void editor_native_close_probe.main.closeWindow() pure nothrow @nogc @systemcloseWindow();
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(250.msecs);
assert(!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.Pid childchild).terminated, "Native close discarded dirty text.");
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(9); // Escape cancels the close decision.
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(150.msecs);
assert(!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.Pid childchild).terminated);
void editor_native_close_probe.main.closeWindow() pure nothrow @nogc @systemcloseWindow();
(class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(250.msecs);
void editor_native_close_probe.main.key(ubyte code, ushort modifiers = cast(ushort)0u) pure nothrow @nogc @systemkey(40); // d explicitly discards the dirty document.
const (local variable) const(core.time.MonoTimeImpl!(ClockType.normal)) deadlinedeadline = (struct) core.time.MonoTimeImpl!(ClockType.normal)MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime + 5.seconds;
while (!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.Pid childchild).terminated && (field) bool std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_0MonoTime.core.time.MonoTimeImpl!(ClockType.normal) core.time.MonoTimeImpl!(ClockType.normal).currTime() nothrow @nogc @property @trustedThe current time of the system's monotonic clock. This has no relation
to the wall clock time, as the wall clock time can be adjusted (e.g.
by NTP), whereas the monotonic clock always moves forward. The source
of the monotonic time is system-specific.
On Windows, QueryPerformanceCounter is used. On Mac OS X,
mach_absolute_time is used, while on other POSIX systems,
clock_gettime is used.
Warning: On some systems, the monotonic clock may stop counting
when the computer goes to sleep or hibernates. So, the
monotonic clock may indicate less time than has actually
passed if that occurs. This is known to happen on
Mac OS X. It has not been tested whether it occurs on
either Windows or Linux.
currTime < int core.time.MonoTimeImpl!(ClockType.normal).opCmp(core.time.MonoTimeImpl!(ClockType.normal) rhs) const pure nothrow @nogc @safeCompares this MonoTime with the given MonoTime.
deadline) (class) core.thread.osthread.ThreadThis class encapsulates all threading functionality for the D
programming language. As thread manipulation is a required facility
for garbage collection, all user threads should derive from this
class, and instances of this class should never be explicitly deleted.
A new thread may be created using either derivation or composition, as
in the following example.
Thread.void core.thread.osthread.Thread.sleep(core.time.Duration val) nothrow @nogc @trustedSuspends the calling thread for at least the supplied period. This may
result in multiple OS calls if period is greater than the maximum sleep
duration supported by the operating system.
In
period must be non-negative.
Example
Thread.sleep( dur!("msecs")( 50 ) ); // sleep for 50 milliseconds
Thread.sleep( dur!("seconds")( 5 ) ); // sleep for 5 seconds
sleep(20.msecs);
assert(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.Pid childchild).terminated, "Discard did not approve native close.");
assert(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.Pid childchild).status == 0, (field) int std.typecons.Tuple!(bool, "terminated", int, "status").__expand_field_1readText((local variable) std.stdio.File loglog.string std.stdio.File.name() const pure nothrow @property return @safeReturns the name last used to initialize this File, if any.
Some functions that create or initialize the File set the name field to null.
Examples include tmpfile, wrapFile, and fdopen. See the
documentation of those functions for details.
name));
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("native draft survived SIGKILL; Restore and editing produced ab; dirty close deferred; Escape retained the document; explicit Discard flushed and exited");
return 0;
}