[In progress] 父子进程通信,node python进程通信,测试代码
father.js
1 const spawn = require('child_process').spawn; 2 const ipcOutgoingFd = 3; 3 const ipcIncomingFd = 4; 4 let stdio = ['ignore', 'pipe', process.stderr, 'pipe', 'pipe']; 5 6 //const proc = spawn('python child.py', [], { stdio, shell: true }); 7 const proc = spawn('node', ['child.js'], { stdio, shell: true }); 8 // record its sent/received commands on exit 9 10 proc.on('exit', (code) => { 11 if (code == 0) { 12 let str = proc.stdout.read().toString(); 13 if(str.search("\r\n")!=-1){ 14 sentCommands = str.split("\r\n"); 15 } 16 else{ 17 sentCommands = str.split('\n'); 18 } 19 console.log(sentCommands); 20 console.log("OK"); 21 } 22 }); 23 24 // create IPC interface 25 let outgoingStream = proc.stdio[ipcOutgoingFd]; 26 let incomingStream = proc.stdio[ipcIncomingFd]; 27 28 // Command #1: ok 29 outgoingStream.write(12); 30 31 // Command #2: ok 32
child.js
1 const ipcOutgoingFd = 4; 2 var ipcIncomingFd = 3; 3 const fs = require('fs'); 4 5 6 var bufferSize=256 , 7 chunkSize=128, 8 buffer= Buffer.alloc(bufferSize), 9 bytesRead = 0; 10 fs.read(ipcIncomingFd, buffer, bytesRead, chunkSize, bytesRead, testCallback); 11 /* while (bytesRead < bufferSize) { 12 if ((bytesRead + chunkSize) > bufferSize) { 13 chunkSize = (bufferSize - bytesRead); 14 } 15 16 fs.read(ipcIncomingFd, buffer, bytesRead, chunkSize, bytesRead, testCallback); 17 bytesRead += chunkSize; 18 } */ 19 console.log("receive"); 20 console.log(buffer.toString('utf8')); 21 22 var testCallback = function(err, bytesRead, buffer){ 23 console.log('err : ' + err); 24 };
child.py
1 _in_file = open(3, 'rb') 2 _out_file = open(4, 'wb') 3 4 def send(command, data): 5 command = command.encode('utf8') 6 data = data.encode('utf8') 7 msg = b'%b%06d%b' % (command, len(data), data) 8 _out_file.write(msg) 9 _out_file.flush() 10 11 12 def receive(): 13 header = _in_file.read(1024) 14 data = header.decode('utf8') 15 return data 16 17 18 print(receive()) 19 20 send('KI', '') 21 22 print(receive()) 23 24 send('KI', 'hello') 25 26 send('KI', '世界')