Is checking the existence of file or folder blocking or non-blocking?
access( fname, F_OK ) // blocking ?
Is opening dir / file blocking or non-blocking?
opendir(dir); // blocking? open(fd..); // blocking?
Is list dir blocking or non-blocking?
readdir // blocking?
By block, I mean take a long time to return.
Advertisement
Answer
(I assume that you mean “block” in the sense that it’s usually used in Unix manpages and related documentation: that is, you are asking whether these operations can involve the calling process waiting for an extended period for I/O to complete. If this is not what you mean please edit your question to clarify.)
The short answer is that all of these system calls can potentially block.
The long answer:
checking for the existence of a file or folder: never do this, it introduces a TOCTOU race condition into your program. In 20 years of Unix system programming I have literally never encountered a situation where the
accesssystem call was the right thing to use. Instead just go ahead and attempt to open the file, enter the directory, whatever, and check whether that failed.Having said that,
access,stat, andlstatcan block for the same reasonsopencan (discussed below).fstatis not guaranteed not to block but usually it’s ok to assume it won’t.openandopendircan block, even if you useO_NONBLOCK. The most common case where this happens is when the file or directory you’re trying to open is on a remote file system, so finding out whether the file exists and you’re allowed to access it involves sending packets over the network.There isn’t any way around this within the POSIX API because there’s no way to represent an in-progress
openoperation. The networking API separates the creation of a socket (socket, which can’t block) from the request to connect it to a remote peer (connect, which can), so whenconnectreturns −1 with errno set toEINPROGRESS, you already know the socket descriptor number and you canselecton it. Ifopenwere to give youEINPROGRESSyou wouldn’t have a file descriptor toselecton.readdircan block for all the same reasons plain oldreadcan block. Again, the most common case where you’d notice is when the directory is on a remote file system. The problem in this case is theDIRabstraction gets in the way of requesting non-blocking I/O in the normal fashion.