Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.process

Functions for starting and interacting with other processes, and forworking 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 aroundspawnProcess.
  • 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 thespawnProcess documentation for examples.tryWait is similar towait, 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'spopen 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 andexecuteShell work likespawnProcess,pipeProcess andexecute, 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'ssystem function.
  • kill attempts to terminate a running process.
The following table compactly summarises the different process creationfunctions and how they relate to each other:
Runs program directlyRuns shell command
Low-level process creationspawnProcessspawnShell
Automatic input/output redirection using pipespipeProcesspipeShell
Execute and wait for completion, collect outputexecuteexecuteShell

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 andescapeShellFileName are useful for constructing shell command lines in a portable way.

Authors:
Lars Tandle Kyllingstad,Steven Schveighoffer,Vladimir Panteleev
License:
Boost License 1.0.

Sourcestd/process.d

NoteMost of the functionality in this module is not available on iOS, tvOSand watchOS. The only functions available on those platforms are:environment,thisProcessID andthisThreadID.

abstract classenvironment;
Manipulates environment variables using an associative-array-likeinterface.
This class contains only static methods, and cannot be instantiated.See below for examples of use.
static @safe stringopIndex(scope const(char)[]name);
Retrieves the value of the environment variable with the givenname.
auto path = environment["PATH"];
Throws:
Exception if the environment variable does not exist, orstd.utf.UTFException if the variable contains invalid UTF-16 characters (Windows only).
See Also:
environment.get, which doesn't throw on failure.
static @safe stringget(scope const(char)[]name, stringdefaultValue = null);
Retrieves the value of the environment variable with the givenname, or a default value if the variable doesn't exist.
Unlikeenvironment.opIndex, this function never throws on Posix.
auto sh = environment.get("SHELL","/bin/sh");
This function is also useful in checking for the existence of an environment variable.
auto myVar = environment.get("MYVAR");if (myVarisnull){// Environment variable doesn't exist.// Note that we have to use 'is' for the comparison, since// myVar == null is also true if the variable exists but is// empty.}
Parameters:
const(char)[]namename of the environment variable to retrieve
stringdefaultValuedefault value to return if the environment variable doesn't exist.
Returns:
the value of the environment variable if found, otherwisenull if the environment doesn't exist.
Throws:
std.utf.UTFException if the variable contains invalid UTF-16 characters (Windows only).
static @trusted inout(char)[]opIndexAssign(return scope inout char[]value, scope const(char)[]name);
Assigns the givenvalue to the environment variable with the givenname. Ifvalue is null the variable is removed from environment.
If the variable does not exist, it will be created. If it already exists, it will be overwritten.
environment["foo"] ="bar";
Throws:
Exception if the environment variable could not be added (e.g. if the name is invalid).

NoteOn some platforms, modifying environment variables may not be allowed in multi-threaded programs. See e.g.glibc.

static nothrow @nogc @trusted voidremove(scope const(char)[]name);
Removes the environment variable with the givenname.
If the variable isn't in the environment, this function returns successfully without doing anything.

NoteOn some platforms, modifying environment variables may not be allowed in multi-threaded programs. See e.g.glibc.

@trusted boolopBinaryRight(string op : "in")(scope const(char)[]name);
Identify whether a variable is defined in the environment.
Because it doesn't return the value, this function is cheaper thanget. However, if you do need the value as well, you should just check the return ofget fornull instead of using this function first.

Example

// good usageif ("MY_ENV_FLAG"in environment)    doSomething();// bad usageif ("MY_ENV_VAR"in environment)    doSomething(environment["MY_ENV_VAR"]);// do this insteadif (auto var = environment.get("MY_ENV_VAR"))    doSomething(var);

static @trusted string[string]toAA();
Copies all environment variables into an associative array.

Windows specificWhile Windows environment variable names are case insensitive, D's built-in associative arrays are not. This function will store all variable names in uppercase (e.g.PATH).

Throws:
Exception if the environment variables could not be retrieved (Windows only).
nothrow @nogc @property @trusted intthisProcessID();
Returns the process ID of the current process, which is guaranteed to be unique on the system.

Example

writefln("Current process ID: %d",thisProcessID);

nothrow @nogc @property @trusted ThreadIDthisThreadID();
Returns the process ID of the current thread, which is guaranteed to be unique within the current process.
Returns:
Acore.thread.ThreadID value for the calling thread.

Example

writefln("Current thread ID: %s",thisThreadID);

@safe PidspawnProcess(scope const(char[])[]args, Filestdin = std.stdio.stdin, Filestdout = std.stdio.stdout, Filestderr = std.stdio.stderr, const string[string]env = null, Configconfig = Config.none, scope const char[]workDir = null);

@trusted PidspawnProcess(scope const(char[])[]args, const string[string]env, Configconfig = Config.none, scope const(char)[]workDir = null);

@trusted PidspawnProcess(scope const(char)[]program, Filestdin = std.stdio.stdin, Filestdout = std.stdio.stdout, Filestderr = std.stdio.stderr, const string[string]env = null, Configconfig = Config.none, scope const(char)[]workDir = null);

@trusted PidspawnProcess(scope const(char)[]program, const string[string]env, Configconfig = Config.none, scope const(char)[]workDir = null);
Spawns a new process, optionally assigning it an arbitrary set of standardinput, output, and error streams.
The function returns immediately, leaving the child process to executein parallel with its parent. It is recommended to always callwaiton the returnedPid unless the process was spawned withConfig.detached flag, as detailed in the documentation forwait.

Command lineThere are four overloads of this function. The first two take an arrayof strings,args, which should contain the program name as thezeroth element and any command-line arguments in subsequent elements.The third and fourth versions are included for convenience, and may beused when there are no command-line arguments. They take a single string,program, which specifies the program name.

Unless a directory is specified inargs[0] orprogram,spawnProcess will search for the program in a platform-dependentmanner. On POSIX systems, it will look for the executable in thedirectories listed in the PATH environment variable, in the orderthey are listed. On Windows, it will search for the executable inthe following sequence:
  1. The directory from which the application loaded.
  2. The current directory for the parent process.
  3. The 32-bit Windows system directory.
  4. The 16-bit Windows system directory.
  5. The Windows directory.
  6. 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 variablesBy default, the child process inherits the environment of the parentprocess, along with any additional variables specified in theenvparameter. If the same variable exists in both the parent's environmentand inenv, the latter takes precedence.

If theConfig.newEnv flag is set inconfig, the childprocess willnot inherit the parent's environment. Its entireenvironment will then be determined byenv.
wait(spawnProcess("myapp", ["foo" :"bar"], Config.newEnv));

Standard streamsThe optional argumentsstdin,stdout andstderr maybe used to assign arbitrarystd.stdio.File objects as the standardinput, output and error streams, respectively, of the child process. Theformer must be opened for reading, while the latter two must be opened forwriting. The default is for the child process to inherit the standardstreams 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 aFile object that isnotone of the standard input/output/error streams of the parent process,that stream will by default beclosed in the parent process whenthis function returns. See theConfig documentation below forinformation about how to disable this behaviour.
Beware of buffering issues when passingFile objects tospawnProcess. The child process will inherit the low-level rawread/write offset associated with the underlying file descriptor, butit 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 thechild process), it may be a good idea to use unbuffered streams, or atleast ensure all relevant buffers are flushed.

