child process

2017-06-04  本文已影响87人  MoonBall

用 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 的话还需要自己对子程序的输出进行组装。

上一篇 下一篇

猜你喜欢

热点阅读