开发者

non-blocking file openat()

开发者 https://www.devze.com 2023-01-11 04:31 出处:网络
I would like to implement a multi-threaded, non-blocking file open.Ideally, the desired solution would be to make a call to open() & have it return immediately, and do something like register a ca

I would like to implement a multi-threaded, non-blocking file open. Ideally, the desired solution would be to make a call to open() & have it return immediately, and do something like register a callback to be called (or handle a signal, or conditional variable) when the open() operation is actually complete. To that end, I wrote a little test driver that creates multiple simultaneous threads and tries to open the same file. I would have hoped the return from openat() to be an invalid file descriptor, with an errno == EAGAIN, but the open call seems to always block until the open completes successfully.

Is there an implementation of this approach for a non-blocking open()?

Thanks开发者_运维知识库 in advance.

Reference Thread Code:

void* OpenHandler(void* args)
{

// Declarations removed

   Dir = "/SomeDir";

   if ((DirFd = open(Dir, O_RDONLY )) < 0) {
      printf("********Error opening Directory*******\n");
      return NULL;
   }


   do {

      FileFd = openat(DirFd, &FileName[DirLen], O_RDONLY | O_NONBLOCK);

      /* If open failed */
      if (FileFd == -1) {
         if (errno == EAGAIN)
            printf("Open would block\n");
         else {
            printf("Open failed\n");
            pthread_exit(NULL);
         }
      }
      else
         Opened = 1;

   } while (!Opened);

   pthread_exit(NULL);
}


open() and openat() always fully resolve the open request in one shot (normally, this doesn't need to sleep, but it can if directory entries need to be brought in from disk or over the network).

To do what you want, you'll have to build a thread pool of file-opening threads, that perform the open() on behalf of the thread you want to continue working and notify it when the open is complete. Unless you're opening a lot of files on very slow network filesystems, I doubt the juice will be worth the squeeze.

0

精彩评论

暂无评论...
验证码 换一张
取 消