1 var common = require('../common');
2 var assert = require('assert');
3 var http = require('http');
4 var net = require('net');
5 var PORT = common.PORT;
6 var spawn = require('child_process').spawn;
8 if (process.platform === 'win32') {
9 console.error('This test is disabled on windows.');
13 switch (process.argv[2]) {
14 case 'child': return child();
15 case 'parent': return parent();
16 default: return test();
19 // spawn the parent, and listen for it to tell us the pid of the child.
20 // WARNING: This is an example of listening on some arbitrary FD number
21 // that has already been bound elsewhere in advance. However, binding
22 // server handles to stdio fd's is NOT a good or reliable way to do
23 // concurrency in HTTP servers! Use the cluster module, or if you want
24 // a more low-level approach, use child process IPC manually.
26 var parent = spawn(process.execPath, [__filename, 'parent'], {
27 stdio: [ 0, 'pipe', 2 ]
30 parent.stdout.on('data', function(c) {
32 if (json.indexOf('\n') !== -1) next();
35 console.error('output from parent = %s', json);
36 var child = JSON.parse(json);
37 // now make sure that we can request to the child, then kill it.
42 }).on('response', function (res) {
44 res.on('data', function(c) {
47 res.on('end', function() {
48 // kill the child before we start doing asserts.
49 // it's really annoying when tests leave orphans!
50 process.kill(child.pid, 'SIGKILL');
55 assert.equal(s, 'hello from child\n');
56 assert.equal(res.statusCode, 200);
62 // Listen on PORT, and then pass the handle to the detached child.
63 // Then output the child's pid, and immediately exit.
65 var server = net.createServer(function(conn) {
66 throw new Error('Should not see connections on parent');
67 conn.end('HTTP/1.1 403 Forbidden\r\n\r\nI got problems.\r\n');
68 }).listen(PORT, function() {
69 console.error('server listening on %d', PORT);
71 var child = spawn(process.execPath, [__filename, 'child'], {
72 stdio: [ 0, 1, 2, server._handle ],
76 console.log('%j\n', { pid: child.pid });
78 // Now close the parent, so that the child is the only thing
79 // referencing that handle. Note that connections will still
80 // be accepted, because the child has the fd open, but the parent
81 // will exit gracefully.
87 // Run as a child of the parent() mode.
89 // start a server on fd=3
90 http.createServer(function(req, res) {
91 console.error('request on child');
92 console.error('%s %s', req.method, req.url, req.headers);
93 res.end('hello from child\n');
94 }).listen({ fd: 3 }, function() {
95 console.error('child listening on fd=3');