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


where ch is the channel variable.



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?

I didn’t try that so far.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.