3

I have a problem at present when calling read() like this:

unsigned char byData[1024] = {0};
ssize_t len = read(fd, byData, sizeof(byData));

where fd is the file descriptor.

read() is blocking which is not what I want. Is there a simple way to set read to non-blocking or time out? The code is used with inotify.

Thanks for any help.

Smithy
  • 1,157
  • 3
  • 11
  • 18
  • 1
    See http://cr.yp.to/unix/nonblock.html (in short: alter the fd as in the answers below, not read()) – loreb Jul 23 '14 at 16:56
  • Possible duplicate of [Non-blocking call for reading descriptor](https://stackoverflow.com/questions/5616092/non-blocking-call-for-reading-descriptor) – Ben Stern Jan 29 '18 at 01:20

4 Answers4

5

You cannot make such system calls non-blocking; rather, you can make the file descriptor they work on non-blocking

fcntl(fd, F_SETFL, O_NONBLOCK) 

or

int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK);

if you need to add O_NONBLOCK and preserve the previously set flags.

That way read will not block. If you want to set a timeout, use select or poll

fd_set fds; 
FD_ZERO(&fds);
FD_SET(fd, &fds);

struct timeval t = {/*seconds*/, /*microseconds*/};
select(fd + 1, &fds, NULL, NULL, &t);

The error handling and following work(select will overwrite both fds and t) is left to you.

edmz
  • 8,220
  • 2
  • 26
  • 45
3

You can use poll on the file descriptor to know when there is data to read. And then, call read().

# Poll definition
int poll(struct pollfd *fds, nfds_t nfds, int timeout);

as you can see you can set a timeout. This is usefull for situations where the file can' t be opened with the O_NONBLOCK flag, or you aren't calling open() at all.

Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
2

Call the open(fd, ...) with O_NONBLOCK flag.

From open() man page:

O_NONBLOCK or O_NDELAY: When possible, the file is opened in nonblocking mode. Neither the open() nor any subsequent operations on the file descriptor which is returned will cause the calling process to wait. For the handling of FIFOs (named pipes), see also fifo(7). For a discussion of the effect of O_NONBLOCK in conjunction with mandatory file locks and with file leases, see fcntl(2).

Alper
  • 12,860
  • 2
  • 31
  • 41
  • Unfortunately the code I'm using doesn't call open. This is the code : s_MyRes.wd = inotify_add_watch (s_MyRes.fd, ctx.szFolder.c_str(), ctx.uMask); After this, read() is called, which is blocking. – Smithy Jul 23 '14 at 14:53
0

This topic has already been described here.

Also you can try timer or thread. Here is the example of thread

#include <pthread.h>

unsigned char byData[1024] = {0};
ssize_t len;

void *thread(arguments) {
  while (1) {
    len = read(fd, byData, sizeof(byData));
  }

int main(){
  pthread_t pth;
  pthread_create(&pth, NULL, thread, arguments);
}
George Sovetov
  • 4,942
  • 5
  • 36
  • 57
PaulPonomarev
  • 355
  • 1
  • 4
  • 20