Skip to content
Advertisement

Is checking the existence of file or folder blocking or non-blocking?

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 access system 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, and lstat can block for the same reasons open can (discussed below). fstat is not guaranteed not to block but usually it’s ok to assume it won’t.

  • open and opendir can block, even if you use O_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 open operation. 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 when connect returns −1 with errno set to EINPROGRESS, you already know the socket descriptor number and you can select on it. If open were to give you EINPROGRESS you wouldn’t have a file descriptor to select on.

  • readdir can block for all the same reasons plain old read can 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 the DIR abstraction gets in the way of requesting non-blocking I/O in the normal fashion.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement