繁体   English   中英

与 spawn() 子进程通信?

[英]communicating with a spawn() child process?

我正在尝试使用spawn()和它自己的终端创建一个子进程

父.js:

const spawn = require('child_process').spawn;

console.log('started parent process...'); //this should be printed in the parent terminal

const child = spawn('start node', [`child.js`], {
    cwd:__dirname,
    shell: true,
    stdio: [null, null, null, 'pipe']
});

const Name = 'general kenobi';

child.stdio[3].write(Name);

child.stdio[3].on('data', (data) => {
    console.log('data=>', data.toString());
    child.kill();
});

child.js:

console.log('started child process...');

(async()=>{
    await new Promise(r=>setTimeout(r,3000));

    try{
        let net = require('net');
        let pipe = new net.Socket({ fd: 3 });

        pipe.on('data',(data)=>{
            pipe.write(`hello there ${data}`);
        });
    }catch(err){console.log(err)}
    await new Promise(r => setTimeout(r, 3000));
})();

预期的数据应该是data=> hello there general kenobi但它在子终端中给出了这个错误

 throw new ERR_INVALID_FD_TYPE(type); ^ TypeError [ERR_INVALID_FD_TYPE]: Unsupported fd type: UNKNOWN at new NodeError (node:internal/errors:371:5) at createHandle (node:net:152:9) at new Socket (node:net:340:20) at Object.<anonymous> (C:\\...\\parent.js:4:12) at Module._compile (node:internal/modules/cjs/loader:1101:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) at Module.load (node:internal/modules/cjs/loader:981:32) at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:17:47 { code: 'ERR_INVALID_FD_TYPE' }

我找不到很多参考资料,所以我用这个视频作为指南

(请在回答时尽量避免第三者包)

删除shell: true并将命令更改为parent.js文件中的“节点”。

const child = spawn('node', [`child.js`], {
cwd:__dirname,
stdio: [null, null, null, 'pipe']
});

在添加shell: true , spawn 将使用系统的 shell来运行该命令,而不是使用 spawn 本身。 通常,我建议使用纯 spawn 而不使用 shell。 不直接接触壳体和管道数据问题将降低风险。

首先,正如评论中提到的其他人, 'start node'应该只是'node' 我比较了您链接的视频,发现如果您将'node'spawn参数)更改为'process.execPath'它会神奇地起作用!

我目前不确定为什么会这样?? 我猜这可能只是一个错误! 现在,我想也许只有修复才能帮助您。

如果您记录process.execPath并且正如文档中提到的那样,它会返回节点的绝对路径并解析所有符号链接。 这可能是 spawn 的问题。

此外,如果您在选项中使用shell: true ,则子进程不会被杀死。 我不知道这是否是您的预期行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM