Need help on Fork and setInterval

I am getting unexpected behavior. I have 2 files : parent.js and child.js

parent.js:

var cp = require("child_process");
var child = cp.fork(__dirname + "/child");
child.on("message", function (message) {
    console.log("parent received:  " + message.count);
    if (child.connected) {
        setInterval(function () {
            message.count++;
            child.send(message);
        }, 2000)
    }
});
child.on("SIGINT", function () {
    child.kill();
    process.exit();
});
child.send({
    count: 0
});

child.js :

process.on("message", function (message) {
      console.log("child received:  " + message.count);
       if (process.connected) {
              setInterval(function () {
                    message.count++;
                    process.send(message);
               }, 2000)
    }
});

output I was expecting :
hild received: 0
parent received: 1
parent received: 2
child received: 3
child received: 4
parent received: 5
child received: 6

But I am getting :

child received: 0
parent received: 1
parent received: 2
child received: 2
child received: 3
parent received: 3
child received: 3
parent received: 3
parent received: 4
child received: 4
child received: 4
parent received: 4
child received: 4
parent received: 4
child received: 4
parent received: 4

Any idea why?

Because every time parent or child receives a message, you’re creating an ever increasing number of new timers that will run indefinitely.

If you just want to ping messages back and forth, use setTimeout.

For example:

const cp = require("child_process");
const child = cp.fork(__dirname + "/child");

child.on("message", (message) => {
  console.log(`Parent received: ${message.count}`);

  if (child.connected) {
    setTimeout(() => {
      message.count++;
      child.send(message);
    }, 500)
  }
});

child.on("SIGINT", () => {
  child.kill();
  process.exit();
});

child.send({
  count: 0
});

and:

process.on("message", (message) => {
  console.log(`child received:  ${message.count}`);

  if (process.connected) {
    setTimeout(() => {
      message.count++;
      process.send(message);
    }, 500);
  }
});

Produces:

child received:  0
Parent received: 1
child received:  2
Parent received: 3
child received:  4
...

Otherwise, could you describe what you’re trying to achieve in a little more detail.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.