Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reattaching to spawned process via nodejs

I am creating a small proprietary game server manager in Node.js; currently it runs the game by spawning via child_process:

var server = spawn(cmd, args, { cwd: 'something' });

So long as the manager continues to run I can pipe commands and deal with the child as I would like. However, consider the possibility that my manager crashes or is closed. How would I then reattach to the previously spawned child process (which was still running while the manager was down)? I can store pidfiles to try and reconnect based on pid; but I'm not sure how to get a child_process object with access to the child's stdio objects.

I really would like this to be recoverable; any help is appreciated, thanks!


Please note: The game servers are proprietary, some examples are Minecraft, Source DS, etc. Assume i do not have access to the sever source.


EDIT

After reading some source code from node's child_process it looks like if you specify a property in the options called stdinStream, stdoutStream, or stderrStream it should just open a socket to it. (See lines 428 - 496). So the issue then is, how do I stop spawn from actually doing a spawn and instead just settings its values based on a specified pid and streams I pass. (I would get my stdinStream by doing fs.createWriteStream('/proc/PID/fd/0'); which should work since that fd is created as a pipe.)

like image 626
Chad Avatar asked Apr 11 '12 19:04

Chad


People also ask

How do I fix a process out of memory exception in node JS?

This exception can be solved by increasing the default memory allocated to our program to the required memory by using the following command. Parameters: SPACE_REQD: Pass the increased memory space (in Megabytes).

What is child_process spawn?

child_process.exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.


1 Answers

To extend what someone said in a comment above, you may be able to use http://nodejs.org/api/net.html where each child process creates a server (net.createServer()) and you keep a list of what children are listening at what ports somewhere, and then when your master restarts, it goes and finds that list of children and connects to each their servers. The Sockets that you get from net.createConnection() replace the child_process objects in your master.

net servers and sockets implement the same Readable and Writable Stream interfaces as stdio, so after setting up and connecting, you should be able to write(...) and pipe() events like you've been doing.

This may not be the best solution but I believe it will work.

like image 168
Nathan Friedly Avatar answered Sep 20 '22 12:09

Nathan Friedly