Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

618
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda