How do you construct a read-write pipe with lua?

后端 未结 7 1052
甜味超标
甜味超标 2020-12-09 04:26

I\'d like to do the equivalent of:

foo=$(echo \"$foo\"|someprogram)

within lua -- ie, I\'ve got a variable containing a bunch of text, and

7条回答
  •  失恋的感觉
    2020-12-09 05:12

    Aha, a possibly better solution:

    require('posix')
    require('os')
    require('io')
    
    function splat_popen(data,cmd)
       rd,wr = posix.pipe()
       io.flush()
       child = posix.fork()
       if child == 0 then
          rd:close()
          wr:write(data)
          io.flush()
          os.exit(1)
       end
       wr:close()
    
       rd2,wr2 = posix.pipe()
       io.flush()
       child2 = posix.fork()
       if child2 == 0 then
          rd2:close()
          posix.dup(rd,io.stdin)
          posix.dup(wr2,io.stdout)
          posix.exec(cmd)
          os.exit(2)
       end
       wr2:close()
       rd:close()
    
       y = rd2:read("*a")
       rd2:close()
    
       posix.wait(child2)
       posix.wait(child)
    
       return y
    end
    
    munged=splat_popen("hello, world","/usr/games/rot13")
    print("munged: "..munged.." !")
    

提交回复
热议问题