Parameters:
const(char[])[]argsAn array which contains the program name as the zeroth element and any command-line arguments in the following elements.
FilestdinThe standard input stream of the child process. This can be anystd.stdio.File that is opened for reading. By default the child process inherits the parent's input stream.
FilestdoutThe standard output stream of the child process. This can be anystd.stdio.File that is opened for writing. By default the child process inherits the parent's output stream.
FilestderrThe standard error stream of the child process. This can be anystd.stdio.File that is opened for writing. By default the child process inherits the parent's error stream.
string[string]envAdditional environment variables for the child process.
ConfigconfigFlags that control process creation. SeeConfig for an overview of available flags.
char[]workDirThe working directory for the new process. By default the child process inherits the parent's working directory.
Returns:
APid object that corresponds to the spawned process.
Throws:
ProcessException on failure to start the process.
std.stdio.StdioException on failure to pass one of the streams to the child process (Windows only).
core.exception.RangeError ifargs is empty.
@trusted PidspawnShell(scope const(char)[]command, Filestdin = std.stdio.stdin, Filestdout = std.stdio.stdout, Filestderr = std.stdio.stderr, scope const string[string]env = null, Configconfig = Config.none, scope const(char)[]workDir = null, scope stringshellPath = nativeShell);

@trusted PidspawnShell(scope const(char)[]command, scope const string[string]env, Configconfig = Config.none, scope const(char)[]workDir = null, scope stringshellPath = nativeShell);
A variation onspawnProcess that runs the given command throughthe current user's preferred command interpreter (aka. shell).
The stringcommand is passed verbatim to the shell, and is thereforesubject to its rules about command structure, argument/filename quotingand escaping of special characters.The path to the shell executable defaults tonativeShell.
In all other respects this function works just likespawnProcess.Please refer to thespawnProcess documentation for descriptionsof the other function parameters, the return value and any exceptionsthat may be thrown.
// Run the command/program "foo" on the file named "my file.txt", and// redirect its output into foo.log.auto pid =spawnShell(`foo "my file.txt" > foo.log`);wait(pid);
See Also:
escapeShellCommand, which may be helpful in constructing aproperly quoted and escaped shell command line for the current platform.
structConfig;
Options that control the behaviour of process creation functions in thismodule. Most options only apply tospawnProcess andspawnShell.

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();}

enumFlags: int;

Flagsflags;
Flag options. Use bitwise OR to combine flags.
newEnv
By default, the child process inherits the parent's environment, and any environment variables passed tospawnProcess will be added to it. If this flag is set, the only variables in the child process' environment will be those given to spawnProcess.
retainStdin

retainStdout

retainStderr
Unless the child process inherits the standard input/output/error streams of its parent, one almost always wants the streams closed in the parent whenspawnProcess returns. Therefore, by default, this is done. If this is not desirable, pass any of these options to spawnProcess.
suppressConsole
On Windows, if the child process is a console application, this flag will prevent the creation of a console window. Otherwise, it will be ignored. On POSIX,suppressConsole has no effect.
inheritFDs
On POSIX, openfile descriptors are by default inherited by the child process. As this may lead to subtle bugs when pipes or multiple threads are involved,spawnProcess ensures that all file descriptors except the ones that correspond to standard input/output/error are closed in the child process when it starts. UseinheritFDs to prevent this.
On Windows, this option has no effect, and any handles which have been explicitly marked as inheritable will always be inherited by the child process.
detached
Spawn process in detached state. This removes the need in callingwait to clean up the process resources.

NoteCallingwait orkill with the resultingPid is invalid.

stderrPassThrough
By default, theexecute andexecuteShell functions will capture child processes' both stdout and stderr. This can be undesirable if the standard output is to be processed or otherwise used by the invoking program, asexecute's result would then contain a mix of output and warning/error messages.
Specify this flag when callingexecute orexecuteShell to cause invoked processes' stderr stream to be sent to std.stdio.stderr, and only capture and return standard output.
This flag has no effect onspawnProcess orspawnShell.
enum Confignone;

enum ConfignewEnv;

enum ConfigretainStdin;

enum ConfigretainStdout;

enum ConfigretainStderr;

enum ConfigsuppressConsole;

enum ConfiginheritFDs;

enum Configdetached;

enum ConfigstderrPassThrough;

ConfigopUnary(string op)()
if (is(typeof(mixin(op ~ "flags"))));

ConfigopBinary(string op)(Configother)
if (is(typeof(mixin("flags" ~ op ~ "other.flags"))));

