user2654735
user2654735

Reputation: 323

C++ catch if file closed by another program while polling

I have a program that is polling a file for changes. However, if I open another Linux console and delete the file that it is polling, while it is polling, the program will continue to poll forever. Is there a way to catch this?

struct pollfd pollFileDescriptor;
pollFileDescriptor.fd = GetFileDescriptor(...returns fd
pollFileDescriptor.events = POLLPRI | POLLERR | POLLNVAL | POLLHUP;

if (poll(&pollFileDescriptor, 1, -1) > 0)
{
     ...
}

I have tried all the various events, checking them against revents, as well as just putting a printf within the polling if statement just to see if it enters the code block with no luck. It seems to hang on poll

Upvotes: 3

Views: 300

Answers (1)

StenSoft
StenSoft

Reputation: 9609

Deleting the file removes its reference from the filesystem. But file descriptor is another reference. As long as there is any reference, the file is not actually destroyed so no change to the file data that can be reported to the polling happened. (The file can also be hardlinked, that is another reference whose deletion would not be reported to you.)

You can watch the directory for changes. Linux provides inotify and dnotify for that.

Upvotes: 2

Related Questions