NodeJS —使用函数字符串而不是文件的Fork子进程

编程入门 行业动态 更新时间:2024-10-12 18:23:10
本文介绍了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子进程

本文发布于:2023-10-09 05:36:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474853.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   函数   而不是   进程   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!