简体   繁体   中英

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. 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.

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.

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). It is blocking at the first read() of watch events.

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.

If you open a named pipe for writing, the open system call will block until some process opens the named pipe for reading. 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. Furthermore, a read will block until the writer actually writes data. So the named pipe basically takes care of synchronisation.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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