node icon indicating copy to clipboard operation
node copied to clipboard

Child process/streams memory leak

Open jhenninger opened this issue 11 years ago • 2 comments

The following code is leaking memory. I tested this using node-inspector and taking heap snapshots in chrome.

var cp = require('child_process');

setInterval(function () {
  var p = cp.spawn('yes');

  p.stdout.read();
  p.kill();
}, 50);

The leak stops if the p.stdout.read(); line is removed.

Another test, requires weak:

var cp = require('child_process');
var weak = require('weak');

var c = 0;

function cb() {
  console.log(--c);
}

setInterval(function () {
  var p = cp.spawn('yes');

  ++c;

  p.stdout.read();
  p.kill();

  weak(p, cb);

  gc();

}, 50);

Running this with --expose-gc will display the the number of process instances that haven't been garbaged collected. The number will always be counting up and never decrease.

If the p.stdout.read() line is removed, there will always be only one process object waiting to be collected.

jhenninger avatar Nov 27 '15 18:11 jhenninger

+1. The leak also seems to go away if you replace p.stdout.read() with p.stdout.read(0) or p.stdin.read() or p.stderr.read().

davidvgalbraith avatar Nov 29 '15 23:11 davidvgalbraith

I found this one interesting and untoward, so I took a crack at it: https://github.com/nodejs/node/pull/4071.

davidvgalbraith avatar Nov 30 '15 10:11 davidvgalbraith