How to check if pipe is empty

How can I check if a pipe is empty without reading pipe and getting blocked ?

Hi @Thoma-s,

What is a pipe in this context?

If you mean channel, the number of elements in a buffered channel can be determined by calling

len(ch)

where ch is the channel variable.

Call

cap(ch)

to get the total size of the channel.

During reading, you can check the channel status through an extra parameter. If you receive data from a channel in this way:

value, ok := <-ch

then the ok variable contains the current channel status.

ok is true on successful reads. ok turns false after the sender closes the channel and the last remaining element has been read. After that, the channel continues to emit (zero, false), where zero is the zero value of the channel’s element type.

Hi christophberger,

I am opening a pipe:

r, w, err := os.Pipe

if a read the pipe, f.i.
nc, err := r.Read(make([]byte, 1024))

I get blocked if the pipe is empty.
I would like to know if it is possible, to check before reading if the pipe is empty.

Oh, sorry, my fault.

Did you try wrapping r into a bufio.Reader and using its Peek() method?

Hi,
I didn’t try that so far.