2012-09-19 69 views

回答

0

我有很多问题,因为node.js并不真正“分叉”,它“产生”或“fork/execs”。当我将群集用于UDP服务器时,只有一个子进程会接收数据包,最后一个绑定。如果您只是“fork()”,则操作系统会将传入的数据包发送给每个孩子。如果您“spawn()”遇到文件/套接字句柄的继承权限问题,则必须设置选项等,并且基础node.js udp服务器可能没有应用这些选项。

我不得不编写自己的扩展,简单地称为底层OS fork(),并使其像普通分叉,网络服务器一样工作。

Windows没有fork(),所以这种方法不起作用,这可能是为什么node.js没有普通的普通花园变种fork()。这样做会使其不能移植到Windows。

1)创建一个目录,我称之为“util”。

2)将这两个文件放在该目录中。

-------------------这里切,命名以下 “util.cc” -------

#include <v8.h> //needed for extension infrastructure 
#include <node.h> //needed for extension infrastructure 

#include <iostream> // not part of extension infrastructure, just for the code I'm adding and only while developing to output debugging messages 

using namespace node; 
using namespace v8; 

// The following two functions are examples of the minimum required for a node.js  extension that does anything 

static Handle<Value> spoon(const Arguments& args) 
{ 
    pid_t rval = fork(); 
    if (rval < 0) 
    { 
     return ThrowException(Exception::Error(String::New("Unable to fork daemon, pid < 0."))); 
    } 
    Handle<Value> n = v8::Number::New(rval); 
    return n; 
} 

static Handle<Value> pid(const Arguments& args) 
{ 
    pid_t rval = getpid(); 
    Handle<Value> n = v8::Number::New(rval); 
    return n; 
} 

extern "C" void init(Handle<Object> target) 
{ 
    NODE_SET_METHOD(target, "fork", spoon); 
    NODE_SET_METHOD(target, "pid", pid); 
} 

- ------这里切下来,命名为下面的“wscript”-------

def set_options(opt): 
    opt.tool_options("compiler_cxx") 

def configure(conf): 
    conf.check_tool("compiler_cxx") 
    conf.check_tool("node_addon") 

def build(bld): 
    obj = bld.new_task_gen("cxx", "shlib", "node_addon") 
    obj.cxxflags = ["-g", "-D_FILE_OFFSET_BITS=64", "-D_LARGEFILE_SOURCE", "-Wall"] 
    obj.target = "util" 
    obj.source = "util.cc" 

---------结束切割,请给我们切刀---- -

3)运行“node-waf configure”

如果顺利的话,

4)运行“节点-WAF”

5)一个名为“打造”新目录将被创建,以及您的分机“建设/默认/ util.node”将一直创建。复制该内容并在节点程序中使用它:

var util = require(“util.node”);

var pid = util.fork();

还包含util.pid()函数,因为分叉后process.pid不能正常工作。它提供了父进程的pid。

我是一个初学者节点扩展编写器,所以如果这是一个天真的方法,哦,但它迄今为止服务得很好。任何改进,如“简化”将不胜感激。

+0

谢谢。 节点团队已解决此问题 –

+0

... udp-cluster-v0.8分支(https://github.com/StrongLoop/node/commits/udp-cluster-v0.8)并将其合并到主节点中。 –

0

此问题已在node.js v0.10中得到解决

+0

解释如何使用它的任何代码片段将是很好的 –