Módulo módulo básico

módulo child_process

Módulo de xestión de subprocesos

Cita:

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

Ao crear un proceso fillo, a opción options.stdio úsase para configurar a canalización establecida entre o proceso pai e o proceso fillo. De forma predeterminada, o stdin, stdout e stderr do proceso fillo son redirixidosChildProcessOs fluxos stdin, stdout e stderr correspondentes no obxecto. Isto é equivalente a configurar options.stdio en ['pipe', 'pipe', 'pipe'].

Para comodidade, options.stdio pode ser unha das seguintes cadeas:

  • 'pipe': equivalente a ['pipe', 'pipe', 'pipe'] (predeterminado).
  • 'ignorar': Equivalente a ['ignorar', 'ignorar', 'ignorar'].
  • 'herdar': equivalente a ['herdar', 'herdar', 'herdar'] ou [0, 1, 2].
  • 'pty': equivalente a ['pty', 'pty', 'pty']. Windows non é compatible.

En caso contrario, o valor de options.stdio debe ser unha matriz (onde cada índice corresponde a un descritor de ficheiro no proceso fillo). Os descritores de ficheiros 0, 1 e 2 corresponden a stdin, stdout e stderr respectivamente. Pódense especificar outros descritores de ficheiros para crear outras canalizacións entre o proceso principal e o proceso fillo. O valor pode ser un dos seguintes:

  1. 'pipe': crea unha canalización entre o proceso fillo e o proceso principal. O extremo pai da canalización está exposto ao proceso pai como o atributo stdio[fd] no obxecto child_process. As canalizacións creadas para os descritores de ficheiros 0, 1 e 2 tamén están dispoñibles como stdin, stdout e stderr respectivamente.
  2. 'ignore': indica a fibjs que ignore os descritores de ficheiros nos procesos fillos. Aínda que fibjs sempre abrirá os descritores de ficheiros 0, 1 e 2 para os seus procesos xerados, establecer o descritor de ficheiros en "ignorar" fai que fibjs abra /dev/null e o anexa ao descritor de ficheiros do proceso fillo.
  3. 'herdar': transmite o stdio correspondente ao proceso pai ou desde o proceso principal. Nas tres primeiras posicións, isto é equivalente aprocess.stdin,process.stdouteprocess.stderr. En calquera outra posición, equivalente a 'ignorar'.
  4. 'pty': o proceso fillo executarase nun terminal virtual. Neste momento só son válidos stdin e stdout.
  5. Enteiro positivo: o valor enteiro interpretarase como o descritor de ficheiro actualmente aberto no proceso principal. Compártese co proceso fillo, de forma similar a compartir <Stream> Camiño obxecto. Os sockets entrantes non son compatibles con Windows.
  6. nulo ou indefinido: use o valor predeterminado. Créanse canalizacións para os descritores de ficheiros 0, 1 e 2 de stdio (noutras palabras, stdin, stdout e stderr). Para os descritores de ficheiros 3 e superiores, o valor predeterminado é "ignorar".
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] });

Para os usuarios que tamén usan nodejs, teña en conta que

  • A función da API de fibjs child_process.exec(command, args)co mesmo nome é similar á de nodejs, pero en Windows, cmd.exe non se usará automaticamente como ambiente de execución do parámetro de comando;
  • o proceso_fillo de fibjs.[spawn|exec|execFile|run] é unha función de estilo asíncrono que integra sincronización/callback:
    • Se o último parámetro non é unha función, está sincronizado
    • Se se pasa unha función como último parámetro, é asíncrona;
  • O resultado de retorno de child_process de fibjs.[exec|execFile] é un obxecto, que é completamente diferente do obxecto devolto pola API de nodejs co mesmo nome.
  • fibjs child_process.runnon ten unha API correspondente en nodejs

función estática

spawn

Publica un proceso fillo co comando indicado

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

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • args: Matriz, especifica a lista de parámetros de cadea
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

As opcións admitidas son as seguintes:

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. }

Publica un proceso fillo co comando indicado

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

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

As opcións admitidas son as seguintes:

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

Executar un comando no shell e almacenar a saída. Cando se executa no modo de devolución de chamada, a función devolverá o obxecto do proceso fillo

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

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

  • (Variant stdout, Variant stderr), devolve o contido de saída stdio do proceso fillo

As opcións admitidas son as seguintes:

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

Executar directamente o ficheiro especificado e almacenar a saída. Cando se executa no modo de devolución de chamada, a función devolverá o obxecto do proceso fillo.

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

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • args: Matriz, especifica a lista de parámetros de cadea
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

  • (Variant stdout, Variant stderr), devolve o contido de saída stdio do proceso fillo

As opcións admitidas son as seguintes:

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. }

Executar directamente o ficheiro especificado e almacenar a saída. Cando se executa no modo de devolución de chamada, a función devolverá o obxecto do proceso fillo.

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

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

  • (Variant stdout, Variant stderr), devolve o contido de saída stdio do proceso fillo

As opcións admitidas son as seguintes:

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

Publica un proceso fillo co comando indicado

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;

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • args: Matriz, especifica a lista de parámetros de cadea
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

  • (Pid enteiro, saída NArray, Variant stdout, Variant stderr, Integer status, Variant error), devolve o resultado en execución do proceso fillo

As opcións admitidas son as seguintes:

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. }

Publica un proceso fillo co comando indicado

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

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

  • (Pid enteiro, saída NArray, Variant stdout, Variant stderr, Integer status, Variant error), devolve o resultado en execución do proceso fillo

As opcións admitidas son as seguintes:

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

Executar un módulo nun proceso fillo

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

Parámetros de chamada:

  • module: Cadea, especifica o comando a executar
  • args: Matriz, especifica a lista de parámetros de cadea
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

As opcións admitidas son as seguintes:

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. }

Executar un módulo nun proceso fillo

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

Parámetros de chamada:

  • module: Cadea, especifica o comando a executar
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

As opcións admitidas son as seguintes:

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

Execute directamente o ficheiro especificado e devolve o exitCode. Cando se executa no modo de devolución de chamada, a función devolverá o obxecto do proceso fillo.

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

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • args: Matriz, especifica a lista de parámetros de cadea
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

  • Integer, devolve o exitCode do proceso fillo

As opcións admitidas son as seguintes:

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. }

Execute directamente o ficheiro especificado e devolve o exitCode. Cando se executa no modo de devolución de chamada, a función devolverá o obxecto do proceso fillo.

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

Parámetros de chamada:

  • command: Cadea, especifica o comando a executar
  • options: Obxecto, especifique os parámetros de creación

Resultados de devolución:

  • Integer, devolve o exitCode do proceso fillo

As opcións admitidas son as seguintes:

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. }