Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block the read system call

Tags:

c

linux

io

I don't understand how read() system blocks. I have created an empty file and trying to read using the read() system call. It returns 0.

fd = open("Demo.txt",O_RDONLY);
n = read(fd,&ch,10); // returns 0 

I am expecting read() to block indefinitely as there is no data in the file. Does read() consider EOF as a valid data and return immediately ? Is my understanding correct ?

like image 519
Gowtam Avatar asked Jan 15 '23 07:01

Gowtam


2 Answers

Yes, EOF will cause read() to return immediately, not block. When you reach EOF read() doesn't wait for more data to be written to the file; it returns 0 bytes immediately. Blocking does not come into play when reading from on-disk files, aside from the usually imperceptible delay when data on disk is read into memory.

It's more relevant when working with TTYs, sockets, and pipes. For instance, reading from stdin when stdin is connected to the terminal will block until the user types something. Reading from a socket will block if we haven't received data from the other side. Reading from a pipe will block until the program on the other side of the pipe writes something.

like image 173
John Kugelman Avatar answered Jan 16 '23 22:01

John Kugelman


Your understanding is correct. read() would block only when reading from a pipe or network socket that was connected.

like image 44
Jim Garrison Avatar answered Jan 16 '23 21:01

Jim Garrison