2017-04-20 65 views
1

我只是想分叉一個簡單的子進程,並讓IPC通道保持打開狀態,但由於某種原因它會立即退出。爲什麼分叉的子進程在我分叉後立即退出?

在parent.js:

var child = require('child_process').fork('./child.js'); 
child.on('hi', function() { 
    console.log("Hi"); 
}); 

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

child.send('hello'); 

在child.js:

process.on('hello', function() { 
    process.send('hi'); 
}); 

我得到 「已退出」 立即打印到控制檯,從來沒有得到一個 '嗨'。然後,如果我繼續嘗試發送到子進程,則會出現通道關閉錯誤。

我做錯了什麼?

+0

我覺得這是發生,因爲你的子進程結束。子進程中的某些東西需要保持進程運行。 – chris

+0

我試着添加一個垃圾'setInterval()'讓它保持活着,並且仍然沒有骰子 – Joey

+0

嘗試'process.stdin.resume();' – chris

回答

1

您需要保持這兩個進程打開,因爲孩子會立即關閉,父母也會關閉。你可以像這樣做:

parent.js

var child = require('child_process').fork('./child.js'); 

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

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

setTimeout(() => { 
    child.send('hello'); 
}, 1000); 


process.stdin.resume(); 

child.js

process.on('message', function() { 
    console.log("sending hi"); 
    process.send('hi'); 
}); 
+1

這樣的一些任意字符串,我不確定任意事件名稱的作用,好像它必須是「message」 – chris

+0

ohhhhh我懂了:)事實證明這是事件的名稱 - 認爲它可以是任何東西,但就像你說它必須是「消息」 – Joey