在 Electron 中生成一个子进程 [英] Spawn a child process in Electron

查看:115
本文介绍了在 Electron 中生成一个子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Node v6.2.2 和 Electron v1.2.5.

I'm using Node v6.2.2 and Electron v1.2.5.

我有一个基于 Electron 构建的小型应用程序,现在我需要 fork 进程以在另一个节点进程中运行一些长时间运行的任务,但它似乎不起作用,当我查看 ChildProcess 对象时,我可以看到参数 spawnargs[0] 是用电子可执行文件而不是节点初始化的,所以我所做的是我尝试使用 spawn,但据我所知,它不起作用.

I have a small application that I've built on top of Electron and now I need to fork the process to run some long running task in another node process but it doesn't seems to work, when I'm looking at the ChildProcess object I can see that in the argument spawnargs[0] is initialized with the electron executable instead of node so what I did is I've tried to use spawn instead but it's not working as far as I can tell.

这是我用来spawn 进程的代码(lives 在文件 ./modules/tester.js 中):

Here is the code I'm using to spawn the process (lives inside the file ./modules/tester.js):

const {spawn} = require('child_process');

var child = spawn("node", ["worker.js"], { stdio: ['inherit', 'inherit', 'inherit', 'ipc'] });

const self = {};

self.start = () => {
    console.log("start");
    child.send("ping");
};

这是我用于 worker.js 文件的代码:

And here is the code I'm using for my worker.js file:

process.on("message", (data) => {
    console.log(data);
    console.log("pong");
});

最后这就是我的消费方式.

And finally this is how I'm consuming it.

const {app} = require("electron");

const tester = require("./modules/tester");

app.on("ready", () => {
    tester.start();
});

也许我做错了,但我不这么认为,因为当我使用 nodejs 时,它似乎工作得很好.

Maybe I'm doing it wrong but I don't think so because when I'm using nodejs it seems to work just fine.

我尝试了很多示例,但似乎没有一个有效,另一种可能是我需要在 Electron 中做一些特殊的事情才能使其工作,但我不知道.

I've tried many examples but none of them seems to work, another possibility is that I need to do something special in Electron for it to work but I don't know.

推荐答案

终于解决了.

我解决这个问题的方法正好相反,NodeJS 在生产机器上可用,所以我只写了一个 start.js 脚本,它基本上产生一个子进程来运行 Electron 和父进程我正在运行这个长时间运行的任务,最后我使用 IPC 在两个进程之间进行通信.

The way I solved this is doing exactly the reverse, NodeJS is available on the production machines so I just wrote a start.js script that basically spawn a child process to run Electron and on the parent process I'm running this long running task and finally I'm using IPC to communicate between the two processes.

这篇关于在 Electron 中生成一个子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