首页 > 解决方案 > 如何等待父进程发送数据?

问题描述

我是使用 fork 的新手,我想知道
是否有办法等待父进程将数据发送到子进程?

也许是这样的

index.js:

var fork = require('child_process').fork;

var child = fork(__dirname + '/index 2.js');

child.on('message', function (response) {
    console.log(response);
});

async function out(){

    child.send(50);

    await new Promise(r => setTimeout(r, 3000)); //sleeps for 3000ms

    child.send(30);
}

out();

index2.js:

let a=0;

function wait_and_listen(){ 
   let temp_data;
   process.on('message',(data)=>{temp_data=data});
   return temp_data;
}

a+=wait_and_listen();

a-=wait_and_listen();

process.send(a);
process.exit();

标签: javascriptnode.js

解决方案


您只需使用一次“process.on('message') 并计算其调用次数。

// variable to detect if its the first call
let nthcall = 0;

// variable to accumulate data
let a = 0;

// work functon to be called when data is received from the parent
function work(data) {
    nthcall++;

    // feel free to do wwhatever you like with your data depending on nthcall value
    a += data;

    if (nthcall == 1) {
        console.log('first time i got data', data);
        return;
    }

    if (nthcall == 4) {
        console.log('last time i got data', data);
        process.send(a);
        process.exit(0);
    }

    console.log('i got data', data);
}

process.on('message', work);

推荐阅读