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

查看:725
本文介绍了在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.

这是我用来生成 的代码进程(文件 ./ 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 文件:

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天全站免登陆