【发布时间】:2017-03-08 10:11:12
【问题描述】:
在我的项目中,我需要创建一个子进程并通过IPC与它通信,同时这个子进程必须以root身份运行。所以我用cp.spawn('sudo', ...)和IPC通道,但是我发现process.send方法是undefined。
代码如下:
文件:parent.js
'use strict'
const cp = require('child_process')
const path = require('path')
const script = path.join(__dirname, 'child.js')
let child = cp.spawn('sudo', [process.execPath, script], {
stdio: ['inherit', 'inherit', 'inherit', 'ipc']
})
child.on('message', msg => {
console.log('message> ', msg)
})
console.log('parent> parent run!')
文件:child.js
'use strict'
console.log('child> child run!')
process.send('hahaha')
运行node parent.js
parent> parent run!
Password:
child> child run!
/Users/zoujie.wzj/workbench/child.js:5
process.send('hahaha')
^
TypeError: process.send is not a function
at Object.<anonymous> (/Users/zoujie.wzj/workbench/child.js:5:9)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
at bootstrap_node.js:509:3
更新:在我将 cp.spawn('sudo', ...) 替换为 cp.spawn(process.execPath, ...) 后,程序将运行:
parent> parent run!
child> child run!
message> hahaha
有人知道为什么 IPC 不能与 sudo 一起使用吗?
【问题讨论】: