是否可以从电子渲染进程中分叉一个 child_process ?我在网上找到了一些帖子,但没有提示如何帮助我让我的代码正常工作。我创建了一个模块,用于分叉子进程。当我使用 cmd 在节点下运行此代码时,此代码有效。但是当我尝试将其集成到我的电子应用程序中时,我无法与 child.send() 方法进行通信。
// create fork
const fork = require('child_process').fork;
const fs = require('fs');
const img_path = [
'path/to/an/image1.jpg',
'path/to/an/image2.jpg',
'path/to/an/image3.jpg'
];
const cp = [];
const temp_path = img_path.map((item) => item);
createAndResize(2);
function createAndResize(num) {
return childResize(createChildProcess(num));
}
function createChildProcess(num) {
if(num <= 0) {
return cp;
} else {
let cf = fork('./child.js');
cp.push(cf);
num -= 1;
return createChildProcess(num);
}
}
function childResize(list) {
if(list.length <=0) {
return true;
} else {
// child_process is created
let child = list.shift();
child.on('message', function (data) {
if (!temp_path.length) {
process.kill(data);
} else {
child.send(temp_path.shift());
}
});
child.send(temp_path.shift());
setTimeout(function() {
childResize(list);
}, 1000);
}
}
//child.js
process.on('message', function(msg) {
console.log(msg); //this is never reached
};
Run Code Online (Sandbox Code Playgroud)
编辑:根据下面的评论,我在主进程上分叉了子进程。沟通似乎很有效,几乎没有例外。但首先是我的新代码:
// myView.js
const { remote } = require('electron');
const mainProcess = remote.require('./main.js');
const { forkChildfromMain } = mainProcess;
forkChildfromMain();
// main.js
const fork = require('child_process').fork;
let cp = [];
function forkChildfromMain() {
createAndResize(4);
}
function createAndResize(num) {
return childResize(createChildProcess(num));
}
function createChildProcess(num) {
if(num <= 0) {
return cp;
} else {
let cf = fork('./resize.js');
cp.push(cf);
num -= 1;
return createChildProcess(num);
}
}
function childResize(list) {
if(list.length <=0) {
return true;
} else {
let child = list.shift();
child.on('message', function (msg) {
// logs 'Hello World' to the cmd console
console.log(msg);
});
child.send('Hello World');
setTimeout(function() {
childResize(list);
}, 1000);
}
}
exports.forkChildfromMain = forkChildfromMain;
// child.js
process.on('message', function(msg) {
// this console statement get never loged
// I think, I must integrate an icpModule
console.log(msg);
//process send msg back to main.js
process.send(msg);
})
Run Code Online (Sandbox Code Playgroud)
过时:现在的主要问题是,我认为电子“产生”新的子进程并且不分叉。因为,当我查看任务管理器时,我只看到一个来自 Electron 的实例。当我在节点环境中运行代码时,我看到有多个节点实例的分叉。
我更喜欢在多个节点实例中分叉子进程的原因是,我想要进行许多图像操作。因此,当我分叉子节点时,每个子节点都有自己的节点实例和内存等。我认为,当我只有一个实例向所有孩子共享内存和资源时,这会更高效。
第二个意外行为是,子项中的 console.log 语句未打印到我的 cmd 控制台。但这是较小的:)
编辑:在我更深入地分析我的任务管理器之后,我发现电子会像它应该的那样生成多个子进程。
| 归档时间: |
|
| 查看次数: |
4082 次 |
| 最近记录: |