27
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

child_process.fork()は全然fork(2)じゃないけど面白い。

Posted at

親子は"message"イベントを通じて通信できる。通信できるデータはプリミティブ値の他、JSONオブジェクトが許されている。プロセスは2つできているけどゾンビ化したりしないしちゃんとwaitpidするみたいだ。

欠点としては、UNIX的なfork(2)と違ってdaemon化には使えないこと。cihld_process.exec()もexec(2)とは全く違うのでUNIX的なプロセス管理はまったくできなくなっている。手軽だけど細かな制御ができないのは困るなあ。

以下は1秒ごとにメッセージを送りあうスクリプト。

親プロセス parent.js:

#!/usr/bin/env node
var child_process = require("child_process");

var child = child_process.fork("./child");

child.on("message", function (msg) {
	console.log(msg);

	setTimeout(function () {
		child.send({ message: "from parent" });
	}, 1000);
});

child.send({ message: "from parent" });

子プロセス child.js:

console.log("child start");

process.on("message", function (msg) {
	console.log(msg);

	setTimeout(function() {
		process.send({ message: "from child!" });
	}, 1000);
});

process.on("exit", function () {
	console.log("child exit");
});

実行結果:

child start
{ message: 'from parent' }
{ message: 'from child!' }
{ message: 'from parent' }
{ message: 'from child!' }
{ message: 'from parent' }
{ message: 'from child!' }
{ message: 'from parent' }
{ message: 'from child!' }
27
21
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
21

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?