Skip to content

Process abstract interface

abstract interface class Process

The means to execute a program.

Use the static start and run methods to start a new process. The run method executes the process non-interactively to completion. In contrast, the start method allows your code to interact with the running process.

Start a process with the run method

The following code sample uses the run method to create a process that runs the UNIX command ls, which lists the contents of a directory. The run method completes with a ProcessResult object when the process terminates. This provides access to the output and exit code from the process. The run method does not return a Process object; this prevents your code from interacting with the running process.

dart
import 'dart:io';

main() async {
  // List all files in the current directory in UNIX-like systems.
  var result = await Process.run('ls', ['-l']);
  print(result.stdout);
}

Start a process with the start method

The following example uses start to create the process. The start method returns a Future for a Process object. When the future completes the process is started and your code can interact with the process: writing to stdin, listening to stdout, and so on.

The following sample starts the UNIX cat utility, which when given no command-line arguments, echos its input. The program writes to the process's standard input stream and prints data from its standard output stream.

dart
import 'dart:io';
import 'dart:convert';

main() async {
  var process = await Process.start('cat', []);
  process.stdout
      .transform(utf8.decoder)
      .forEach(print);
  process.stdin.writeln('Hello, world!');
  process.stdin.writeln('Hello, galaxy!');
  process.stdin.writeln('Hello, universe!');
}

Standard I/O streams

As seen in the previous code sample, you can interact with the Process's standard output stream through the getter stdout, and you can interact with the Process's standard input stream through the getter stdin. In addition, Process provides a getter stderr for using the Process's standard error stream.

A Process's streams are distinct from the top-level streams for the current program.

NOTE:stdin, stdout, and stderr are implemented using pipes between the parent process and the spawned subprocess. These pipes have limited capacity. If the subprocess writes to stderr or stdout in excess of that limit without the output being read, the subprocess blocks waiting for the pipe buffer to accept more data. For example:

dart
import 'dart:io';

main() async {
  var process = await Process.start('cat', ['largefile.txt']);
  // The following await statement will never complete because the
  // subprocess never exits since it is blocked waiting for its
  // stdout to be read.
  await process.stderr.forEach(print);
}

Exit codes

Call the exitCode method to get the exit code of the process. The exit code indicates whether the program terminated successfully (usually indicated with an exit code of 0) or with an error.

If the start method is used, the exitCode is available through a future on the Process object (as shown in the example below). If the run method is used, the exitCode is available through a getter on the ProcessResult instance.

dart
import 'dart:io';

main() async {
  var process = await Process.start('ls', ['-l']);
  var exitCode = await process.exitCode;
  print('exit code: $exitCode');
}

Properties

exitCode no setter

Future<int> get exitCode

A Future which completes with the exit code of the process when the process completes.

The exit code is not available for processes running with ProcessStartMode.detached or ProcessStartMode.detachedWithStdio and the getter will throw StateError if it is used.

The handling of exit codes is platform specific.

On Linux and OS X a normal exit code will be a positive value in the range [0..255]. If the process was terminated due to a signal the exit code will be a negative value in the range [-255..-1], where the absolute value of the exit code is the signal number. For example, if a process crashes due to a segmentation violation the exit code will be -11, as the signal SIGSEGV has the number 11.

On Windows a process can report any 32-bit value as an exit code. When returning the exit code this exit code is turned into a signed value. Some special values are used to report termination due to some system event. E.g. if a process crashes due to an access violation the 32-bit exit code is 0xc0000005, which will be returned as the negative number -1073741819. To get the original 32-bit value use (0x100000000 + exitCode) & 0xffffffff.

There is no guarantee that stdout and stderr have finished reporting the buffered output of the process when the returned future completes. To be sure that all output is captured, wait for the done event on the streams.

Implementation
dart
Future<int> get exitCode;

hashCode no setter inherited

int get hashCode

The hash code for this object.

A hash code is a single integer which represents the state of the object that affects operator == comparisons.

All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.

Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.

Inherited from Object.

Implementation
dart
external int get hashCode;

pid no setter

int get pid

The process id of the process.

Implementation
dart
int get pid;

runtimeType no setter inherited

Type get runtimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

stderr no setter

Stream<List<int>> get stderr

The standard error stream of the process as a Stream.

NOTE:stdin, stdout, and stderr are implemented using pipes between the parent process and the spawned subprocess. These pipes have limited capacity. If the subprocess writes to stderr or stdout in excess of that limit without the output being read, the subprocess blocks waiting for the pipe buffer to accept more data. For example:

dart
import 'dart:io';

main() async {
  var process = await Process.start('cat', ['largefile.txt']);
  // The following await statement will never complete because the
  // subprocess never exits since it is blocked waiting for its
  // stdout to be read.
  await process.stderr.forEach(print);
}
Implementation
dart
Stream<List<int>> get stderr;

