Skip to content

Commit 8cc41e5

Browse files
committed
doc: make socket IPC examples more robust
This commit aims to improve the documentation examples that send sockets over IPC channels. Specifically, pauseOnConnect is added to a server that inspects the socket before sending and a 'message' handler adds a check that the socket still exists. PR-URL: nodejs/node#13196 Reviewed-By: Santiago Gimeno <[email protected]> Reviewed-By: Refael Ackermann <[email protected]>
1 parent d20b7bf commit 8cc41e5

File tree

1 file changed

+13
-3
lines changed

1 file changed

+13
-3
lines changed

doc/api/child_process.md

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1050,8 +1050,9 @@ const { fork } = require('child_process');
10501050
const normal = fork('subprocess.js', ['normal']);
10511051
const special = fork('subprocess.js', ['special']);
10521052

1053-
// Open up the server and send sockets to child
1054-
const server = require('net').createServer();
1053+
// Open up the server and send sockets to child. Use pauseOnConnect to prevent
1054+
// the sockets from being read before they are sent to the child process.
1055+
const server = require('net').createServer({ pauseOnConnect: true });
10551056
server.on('connection', (socket) => {
10561057

10571058
// If this is special priority
@@ -1071,7 +1072,12 @@ passed to the event callback function:
10711072
```js
10721073
process.on('message', (m, socket) => {
10731074
if (m === 'socket') {
1074-
socket.end(`Request handled with ${process.argv[2]} priority`);
1075+
if (socket) {
1076+
// Check that the client socket exists.
1077+
// It is possible for the socket to be closed between the time it is
1078+
// sent and the time it is received in the child process.
1079+
socket.end(`Request handled with ${process.argv[2]} priority`);
1080+
}
10751081
}
10761082
});
10771083
```
@@ -1081,6 +1087,10 @@ tracking when the socket is destroyed. To indicate this, the `.connections`
10811087
property becomes `null`. It is recommended not to use `.maxConnections` when
10821088
this occurs.
10831089

1090+
It is also recommended that any `'message'` handlers in the child process
1091+
verify that `socket` exists, as the connection may have been closed during the
1092+
time it takes to send the connection to the child.
1093+
10841094
*Note: this function uses [`JSON.stringify()`][] internally to serialize the
10851095
`message`.*
10861096

0 commit comments

Comments
 (0)