2

I am writing a little lua script that read data from a FIFO.for this I use the classical:

f=assert(io.open("/tmp/myfifo")
f:read()

When the fifo is empty/not feeded, my script block. Is there a way to avoid this ?.

cedlemo
  • 3,205
  • 3
  • 32
  • 50
  • Strange, here it simply returns `nil` when there's nothing left in the fifo. – jpjacobs Oct 19 '11 at 11:25
  • It seems that there is blocking read access and non blocking read access on fifo on Linux. The fifo that my script try to read is generated by mpd. If I use cat on the empty fifo, the cat command block until there is data in the fifo. – cedlemo Oct 19 '11 at 11:58
  • Ah, well Now I see. It's the io.open that blocks, not the reading. – jpjacobs Oct 19 '11 at 12:05
  • Hum not really, I have checked if I just use f=io.open("/tmp/myfifo"); f:close the script doesn't block – cedlemo Oct 19 '11 at 12:10
  • I think its simply impossible with the basic Lua functions I tried [this post about fopen](http://stackoverflow.com/questions/580013/how-do-i-perform-a-non-blocking-fopen-on-a-named-pipe-mkfifo) setting the mode r+ did the io.open unblocking, but made the read blocking :p – jpjacobs Oct 19 '11 at 12:17
  • Ok so, is there a solution with something like threads? one thread which launch read action and one thread which check for timeout and end the other thread. I tried coroutine but it doesn't seem to be paralell execution.. – cedlemo Oct 19 '11 at 14:52

1 Answers1

3

There is no straight forward Lua-only method I guess. With luajit http://luajit.org/ (which provides ffi) it is possible:

 local ffi = require'ffi'

 --- The libc functions used by this process.
 ffi.cdef[[
      int open(const char* pathname, int flags);
      int close(int fd);
      int read(int fd, void* buf, size_t count);
 ]]   
 local O_NONBLOCK = 2048
 local chunk_size = 4096
 local buffer = ffi.new('uint8_t[?]',chunk_size)
 local fd = ffi.C.open('mypipe',O_NONBLOCK)     
 local nbytes = ffi.C.read(fd,buffer,chunksize)
 -- .. process data
lipp
  • 5,586
  • 1
  • 21
  • 32
  • With [Tarantool](https://Tarantool.io) which provides the built in [fio.open()](https://Tarantool.io/en/doc/2.1/reference/reference_lua/fio/#fio-open) there's `O_NONBLOCK` flag. – yds Mar 13 '19 at 19:44