stdin no setter

IOSink get stdin

The standard input stream of the process as an IOSink.

Implementation
dart
IOSink get stdin;

stdout no setter

Stream<List<int>> get stdout

The standard output stream of the process as a Stream.

NOTE:stdin, stdout, and stderr are implemented using pipes between the parent process and the spawned subprocess. These pipes have limited capacity. If the subprocess writes to stderr or stdout in excess of that limit without the output being read, the subprocess blocks waiting for the pipe buffer to accept more data. For example:

dart
import 'dart:io';

main() async {
  var process = await Process.start('cat', ['largefile.txt']);
  // The following await statement will never complete because the
  // subprocess never exits since it is blocked waiting for its
  // stdout to be read.
  await process.stderr.forEach(print);
}
Implementation
dart
Stream<List<int>> get stdout;

Methods

kill()

bool kill([ProcessSignal signal = ProcessSignal.sigterm])

Kills the process.

Where possible, sends the signal to the process. This includes Linux and OS X. The default signal is ProcessSignal.sigterm which will normally terminate the process.

On platforms without signal support, including Windows, the call just terminates the process in a platform specific way, and the signal parameter is ignored.

Returns true if the signal is successfully delivered to the process. Otherwise the signal could not be sent, usually meaning that the process is already dead.

Implementation
dart
bool kill([ProcessSignal signal = ProcessSignal.sigterm]);

noSuchMethod() inherited

dynamic noSuchMethod(Invocation invocation)

Invoked when a nonexistent method or property is accessed.

A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:

dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time error

This invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).

Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.

A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:

dart
class MockList<T> implements List<T> {
  noSuchMethod(Invocation invocation) {
    log(invocation);
    super.noSuchMethod(invocation); // Will throw.
  }
}
void main() {
  MockList().add(42);
}

This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.

If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.

The default behavior is to throw a NoSuchMethodError.

Inherited from Object.

Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);

toString() inherited

String toString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Inherited from Object.

Implementation
dart
external String toString();

Operators

operator ==() inherited

bool operator ==(Object other)

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

  • Total: It must return a boolean for all arguments. It should never throw.

  • Reflexive: For all objects o, o == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

Inherited from Object.

Implementation
dart
external bool operator ==(Object other);

Static Methods

killPid()

bool killPid(int pid, [ProcessSignal signal = ProcessSignal.sigterm])

Kills the process with id pid.

Where possible, sends the signal to the process with id pid. This includes Linux and OS X. The default signal is ProcessSignal.sigterm which will normally terminate the process.

On platforms without signal support, including Windows, the call just terminates the process with id pid in a platform specific way, and the signal parameter is ignored.

Returns true if the signal is successfully delivered to the process. Otherwise the signal could not be sent, usually meaning that the process is already dead.

Implementation
dart
external static bool killPid(
  int pid, [
  ProcessSignal signal = ProcessSignal.sigterm,
]);

run()

Future<ProcessResult> run(
  String executable,
  List<String> arguments, {
  String? workingDirectory,
  Map<String, String>? environment,
  bool includeParentEnvironment = true,
  bool runInShell = false,
  Encoding? stdoutEncoding = systemEncoding,
  Encoding? stderrEncoding = systemEncoding,
})

Starts a process and runs it non-interactively to completion. The process run is executable with the specified arguments.

Using an absolute path for executable is recommended since resolving the executable path is platform-specific. On Windows, both any PATH set in the environment map parameter and the path set in workingDirectory parameter are ignored for the purposes of resolving the executable path.

Use workingDirectory to set the working directory for the process. Note that the change of directory occurs before executing the process on some platforms, which may have impact when using relative paths for the executable and the arguments.

Use environment to set the environment variables for the process. If not set the environment of the parent process is inherited. Currently, only US-ASCII environment variables are supported and errors are likely to occur if an environment variable with code-points outside the US-ASCII range is passed in.

If includeParentEnvironment is true, the process's environment will include the parent process's environment, with environment taking precedence. Default is true.

If runInShell is true, the process will be spawned through a system shell. On Linux and OS X, /bin/sh is used, while %WINDIR%\system32\cmd.exe is used on Windows.

NOTE: On Windows, if executable is a batch file ('.bat' or '.cmd'), it may be launched by the operating system in a system shell regardless of the value of runInShell. This could result in arguments being parsed according to shell rules. For example:

dart
void main() async {
  // Will launch notepad.
  await Process.run('test.bat', ['test&notepad.exe']);
}

The encoding used for decoding stdout and stderr into text is controlled through stdoutEncoding and stderrEncoding. The default encoding is systemEncoding. If null is used no decoding will happen and the ProcessResult will hold binary data.