ConfigopOpAssign(string op)(Configother)
if (is(typeof(mixin("flags" ~ op ~ "=other.flags"))));
For backwards compatibility, and cases when only flags need to be specified in theConfig, these allow buildingConfig instances using flag names only.
bool function() nothrow @nogc @safepreExecFunction;
A function that is called beforeexec inspawnProcess. It returnstrue if succeeded and otherwise returnsfalse.
Warning: Please note that the code in this function must only use async-signal-safe functions.
IfpreExecDelegate is also set, it is called last.
On Windows, this member is not available.
bool delegate() nothrow @nogc @safepreExecDelegate;
A delegate that is called beforeexec inspawnProcess. It returnstrue if succeeded and otherwise returnsfalse.
Warning: Please note that the code in this function must only use async-signal-safe functions.
IfpreExecFunction is also set, it is called first.
On Windows, this member is not available.
classPid;
A handle that corresponds to a spawned process.
pure nothrow @property @safe intprocessID() const;
The process ID number.
This is a number that uniquely identifies the process on the operating system, for at least as long as the process is running. Oncewait has been called on thePid, this method will return an invalid (negative) process ID.
pure nothrow @nogc @property @safe pid_tosHandle();
An operating system handle to the process.
This handle is used to specify the process in OS-specific APIs. On POSIX, this function returns acore.sys.posix.sys.types.pid_t with the same value asPid.processID, while on Windows it returns acore.sys.windows.windows.HANDLE.
Oncewait has been called on thePid, this method will return an invalid handle.
@safe intwait(Pidpid);
Waits for the process associated withpid to terminate, and returnsits exit status.
In general one should always wait for child processes to terminatebefore exiting the parent process unless the process was spawned as detached(that was spawned withConfig.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 onthe samePid it will always return the same value.

POSIX specificIf the process is terminated by a signal, this function returns anegative number whose absolute value is the signal number.Since POSIX restricts normal exit codes to the range 0-255, anegative return value will always indicate termination by signal.Signal codes are defined in thecore.sys.posix.signal module(which corresponds to thesignal.h POSIX header).

Throws:
ProcessException on failure or on attempt to wait for detached process.

ExampleSee thespawnProcess documentation.

See Also:
tryWait, for a non-blocking function.
@safe Tuple!(bool, "terminated", int, "status")waitTimeout(Pidpid, Durationtimeout);
Waits until either the process associated withpid terminates or theelapsed time exceeds the given timeout.
If the process terminates within the given duration it behaves exactly likewait, except that it returns a tuple(true, exit code).
If the process does not terminate within the given duration it will stopwaiting and return(false, 0).
The timeout may not exceed(uint.max - 1).msecs (~ 7 weeks, 17 hours).
This function is Windows-Only.
Returns:
Anstd.typecons.Tuple!(bool, "terminated", int, "status").
Throws:
ProcessException on failure or on attempt to wait for detached process.

ExampleSee thespawnProcess documentation.

See Also:
wait, for a blocking function without timeout.tryWait, for a non-blocking function without timeout.
@safe autotryWait(Pidpid);
A non-blocking version ofwait.
If the process associated withpid has already terminated,tryWait has the exact same effect aswait.In this case, it returns a tuple where theterminated fieldis set totrue and thestatus field has the sameinterpretation as the return value ofwait.
If the process hasnot yet terminated, this function differsfromwait in that does not wait for this to happen, but insteadreturns immediately. Theterminated field of the returnedtuple will then be set tofalse, while thestatus fieldwill always be 0 (zero).wait ortryWait should then becalled again on the samePid at some later time; not only toget the exit code, but also to avoid the process becoming a "zombie"when it finally terminates. (Seewait for details).
Returns:
Anstd.typecons.Tuple!(bool, "terminated", int, "status").
Throws:
ProcessException on failure or on attempt to wait for detached process.

Example

autopid = 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 firstwait call will have noeffect if the process has already terminated by the timetryWaitis called. In the opposite case, however, thescope statementensures that we always wait for the process if it hasn't terminatedby the time we reach the end of the scope.

voidkill(Pidpid);

voidkill(Pidpid, intcodeOrSignal);
Attempts to terminate the process associated withpid.
The effect of this function, as well as the meaning ofcodeOrSignal,is highly platform dependent. Details are given below. Common to allplatforms is that this function onlyinitiates 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 callwait to wait for a process to complete, even ifkillhas been called on it.

Windows specificThe process will beforcefully and abruptly terminated. IfcodeOrSignal is specified, itmust 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 usecodeOrSignal = 259,as this is a special value (aka.STILL_ACTIVE)used by Windows to signal that a process has in factnot terminated yet.

autopid = spawnProcess("some_app");kill(pid, 10);assert(wait(pid) == 10);

POSIX specificAsignal will be sent tothe process, whose value is given bycodeOrSignal. Depending on thesignal sent, this may or may not terminate the process. Symbolic constantsfor variousPOSIX signals are defined incore.sys.posix.signal, which corresponds to thesignal.h POSIX header. IfcodeOrSignal is omitted, theSIGTERM signal will be sent. (This matches the behaviour of the_kill shell command.)

import core.sys.posix.signal : SIGKILL;autopid = spawnProcess("some_app");kill(pid, SIGKILL);assert(wait(pid) == -SIGKILL);// Negative return value on POSIX!

Throws:
ProcessException on error (e.g. if codeOrSignal is invalid). or on attempt to kill detached process. Note that failure to terminate the process is considered a "normal" outcome, not an error.
@trusted Pipepipe();
Creates a unidirectional pipe.
Data is written to one end of the pipe and read from the other.
auto p =pipe();p.writeEnd.writeln("Hello World");p.writeEnd.flush();assert(p.readEnd.readln().chomp() =="Hello World");
Pipes can, for example, be used for interprocess communicationby spawning a new process and passing one end of the pipe tothe child, while the parent uses the other end.(See alsopipeProcess andpipeShell for an easierway of doing this.)
// Use cURL to download the dlang.org front page, pipe its// output to grep to extract a list of links to ZIP files,// and write the list to the file "D downloads.txt":auto p =pipe();auto outFile = File("D downloads.txt","w");auto cpid = spawnProcess(["curl","http://dlang.org/download.html"],                         std.stdio.stdin, p.writeEnd);scope(exit) wait(cpid);auto gpid = spawnProcess(["grep","-o",`http://\S*\.zip`],                         p.readEnd, outFile);scope(exit) wait(gpid);
Returns:
APipe object that corresponds to the created pipe.
Throws:
structPipe;
An interface to a pipe created by thepipe function.
nothrow @property @safe FilereadEnd();
The read end of the pipe.
nothrow @property @safe FilewriteEnd();
The write end of the pipe.
@safe voidclose();
Closes both ends of the pipe.
Normally it is not necessary to do this manually, asstd.stdio.File objects are automatically closed when there are no more references to them.
Note that if either end of the pipe has been passed to a child process, it will only be closed in the parent process. (What happens in the child process is platform dependent.)
Throws:
std.exception.ErrnoException if an error occurs.
@safe ProcessPipespipeProcess(scope const(char[])[]args, Redirectredirect = Redirect.all, const string[string]env = null, Configconfig = Config.none, scope const(char)[]workDir = null);

@safe ProcessPipespipeProcess(scope const(char)[]program, Redirectredirect = Redirect.all, const string[string]env = null, Configconfig = Config.none, scope const(char)[]workDir = null);

@safe ProcessPipespipeShell(scope const(char)[]command, Redirectredirect = Redirect.all, const string[string]env = null, Configconfig = Config.none, scope const(char)[]workDir = null, stringshellPath = nativeShell);
Starts a new process, creating pipes to redirect its standardinput, output and/or error streams.
pipeProcess andpipeShell are convenient wrappers aroundspawnProcess andspawnShell, respectively, andautomate the task of redirecting one or more of the child process'standard streams through pipes. Like the functions they wrap,these functions return immediately, leaving the child process toexecute in parallel with the invoking process. It is recommendedto always callwait on the returnedProcessPipes.pid,as detailed in the documentation forwait.
Theargs/program/command,env andconfigparameters are forwarded straight to the underlying spawn functions,and we refer to their documentation for details.
Parameters:
const(char[])[]argsAn array which contains the program name as the zeroth element and any command-line arguments in the following elements. (SeespawnProcess for details.)
const(char)[]programThe program name,without command-line arguments. (SeespawnProcess for details.)
const(char)[]commandA shell command which is passed verbatim to the command interpreter. (SeespawnShell for details.)
RedirectredirectFlags that determine which streams are redirected, and how. SeeRedirect for an overview of available flags.
string[string]envAdditional environment variables for the child process. (SeespawnProcess for details.)
ConfigconfigFlags that control process creation. SeeConfig for an overview of available flags, and note that theretainStd... flags have no effect in this function.
const(char)[]workDirThe working directory for the new process. By default the child process inherits the parent's working directory.
stringshellPathThe path to the shell to use to run the specified program. By default this isnativeShell.
Returns:
AProcessPipes object which containsstd.stdio.Filehandles that communicate with the redirected streams of the childprocess, along with aPid object that corresponds to thespawned process.
Throws:
ProcessException on failure to start the process.
std.stdio.StdioException on failure to redirect any of the streams.

Example

// my_application writes to stdout and might write to stderrauto pipes =pipeProcess("my_application", Redirect.stdout | Redirect.stderr);scope(exit) wait(pipes.pid);// Store lines of output.string[] output;foreach (line; pipes.stdout.byLine) output ~= line.idup;// Store lines of errors.string[] errors;foreach (line; pipes.stderr.byLine) errors ~= line.idup;// sendmail expects to read from stdinpipes =pipeProcess(["/usr/bin/sendmail","-t"], Redirect.stdin);pipes.stdin.writeln("To: you");pipes.stdin.writeln("From: me");pipes.stdin.writeln("Subject: dlang");pipes.stdin.writeln("");pipes.stdin.writeln(message);// a single period tells sendmail we are finishedpipes.stdin.writeln(".");// but at this point sendmail might not see it, we need to flushpipes.stdin.flush();// sendmail happens to exit on ".", but some you have to close the file:pipes.stdin.close();// otherwise this wait will wait foreverwait(pipes.pid);

enumRedirect: int;
Flags that can be passed topipeProcess andpipeShellto specify which of the child process' standard streams are redirected.Use bitwise OR to combine flags.
stdin

stdout

stderr
Redirect the standard input, output or error streams, respectively.
all
Redirect all three streams. This is equivalent toRedirect.stdin | Redirect.stdout | Redirect.stderr.
stderrToStdout
Redirect the standard error stream into the standard output stream. This can not be combined withRedirect.stderr.
stdoutToStderr
Redirect the standard output stream into the standard error stream. This can not be combined withRedirect.stdout.
structProcessPipes;
Object which containsstd.stdio.File handles that allow communicationwith a child process through its standard streams.
nothrow @property @safe Pidpid();
ThePid of the child process.
nothrow @property @safe Filestdin();
Anstd.stdio.File that allows writing to the child process' standard input stream.
Throws:
Error if the child process' standard input stream hasn't been redirected.
nothrow @property @safe Filestdout();
Anstd.stdio.File that allows reading from the child process' standard output stream.
Throws:
Error if the child process' standard output stream hasn't been redirected.
nothrow @property @safe Filestderr();
Anstd.stdio.File that allows reading from the child process' standard error stream.
Throws:
Error if the child process' standard error stream hasn't been redirected.
@safe autoexecute(scope const(char[])[]args, const string[string]env = null, Configconfig = Config.none, size_tmaxOutput = size_t.max, scope const(char)[]workDir = null);

@safe autoexecute(scope const(char)[]program, const string[string]env = null, Configconfig = Config.none, size_tmaxOutput = size_t.max, scope const(char)[]workDir = null);

@safe autoexecuteShell(scope const(char)[]command, const string[string]env = null, Configconfig = Config.none, size_tmaxOutput = size_t.max, scope const(char)[]workDir = null, stringshellPath = nativeShell);
Executes the given program or shell command and returns its exitcode and output.
execute andexecuteShell start a new process usingspawnProcess andspawnShell, respectively, and waitfor the process to complete before returning. The functions capturewhat the child process prints to both its standard output andstandard 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);
Theargs/program/command,env andconfigparameters are forwarded straight to the underlying spawn functions,and we refer to their documentation for details.
Parameters:
const(char[])[]argsAn array which contains the program name as the zeroth element and any command-line arguments in the following elements. (SeespawnProcess for details.)
const(char)[]programThe program name,without command-line arguments. (SeespawnProcess for details.)
const(char)[]commandA shell command which is passed verbatim to the command interpreter. (SeespawnShell for details.)
string[string]envAdditional environment variables for the child process. (SeespawnProcess for details.)
ConfigconfigFlags that control process creation. SeeConfig for an overview of available flags, and note that theretainStd... flags have no effect in this function.
size_tmaxOutputThe maximum number of bytes of output that should be captured.
const(char)[]workDirThe working directory for the new process. By default the child process inherits the parent's working directory.
stringshellPathThe path to the shell to use to run the specified program. By default this isnativeShell.
Returns:
Anstd.typecons.Tuple!(int, "status", string, "output").

