【问题标题】:Write to file descriptor of socket from bash child process in Node.js从 Node.js 中的 bash 子进程写入套接字的文件描述符
【发布时间】:2019-10-11 14:03:29
【问题描述】:

我有这个:

const net = require('net');
const cp = require('child_process');

const server = net.createServer(s => {

  const bash = cp.spawn('bash');

  s.on('data', d => {
     bash.stdin.write(`
      exec ${String(d)};
      echo 'write to socket s here';  // write to s here
    `);
  });


  bash.stdout.pipe(s, {end:false});
  bash.stderr.pipe(s, {end:false});


});

server.listen(4004);

有谁知道我如何从 bash 进程中写入套接字?我假设我必须以某种方式将文件描述符编号传递给 bash?如何获取套接字的文件描述符?我在控制台记录了套接字属性,但没有看到文件描述符。

类似这样的:

const fd = s.fd;

const bash = cp.spawn('bash', [], {
   env: Object.assign({}, process.env, {
       socketfd: fd
    })
});

然后

bash.stdin.write(`
    exec ${String(d)};
    echo "test" >&"$socketfd"
`)

【问题讨论】:

    标签: node.js shell sockets tcp file-descriptor


    【解决方案1】:

    所以我想出了如何获取套接字的文件描述符:

    const net = require('net');
    const cp = require('child_process');
    const fs = require('fs');
    
    const server = net.createServer(s => {
    
      const fd = s._handle.fd;  // file descriptor
    
      const bash = cp.spawn('bash', [], {
        env: Object.assign({}, process.env, {
          socket_fd: fd
        })
      });
    
    
    
      s.setEncoding('utf8');
    
      s.on('data', d => {
    
        if(String(d).trim() === '∆∆∆'){
          bash.stdout.write('\n$$$');
          return;
        }
    
        d = String(d);
    
         bash.stdin.write(`
             set +e;
    
             ${d}
             echo "file descriptor: $socket_fd"
             echo "∆∆∆\n" >&$socket_fd
    
         `);
      });
    
    
      bash.stdout.pipe(s, {end:false});
      bash.stderr.pipe(s, {end:false});
    
    
    });
    
    server.listen(4004);
    

    但是当我使用 nc localhost 4004 连接到这个并运行简单的 echo 命令时,我得到了这个:

    echo foo
    foo
    file descriptor: 22
    bash: line 8: 1: Bad file descriptor
    

    子进程应该从父进程继承文件描述符,所以我不明白为什么它会是“坏文件描述符”??

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-25
      • 1970-01-01
      • 2019-06-20
      • 2019-04-17
      • 1970-01-01
      • 2012-11-02
      相关资源
      最近更新 更多