#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/event.h>
#include <fcntl.h>
int main()
{
struct kevent ke;
off_t nread = 0;
int kq = kqueue();
int fd = open("filename", O_RDONLY | O_NONBLOCK);
EV_SET(&ke, fd, EVFILT_READ, EV_ADD, 0, 0, 0);
kevent(kq, &ke, 1, NULL, 0, NULL);
while (1)
{
memset(&ke, 0, sizeof(struct kevent));
if (kevent(kq, NULL, 0, &ke, 1, NULL) == -1)
{
perror("kevent");
exit(1);
}
if (ke.flags & EV_EOF)
{
printf("end of file!\n");
exit(1);
}
char buf[1024];
int n = read(ke.ident, buf, 1024);
if (n <= 0)
{
perror("read");
exit(1);
}
nread += n;
printf("nread: %lld\n", nread);
}
return 0;
}
while (1)
{
char buf[64];
int n;
unsigned int left;
if (kevent(kq, NULL, 0, &ke, 1, NULL) == -1)
err(EXIT_FAILURE, "kevent");
if( ke.flags & EV_ERROR )
errc(EXIT_FAILURE, ev.data, "kevent");
if (ke.flags & EV_EOF)
{
printf("premature end of file!\n");
break;
}
n = read(ke.ident, buf, sizeof(buf));
if (n <= 0)
{
err(EX_FAILURE, "read");
}
nread += n;
printf("nread: %lld\n", nread);
left = (unsigned)ke.data;
if( left <= sizeof(buf) )
break; /* At EOF */
}