Базовый модуль модуля

модуль child_process

Модуль управления подпроцессами

Цитировать:

1 2
var child_process = require("child_process"); var child = child_process.spawn("ls");

При создании дочернего процесса опция options.stdio используется для настройки канала, установленного между родительским процессом и дочерним процессом. По умолчанию stdin, stdout и stderr дочернего процесса перенаправляются наChildProcessСоответствующие потоки stdin, stdout и stderr объекта. Это эквивалентно установке в options.stdio значения ['pipe', 'pipe', 'pipe'].

Для удобства options.stdio может быть одной из следующих строк:

  • 'pipe': эквивалент ['pipe', 'pipe', 'pipe'] (по умолчанию).
  • 'игнорировать': эквивалентно ['игнорировать', 'игнорировать', 'игнорировать'].
  • 'наследовать': эквивалент ['наследовать', 'наследовать', 'наследовать'] или [0, 1, 2].
  • 'pty': эквивалент ['pty', 'pty', 'pty']. Windows не поддерживается.

В противном случае значение options.stdio должно быть массивом (где каждый индекс соответствует дескриптору файла в дочернем процессе). Дескрипторы файлов 0, 1 и 2 соответствуют stdin, stdout и stderr соответственно. Другие файловые дескрипторы могут быть указаны для создания других каналов между родительским процессом и дочерним процессом. Значение может быть одним из следующих:

  1. 'pipe': Создайте канал между дочерним процессом и родительским процессом. Родительский конец канала доступен родительскому процессу как атрибут stdio[fd] объекта child_process. Каналы, созданные для файловых дескрипторов 0, 1 и 2, также доступны как stdin, stdout и stderr соответственно.
  2. «игнорировать»: предписывает fibjs игнорировать файловые дескрипторы в дочерних процессах. Хотя fibjs всегда будет открывать файловые дескрипторы 0, 1 и 2 для своих порожденных процессов, установка для файлового дескриптора значения «игнорировать» приводит к тому, что fibjs открывает /dev/null и добавляет его к файловому дескриптору дочернего процесса.
  3. «inherit»: потоковая передача соответствующего stdio в родительский процесс или из него. В первых трех позициях это эквивалентноprocess.stdin,process.stdoutиprocess.stderr. В любой другой позиции эквивалентно «игнорировать».
  4. «pty»: дочерний процесс будет выполнен в виртуальном терминале. В настоящее время действительны только stdin и stdout.
  5. Положительное целое число: целочисленное значение будет интерпретироваться как дескриптор файла, открытый в данный момент в родительском процессе. Он используется совместно с дочерним процессом, аналогично совместному использованию <Stream> Объектный путь. Входящие сокеты не поддерживаются в Windows.
  6. null или undefined: используйте значение по умолчанию. Каналы создаются для файловых дескрипторов 0, 1 и 2 stdio (другими словами, stdin, stdout и stderr). Для файловых дескрипторов версии 3 и выше по умолчанию используется значение «игнорировать».
1 2 3 4 5 6 7 8 9 10 11 12 13
const { spawn } = require('child_process'); // child process uses parent's stdio spawn('prg', [], { stdio: 'inherit' }); // child process uses parent's stderr spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });

Для пользователей, которые также используют nodejs, обратите внимание, что

  • child_process.exec(command, args)Функция одноименного API fibjs аналогична функции nodejs, но в Windows cmd.exe не будет автоматически использоваться в качестве среды выполнения параметра команды;
  • child_process.[spawn|exec|execFile|run] в fibjs — это функция асинхронного стиля, которая объединяет синхронизацию/обратный вызов:
    • Если последний параметр не является функцией, он синхронизируется
    • Если функция передается в качестве последнего параметра, она является асинхронной;
  • Результатом возврата child_process.[exec|execFile] fibjs является объект, который полностью отличается от объекта, возвращаемого API nodejs с тем же именем.
  • fibjs child_process.runне имеет соответствующего API в nodejs

статическая функция

spawn

Опубликовать дочерний процесс с помощью данной команды

1 2 3
static ChildProcess child_process.spawn(String command, Array args, Object options = {});

Параметры звонка:

  • command: строка, указывает команду для запуска
  • args: Массив, указывает список строковых параметров.
  • options: Объект, укажите параметры создания

Результаты возврата:

  • ChildProcess, возвращает объект дочернего процесса

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // configure the group identity of the process "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Опубликовать дочерний процесс с помощью данной команды

1 2
static ChildProcess child_process.spawn(String command, Object options = {});

Параметры звонка:

  • command: строка, указывает команду для запуска
  • options: Объект, укажите параметры создания

Результаты возврата:

  • ChildProcess, возвращает объект дочернего процесса

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

exec

Выполните команду в оболочке и буферизируйте вывод. При выполнении в режиме обратного вызова функция вернет объект дочернего процесса.

1 2
static (Variant stdout, Variant stderr) child_process.exec(String command, Object options = {}) async;

Параметры звонка:

  • command: строка, указывает команду для запуска
  • options: Объект, укажите параметры создания

Результаты возврата:

  • (Вариант stdout, Вариант stderr), возвращает содержимое вывода stdio дочернего процесса.

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "encoding": "utf8", // specify the character encoding used to decode the stdout and stderr output "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

execFile

Непосредственно выполнить указанный файл и буферизовать вывод. При выполнении в режиме обратного вызова функция вернет объект дочернего процесса.

1 2 3
static (Variant stdout, Variant stderr) child_process.execFile(String command, Array args, Object options = {}) async;

Параметры звонка:

  • command: строка, указывает команду для запуска
  • args: Массив, указывает список строковых параметров.
  • options: Объект, укажите параметры создания

Результаты возврата:

  • (Вариант stdout, Вариант stderr), возвращает содержимое вывода stdio дочернего процесса.

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "encoding": "utf8", // specify the character encoding used to decode the stdout and stderr output "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Непосредственно выполнить указанный файл и буферизовать вывод. При выполнении в режиме обратного вызова функция вернет объект дочернего процесса.

1 2
static (Variant stdout, Variant stderr) child_process.execFile(String command, Object options = {}) async;

Параметры звонка:

  • command: строка, указывает команду для запуска
  • options: Объект, укажите параметры создания

Результаты возврата:

  • (Вариант stdout, Вариант stderr), возвращает содержимое вывода stdio дочернего процесса.

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "encoding": "utf8", // specify the character encoding used to decode the stdout and stderr output "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

spawnSync

Опубликовать дочерний процесс с помощью данной команды

1 2 3
static (Integer pid, NArray output, Variant stdout, Variant stderr, Integer status, Variant error) child_process.spawnSync(String command, Array args, Object options = {}) async;

Параметры звонка:

  • command: строка, указывает команду для запуска
  • args: Массив, указывает список строковых параметров.
  • options: Объект, укажите параметры создания

Результаты возврата:

  • (Целый pid, вывод NArray, вариант стандартного вывода, вариант stderr, состояние целого числа, ошибка варианта), возвращает результат выполнения дочернего процесса.

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // configure the group identity of the process "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Опубликовать дочерний процесс с помощью данной команды

1 2
static (Integer pid, NArray output, Variant stdout, Variant stderr, Integer status, Variant error) child_process.spawnSync(String command, Object options = {}) async;

Параметры звонка:

  • command: строка, указывает команду для запуска
  • options: Объект, укажите параметры создания

Результаты возврата:

  • (Целый pid, вывод NArray, вариант стандартного вывода, вариант stderr, состояние целого числа, ошибка варианта), возвращает результат выполнения дочернего процесса.

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

fork

Выполнить модуль в дочернем процессе

1 2 3
static ChildProcess child_process.fork(String module, Array args, Object options = {});

Параметры звонка:

  • module: строка, указывает команду для запуска
  • args: Массив, указывает список строковых параметров.
  • options: Объект, укажите параметры создания

Результаты возврата:

  • ChildProcess, возвращает объект дочернего процесса

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Выполнить модуль в дочернем процессе

1 2
static ChildProcess child_process.fork(String module, Object options = {});

Параметры звонка:

  • module: строка, указывает команду для запуска
  • options: Объект, укажите параметры создания

Результаты возврата:

  • ChildProcess, возвращает объект дочернего процесса

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9 10
{ "cwd": "", // working directory of the child process, default to current directory "stdio": Array | String, // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

run

Непосредственно выполнить указанный файл и вернуть код выхода. При выполнении в режиме обратного вызова функция вернет объект дочернего процесса.

1 2 3
static Integer child_process.run(String command, Array args, Object options = {}) async;

Параметры звонка:

  • command: строка, указывает команду для запуска
  • args: Массив, указывает список строковых параметров.
  • options: Объект, укажите параметры создания

Результаты возврата:

  • Integer, возвращает код выхода дочернего процесса

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }

Непосредственно выполнить указанный файл и вернуть код выхода. При выполнении в режиме обратного вызова функция вернет объект дочернего процесса.

1 2
static Integer child_process.run(String command, Object options = {}) async;

Параметры звонка:

  • command: строка, указывает команду для запуска
  • options: Объект, укажите параметры создания

Результаты возврата:

  • Integer, возвращает код выхода дочернего процесса

Поддерживаются следующие опции:

1 2 3 4 5 6 7 8 9
{ "cwd": "", // working directory of the child process, default to current directory "env": {}, // key-value pairs of environment variables to add to the child's environment "detached": false, // child process will be a leader of a new process group, default to false "uid": 0, // configure the user identity of the process "gid": 0, // con "windowsVerbatimArguments": false, // do not execute any quote or escape processing on Windows. Ignored on Unix. When specified, the command line string is passed directly to the underlying operating system shell without any processing whatsoever. This is set to true automatically when the shell option is specified and is CMD. "windowsHide": false // hide the subprocess console window that would normally be created on Windows systems. This option has no effect on non-Windows systems. }