POSIX specificIf the process is terminated by a signal, thestatus field ofthe return value will contain a negative number whose absolutevalue is the signal number. (Seewait for details.)

Throws:
ProcessException on failure to start the process.
std.stdio.StdioException on failure to capture output.
classProcessException:object.Exception;
An exception that signals a problem with starting or waiting for a process.
@property @safe stringuserShell();
Determines the path to the current user's preferred command interpreter.
On Windows, this function returns the contents of the COMSPEC environmentvariable, if it exists. Otherwise, it returns the result ofnativeShell.
On POSIX,userShell returns the contents of the SHELL environmentvariable, if it exists and is non-empty. Otherwise, it returns the result ofnativeShell.
pure nothrow @nogc @property @safe stringnativeShell();
The platform-specific native shell path.
This function returns"cmd.exe" on Windows,"/bin/sh" on POSIX, and"/system/bin/sh" on Android.
pure @safe stringescapeShellCommand(scope const(char[])[]args...);
Escapes an argv-style argument array to be used withspawnShell,pipeShell orexecuteShell.
string url ="http://dlang.org/";executeShell(escapeShellCommand("wget", url,"-O","dlang-index.html"));
Concatenate multipleescapeShellCommand andescapeShellFileName results to use shell redirection orpiping operators.
executeShell(escapeShellCommand("curl","http://dlang.org/download.html") ~"|" ~escapeShellCommand("grep","-o",`http://\S*\.zip`) ~">" ~    escapeShellFileName("D download links.txt"));
Throws:
Exception if any part of the command line contains unescapablecharacters (NUL on all platforms, as well as CR and LF on Windows).
pure nothrow @trusted stringescapeWindowsArgument(scope const(char)[]arg);
Quotes a command-line argument in a manner conforming to the behavior ofCommandLineToArgvW.
pure nothrow @trusted stringescapeShellFileName(scope const(char)[]fileName);
Escapes a filename to be used for shell redirection withspawnShell,pipeShell orexecuteShell.
intexecv(in stringpathname, in string[]argv);

intexecve(in stringpathname, in string[]argv, in string[]envp);

intexecvp(in stringpathname, in string[]argv);

intexecvpe(in stringpathname, in string[]argv, in string[]envp);
Replaces the current process by executing a command,pathname, with the arguments inargv.
This function is Posix-Only.
Typically, the first element ofargv is the command being executed, i.e.argv[0] == pathname. The 'p' versions ofexec search the PATH environment variable for pathname. The 'e' versions additionally take the new process' environment variables as an array of strings of the form key=value.
Does not return on success (the current process will have been replaced). Returns -1 on failure with no indication of the underlying error.

Windows specific These functions are only supported on POSIX platforms, as the Windows operating systems do not provide the ability to overwrite the current process image with another. In single-threaded programs it is possible to approximate the effect ofexecv* by usingspawnProcess and terminating the current process once the child process has returned. For example:

auto commandLine = ["program","arg1","arg2" ];version (Posix){execv(commandLine[0], commandLine);thrownew Exception("Failed to execute program");}elseversion (Windows){import core.stdc.stdlib : _Exit;    _Exit(wait(spawnProcess(commandLine)));}
This is, however, NOT equivalent to POSIX'execv*. For one thing, the executed program is started as a separate process, with all this entails. Secondly, in a multithreaded program, other threads will continue to do work while the current thread is waiting for the child process to complete.
A better option may sometimes be to terminate the current program immediately after spawning the child process. This is the behaviour exhibited by the__exec functions in Microsoft's C runtime library, and it is how D's now-deprecated Windowsexecv* functions work. Example:
auto commandLine = ["program","arg1","arg2" ];version (Posix){execv(commandLine[0], commandLine);thrownew Exception("Failed to execute program");}elseversion (Windows){    spawnProcess(commandLine);import core.stdc.stdlib : _exit;    _exit(0);}

voidbrowse(scope const(char)[]url);
Start up the browser and set it to viewing the page at url.
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Fri Feb 20 17:58:47 2026

[8]ページ先頭

©2009-2026 Movatter.jp