NodeJS —使用函数字符串而不是文件的Fork子进程 [英] NodeJS — Fork Child Process with function string instead of file

查看:107
本文介绍了NodeJS —使用函数字符串而不是文件的Fork子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了文档,它只是描述提供子模块文件的文件路径。

I've looked at the documentation for the fork method, and it only describes providing a file path to the child module file.

有人知道(是否有可能)直接(而不是通过文件)而不是通过文件传递子模块吗?重点是,我想动态生成模块,然后使用它创建一个子进程。

Does anyone know if it is possible (and undocumented) to pass in the child module directly instead of via a file? Point being, I would like to dynamically generate the module, then create a child process with it.

推荐答案

这是不可能的- fork()创建一个完全不同的过程,该过程不与其父进程共享上下文或变量。

This would not be possible -- fork() creates a completely different process that do not share context or variables with its parent process.

一种选择是在派生进程中生成模块,并通过命令行或临时文件将必要的参数传递给它,以便您的孩子可以运行:

One option you have would be to generate the module inside the forked process, and passing it the necessary arguments via the command line or via a temporary file so that your child can run:

const data = 'something;
var childProcess = child_process.fork(__dirname + '/worker', [something]);

然后您可以使用 process.argv [2]从子级访问参数]

该方法的局限性在于,您只能传递数据类型,而不能在以下情况下从工作人员调用任何函数:它的父母。您需要在子代与父代之间进行某种形式的RPC,这超出了此答案的范围。

One limitation of that approach is that you can only pass data types, and cannot call from the worker any function in the context of its parent. You would need for that some kind of RPC between the child and the parent, which is beyond the scope of this answer.

这篇关于NodeJS —使用函数字符串而不是文件的Fork子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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