Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

親子は"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!' }
gfx
#Android #Java #Kotlin #Ruby #RubyOnRails #Elasticsearch
http://gfx.hatenablog.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした