Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

628
Vistas
Nodejs: Child process not exiting after calling unref()

According to the nodejs docs, the detached option on creating a ChildProcess allows the child process to continue running after the parent exits.

And the unref() method on ChildProcess allows the parent to exit and not wait for the child process to exit.

By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given subprocess to exit, use the subprocess.unref() method. Doing so will cause the parent's event loop to not include the child in its reference count, allowing the parent to exit independently of the child, unless there is an established IPC channel between the child and the parent.

When using the detached option to start a long-running process, the process will not stay running in the background after the parent exits unless it is provided with a stdio configuration that is not connected to the parent. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.

I am trying to create a child process that would do some long-duration work, and I don't want the parent to be waiting for it.

Here's parent.js

import { fork } from "child_process";

console.log(`process.pid: ${process.pid}`);

process.on("beforeExit", () => {
  console.log("parent exiting...");
});

const forked = fork("./child.js", {
  detached: true,
  stdio: "ignore",
});

forked.unref();

and here's child.js

const main = async () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("resolving");
      resolve();
    }, 10 * 1000);
  });
};

main();

The child.js is a trivial script, but my use-case involves the child process to run some computation for a specified duration, which would be 10,20 secs.

When running the code above, the beforeExit event is emitted only after 10 secs, which is when the child process should be exiting. But according to the code and docs, shouldn't the parent be exiting as soon as the child process is created? Or rather, unref()-ed?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda