Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add optional timeout setting after which the child process is killed …

…if it has not finished executing.
  • Loading branch information...
commit d7c09c312c7c7fd9c5ccf57243699972b16645f7 1 parent 0634ca3
Tomaz Muraus authored December 14, 2010

Showing 1 changed file with 33 additions and 0 deletions. Show diff stats Hide diff stats

  1. 33  lib/worker.js
33  lib/worker.js
@@ -62,6 +62,7 @@ Worker.prototype.isTerminated = function () {
62 62
 exports.Worker = Worker;
63 63
 
64 64
 function WorkerChild (eventDest, filename, options) {
  65
+  var timeout_id;
65 66
   var self = this;
66 67
   this.eventDest  = eventDest;
67 68
   this.filename = filename;
@@ -80,18 +81,50 @@ function WorkerChild (eventDest, filename, options) {
80 81
   });
81 82
 
82 83
   this.child.addListener("exit", function (code) {
  84
+    if (!this.terminated) {
  85
+      this.terminated = true;
  86
+    }
  87
+
  88
+    if (self.timeout_id) {
  89
+      clearTimeout(self.timeout_id);
  90
+    }
  91
+
83 92
     self.eventDest.emit("exit", code);
84 93
     debug(self.child.pid + ": exit "+code);
85 94
   });
86 95
 
  96
+  if (options.timeout) {
  97
+    // Set a timeout handler which kills the process if it has not finished
  98
+    // executing after options.timeout number of milliseconds.
  99
+    timeout_id = setTimeout(function() {
  100
+                              self.timeoutHandler();
  101
+                            }, options.timeout);
  102
+  }
  103
+  else {
  104
+    timeout_id = null;
  105
+  }
  106
+
87 107
   this.buffer = "";
88 108
   this.active = false;
89 109
   this.terminated = false;
90 110
   this.queue  = [];
  111
+
  112
+  this.options = options;
  113
+  this.timeout_id = timeout_id;
91 114
 }
92 115
 
93 116
 WorkerChild.prototype = {
94 117
 
  118
+  timeoutHandler: function() {
  119
+    if (!this.terminated) {
  120
+      this.child.kill('SIGTERM');
  121
+
  122
+      err = new Error('Child killed, because it did not finish after '
  123
+                      + this.options.timeout + ' milliseconds');
  124
+      this.eventDest.emit("error", err);
  125
+    }
  126
+  },
  127
+
95 128
   postMessage: function (message) {
96 129
     if (!this.active && this.terminated) {
97 130
       throw new Error('Cannot post message to a terminated child');

0 notes on commit d7c09c3

Please sign in to comment.
Something went wrong with that request. Please try again.