Returns a Future<ProcessResult> that completes with the result of running the process, i.e., exit code, standard out and standard error.

The following code uses Process.run to grep for main in the file test.dart on Linux.

dart
var result = await Process.run('grep', ['-i', 'main', 'test.dart']);
stdout.write(result.stdout);
stderr.write(result.stderr);
Implementation
dart
external static Future<ProcessResult> run(
  String executable,
  List<String> arguments, {
  String? workingDirectory,
  Map<String, String>? environment,
  bool includeParentEnvironment = true,
  bool runInShell = false,
  Encoding? stdoutEncoding = systemEncoding,
  Encoding? stderrEncoding = systemEncoding,
});

runSync()

ProcessResult runSync(
  String executable,
  List<String> arguments, {
  String? workingDirectory,
  Map<String, String>? environment,
  bool includeParentEnvironment = true,
  bool runInShell = false,
  Encoding? stdoutEncoding = systemEncoding,
  Encoding? stderrEncoding = systemEncoding,
})

Starts a process and runs it to completion. This is a synchronous call and will block until the child process terminates.

The arguments are the same as for Process.run.

Returns a ProcessResult with the result of running the process, i.e., exit code, standard out and standard error.

Implementation
dart
external static ProcessResult runSync(
  String executable,
  List<String> arguments, {
  String? workingDirectory,
  Map<String, String>? environment,
  bool includeParentEnvironment = true,
  bool runInShell = false,
  Encoding? stdoutEncoding = systemEncoding,
  Encoding? stderrEncoding = systemEncoding,
});

start()

Future<Process> start(
  String executable,
  List<String> arguments, {
  String? workingDirectory,
  Map<String, String>? environment,
  bool includeParentEnvironment = true,
  bool runInShell = false,
  ProcessStartMode mode = ProcessStartMode.normal,
})

Starts a process running the executable with the specified arguments.

Returns a Future<Process> that completes with a Process instance when the process has been successfully started. That Process object can be used to interact with the process. If the process cannot be started the returned Future completes with an exception.

Using an absolute path for executable is recommended since resolving the executable path is platform-specific. On Windows, both any PATH set in the environment map parameter and the path set in workingDirectory parameter are ignored for the purposes of resolving the executable path.

Use workingDirectory to set the working directory for the process. Note that the change of directory occurs before executing the process on some platforms, which may have impact when using relative paths for the executable and the arguments.

Use environment to set the environment variables for the process. If not set the environment of the parent process is inherited. Currently, only US-ASCII environment variables are supported and errors are likely to occur if an environment variable with code-points outside the US-ASCII range is passed in.

If includeParentEnvironment is true, the process's environment will include the parent process's environment, with environment taking precedence. Default is true.

If runInShell is true, the process will be spawned through a system shell. On Linux and OS X, /bin/sh is used, while %WINDIR%\system32\cmd.exe is used on Windows.

NOTE: On Windows, if executable is a batch file ('.bat' or '.cmd'), it may be launched by the operating system in a system shell regardless of the value of runInShell. This could result in arguments being parsed according to shell rules. For example:

dart
void main() async {
  // Will launch notepad.
  Process.start('test.bat', ['test&notepad.exe']);
}

Users must read all data coming on the stdout and stderr streams of processes started with Process.start. If the user does not read all data on the streams the underlying system resources will not be released since there is still pending data.

The following code uses Process.start to grep for main in the file test.dart on Linux.

dart
var process = await Process.start('grep', ['-i', 'main', 'test.dart']);
stdout.addStream(process.stdout);
stderr.addStream(process.stderr);

If mode is ProcessStartMode.normal (the default) a child process will be started with stdin, stdout and stderr connected to its parent. The parent process will not exit so long as the child is running, unless exit is called by the parent. If exit is called by the parent then the parent will be terminated but the child will continue running.

If mode is ProcessStartMode.detached a detached process will be created. A detached process has no connection to its parent, and can keep running on its own when the parent dies. The only information available from a detached process is its pid. There is no connection to its stdin, stdout or stderr, nor will the process' exit code become available when it terminates.

If mode is ProcessStartMode.detachedWithStdio a detached process will be created where the stdin, stdout and stderr are connected. The creator can communicate with the child through these. The detached process will keep running even if these communication channels are closed or the parent dies. The process' exit code will not become available when it terminated.

The default value for mode is ProcessStartMode.normal.

Implementation
dart
external static Future<Process> start(
  String executable,
  List<String> arguments, {
  String? workingDirectory,
  Map<String, String>? environment,
  bool includeParentEnvironment = true,
  bool runInShell = false,
  ProcessStartMode mode = ProcessStartMode.normal,
});