Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send message to parent process

Tags:

node.js

Can I send message to parent process?

master

var child =child_process.fork();

child.send({msg:msg})

child process

process.on('message', function(){

});

// how to send message to parent??
like image 624
guilin 桂林 Avatar asked May 01 '12 06:05

guilin 桂林


People also ask

How do you send data from child process to parent process?

Write a C program in which the child process takes an input array and send it to the parent process using pipe() and fork() and then print it in the parent process.

What is the output in the child process?

The read end of one pipe serves as standard input for the child process, and the write end of the other pipe is the standard output for the child process.


1 Answers

In short use: process.send()

Longer example, I wrote awhile ago named forktest.js:

var cp = require('child_process');

if (!process.send) {
  var p = cp.fork(__dirname + '/forktest');
  p.send({
    count: 10
  });
  p.on('message', function(data) {
    process.exit(0);
  });
} else {
  process.on('message', function(data) {
    console.log(data);
    data.count--;
    if (data.count === 0) {
      process.send({});
      process.exit(0);
    }
    var p = cp.fork(__dirname + '/forktest');
    p.send(data);
    p.on('message', function(data) {
      process.send(data);
      process.exit(0);
    });
  });
}
like image 141
Dan D. Avatar answered Oct 16 '22 10:10

Dan D.