简体   繁体   English

如何使用 inotify 来判断一个命名的 pipe 何时打开?

[英]How can I use inotify to tell when a named pipe is opened?

The overall goal is I am trying to make a named pipe that when read is a PNG file of the current framebuffer.总体目标是我试图制作一个名为 pipe 的文件,读取时它是当前帧缓冲区的 PNG 文件。 With various snippets cobbled together from online like the PNG creator from Andrew Duncan I have something that can create and write the PNG OK but the trick is I need to not write the pipe until someone reads it so that the image is current and not back when the pipe was opened.从网上拼凑出各种片段,比如 Andrew Duncan 的 PNG 创建者,我有一些东西可以创建和编写 PNG pipe 已打开。

It seems like I should be able to use inotify_add_watch( fd, filename, IN_OPEN | IN_ACCESS ) to tell when someone opens the file to start reading and then I open it for writing and send my PNG file data and then close the file.似乎我应该能够使用inotify_add_watch( fd, filename, IN_OPEN | IN_ACCESS )来判断何时有人打开文件开始读取,然后我打开它进行写入并发送我的 PNG 文件数据,然后关闭文件。

The pipe is getting created but I am not getting the watch event when I try to read from the file (cat fbpipe.png > pipefile.png). pipe 正在创建,但是当我尝试从文件中读取时没有收到监视事件(cat fbpipe.png > pipefile.png)。 It is blocking at the first read() of watch events.它在 watch 事件的第一次 read() 时被阻塞。

Relevant code snippets:相关代码片段:

// Creating the named file(FIFO)
// mkfifo(<pathname>, <permission>)
mkfifo(filename, 0666);

/*creating the INOTIFY instance*/
fd = inotify_init();

wd = inotify_add_watch( fd, filename, IN_OPEN | IN_ACCESS );

/*read to determine the event change happens. Actually this read blocks until the change event occurs*/ 

length = read( fd, buffer, EVENT_BUF_LEN ); 

/*checking for error*/
if ( length < 0 ) {
   perror( "read" );
   return -1;
 }

  //  READ MY FRAMEBUFFER AND THEN WRITE THE DATA:

  FILE* file;
  file = fopen(filename, "wb" );

  fwrite(buffer, 1, buffersize, file);
  fclose(file);

You don't need inotify for this.您不需要为此进行 inotify。

If you open a named pipe for writing, the open system call will block until some process opens the named pipe for reading.如果您打开名为 pipe 进行写入,则 open 系统调用将阻塞,直到某个进程打开名为 pipe 进行读取。 That's basically what you want.这基本上就是你想要的。 When the open returns, you know there's a client waiting to read.当打开返回时,您知道有一个客户在等待阅读。

Similarly, if you open the pipe for reading, the open will block until some process opens the pipe for writing.同样,如果您打开 pipe 进行读取,则打开将阻塞,直到某个进程打开 pipe 进行写入。 Furthermore, a read will block until the writer actually writes data.此外,读取将阻塞,直到写入器实际写入数据。 So the named pipe basically takes care of synchronisation.所以命名的 pipe 基本上负责同步。

That makes for a very simple client-server architecture, but it only works if you never have two concurrent clients.这构成了一个非常简单的客户端-服务器架构,但它仅在您没有两个并发客户端的情况下才有效。 For a more general approach, use Unix domain sockets.对于更通用的方法,使用 Unix 域 sockets。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM