Módulo módulo básico

módulo niño_proceso

Módulo de gestión de subprocesos

Cita:

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

Al crear un proceso hijo, la opción options.stdio se utiliza para configurar la tubería establecida entre el proceso padre y el proceso hijo. De forma predeterminada, la entrada estándar, la salida estándar y la salida estándar del proceso secundario se redirigen aChildProcessLas secuencias stdin, stdout y stderr correspondientes en el objeto. Esto equivale a configurar options.stdio en ['pipe', 'pipe', 'pipe'].

Por conveniencia, options.stdio puede ser una de las siguientes cadenas:

  • 'pipe': Equivalente a ['pipe', 'pipe', 'pipe'] (predeterminado).
  • 'ignorar': Equivalente a ['ignorar', 'ignorar', 'ignorar'].
  • 'heredar': equivalente a ['heredar', 'heredar', 'heredar'] o [0, 1, 2].
  • 'pty': equivalente a ['pty', 'pty', 'pty']. Windows no es compatible.

De lo contrario, el valor de options.stdio debe ser una matriz (donde cada índice corresponde a un descriptor de archivo en el proceso hijo). Los descriptores de archivo 0, 1 y 2 corresponden a stdin, stdout y stderr respectivamente. Se pueden especificar otros descriptores de archivos para crear otras canalizaciones entre el proceso principal y el proceso secundario. El valor puede ser uno de los siguientes:

  1. 'tubería': crea una tubería entre el proceso hijo y el proceso padre. El extremo principal de la tubería está expuesto al proceso principal como el atributo stdio[fd] en el objeto child_process. Las canalizaciones creadas para los descriptores de archivos 0, 1 y 2 también están disponibles como stdin, stdout y stderr respectivamente.
  2. 'ignorar': indica a fibjs que ignore los descriptores de archivos en los procesos secundarios. Aunque fibjs siempre abrirá los descriptores de archivo 0, 1 y 2 para sus procesos generados, configurar el descriptor de archivo en 'ignorar' hace que fibjs abra /dev/null y lo agregue al descriptor de archivo del proceso secundario.
  3. 'heredar': transmite el stdio correspondiente hacia o desde el proceso principal. En las tres primeras posiciones, esto equivale aprocess.stdin,process.stdoutyprocess.stderr. En cualquier otra posición, equivale a 'ignorar'.
  4. 'pty': El proceso hijo se ejecutará en una terminal virtual. En este momento sólo son válidas stdin y stdout.
  5. Entero positivo: el valor entero se interpretará como el descriptor de archivo actualmente abierto en el proceso principal. Se comparte con el proceso hijo, similar a compartir <Stream> Modo objeto. Los sockets entrantes no son compatibles con Windows.
  6. nulo o indefinido: utilice el valor predeterminado. Las canalizaciones se crean para los descriptores de archivos 0, 1 y 2 de stdio (en otras palabras, stdin, stdout y stderr). Para los descriptores de archivos 3 y superiores, el valor predeterminado es "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 los usuarios que también usan nodejs, tenga en cuenta que

  • La función de la API de fibjs child_process.exec(command, args)con el mismo nombre es similar a la de nodejs, pero en Windows, cmd.exe no se utilizará automáticamente como entorno de ejecución del parámetro de comando;
  • child_process.[spawn|exec|execFile|run] de fibjs es una función de estilo asíncrono que integra sincronización/devolución de llamada:
    • Si el último parámetro no es una función, se sincroniza
    • Si se pasa una función como último parámetro, es asincrónica;
  • El resultado de retorno de child_process.[exec|execFile] de fibjs es un objeto, que es completamente diferente del objeto devuelto por la API de nodejs con el mismo nombre.
  • fibjs child_process.runno tiene API correspondiente en nodejs

función estática

spawn

Publicar un proceso hijo con el comando dado

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

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

Las opciones admitidas son las siguientes:

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

Publicar un proceso hijo con el comando dado

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

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

Las opciones admitidas son las siguientes:

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

Ejecute un comando en el shell y almacene en buffer la salida. Cuando se ejecuta en modo de devolución de llamada, la función devolverá el objeto de proceso hijo

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

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

  • (Variant stdout, Variant stderr), devuelve el contenido de salida stdio del proceso hijo

Las opciones admitidas son las siguientes:

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

Ejecute directamente el archivo especificado y almacene la salida en el buffer. Cuando se ejecuta en modo de devolución de llamada, la función devolverá el objeto del proceso secundario.

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

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

  • (Variant stdout, Variant stderr), devuelve el contenido de salida stdio del proceso hijo

Las opciones admitidas son las siguientes:

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

Ejecute directamente el archivo especificado y almacene la salida en el buffer. Cuando se ejecuta en modo de devolución de llamada, la función devolverá el objeto del proceso secundario.

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

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

  • (Variant stdout, Variant stderr), devuelve el contenido de salida stdio del proceso hijo

Las opciones admitidas son las siguientes:

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

Publicar un proceso hijo con el comando dado

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 llamada:

  • command: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

  • (Pid entero, salida NArray, salida estándar variante, stderr variante, estado entero, error variante), devuelve el resultado de ejecución del proceso hijo

Las opciones admitidas son las siguientes:

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

Publicar un proceso hijo con el comando dado

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 llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

  • (Pid entero, salida NArray, salida estándar variante, stderr variante, estado entero, error variante), devuelve el resultado de ejecución del proceso hijo

Las opciones admitidas son las siguientes:

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

Ejecutar un módulo en un proceso hijo

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

Parámetros de llamada:

  • module: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

Las opciones admitidas son las siguientes:

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

Ejecutar un módulo en un proceso hijo

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

Parámetros de llamada:

  • module: Cadena, especifica el comando a ejecutar
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

Las opciones admitidas son las siguientes:

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

Ejecute directamente el archivo especificado y devuelva el código de salida. Cuando se ejecuta en modo de devolución de llamada, la función devolverá el objeto de proceso secundario.

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

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • args: Matriz, especifica la lista de parámetros de cadena
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

  • Integer, devuelve el código de salida del proceso hijo

Las opciones admitidas son las siguientes:

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

Ejecute directamente el archivo especificado y devuelva el código de salida. Cuando se ejecuta en modo de devolución de llamada, la función devolverá el objeto de proceso secundario.

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

Parámetros de llamada:

  • command: Cadena, especifica el comando a ejecutar
  • options: Objeto, especificar parámetros de creación

Resultados de devolución:

  • Integer, devuelve el código de salida del proceso hijo

Las opciones admitidas son las siguientes:

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