美文网首页
child process

child process

作者: MoonBall | 来源:发表于2017-06-04 14:09 被阅读87次

用 exec* 的方法时需注意:它们都是有 maxBuffer 限制的,因为会缓存输出。

options - stdio

  1. 如果把多个 child 的 stdin 重定向到父进程,那么父进程控制台的输入将随机给到某一个子进程中,而不是父进程控制台的一次输入会给到每一个子进程
child = cp.spawn('grep', ['2333'], {
  stdio: [0, 1],
})

child2 = cp.spawn('grep', ['abbb'], {
  stdio: [0, 'pipe'],
})

child2.stdout.on('data', data => {
  console.log('===================data=====================', data.toString())
})
  1. pipe 参数含义是:Node 创建了一个 pipe,且传递给子进程的 fd 是该参数所在 stdio 中的数组下标。
// parent.js
const cp = require('child_process')
const child = cp.spawn('./child.js', [], {
  stdio: [0, 1, 2, 'pipe'],
})

// 在子进程中就可以使用文件描述符 3,来和父进程交流
child.stdio[3].on('data', data => console.log('parent receive: ', data.toString()))
// child.js
#!/Users/gangc/.nvm/versions/node/v4.8.3/bin/node

const fs = require('fs')
const out = fs.createWriteStream(null, { fd: 3 });
out.write('我是孩子\n')
  1. 可以在父子之间设置更多的文件描述符用于父子间交流,例如:
// parent.js
const cp = require('child_process')
const fs = require('fs')
const saveFile = fs.openSync('./save.txt', 'a')

const child = cp.spawn('./child.js', [], {
  stdio: [0, 1, 2, 'pipe', saveFile],
})
// child.js
#!/Users/gangc/.nvm/versions/node/v4.8.3/bin/node

const fs = require('fs')
const out = fs.createWriteStream(null, { fd: 4 });
out.write('我是孩子\n')
// save.text 就会添加一行 我是孩子

同步和异步的区别

  1. 同步方法返回的是子进程执行完后的结果,异步方法返回的是 Class: ChildProcess 的实例。
  2. 同步方法 execSyncexecFileSync 没有回调。
  3. 同步方法特有的的 options.input 只有在子进程的 stdin 为 'pipe' 时才会被使用。

execFile 和 spawn 的区别

execFile 有回调,如果只关心子程序最后的输出结果的话,使用它更简单。而使用 spawn 的话还需要自己对子程序的输出进行组装。

相关文章

  • node中执行shell命令

    //使用插件child_process let process = require(‘child_process’...

  • node一些模块

    child_process模块 通过child_process模块创建子进程 childProcess.exec(...

  • Nodejs child_process 模块

    child_process 用户调用层 exec child_process.exec(command[, opt...

  • 详解node多进程child_process用法及原理

    child_process用法 child_process的api: 异步api:exec(cmd, option...

  • Nodejs cluster 模块

    cluster 和 child_process 模块子进程的区别 child_process 执行 shell 命...

  • child process

    用 exec* 的方法时需注意:它们都是有 maxBuffer 限制的,因为会缓存输出。 options - st...

  • Node.js(多进程)

    Node 提供了 child_process 模块来创建子进程,方法有: exec - child_process...

  • child_process

    在使用 child_process 模块中的 exec 、execFile、spawnSync、execFileS...

  • child_process

    目录 进程 线程 Node.js的进程控制 Node.js的线程控制 进程 Process 场景 notepad....

  • child_process

    child_process 使用目的 子进程的运行结果储存在系统缓存之中(最大200Kb) 等到子进程运行结束以后...

网友评论

      本文标题:child process

      本文链接:https://www.haomeiwen.com/subject/gnbvfxtx.html