[nixio] add timerfd and numexp functions to get timer notifications via fds

This commit is contained in:
Bart Van Der Meerssche 2011-01-24 14:15:30 +01:00
parent abaefa00ad
commit 3da4eee152
2 changed files with 67 additions and 0 deletions

View File

@ -223,6 +223,22 @@ static int nixio_file_read(lua_State *L) {
} }
} }
static int nixio_file_numexp(lua_State *L) {
int fd = nixio__checkfd(L, 1);
uint64_t numexp;
int readc;
do {
readc = read(fd, &numexp, sizeof(uint64_t));
} while (readc == -1 && errno == EINTR);
if (readc < 0) {
return nixio__perror(L);
} else {
lua_pushnumber(L, (lua_Number)numexp);
return 1;
}
}
static int nixio_file_seek(lua_State *L) { static int nixio_file_seek(lua_State *L) {
int fd = nixio__checkfd(L, 1); int fd = nixio__checkfd(L, 1);
@ -350,6 +366,7 @@ static int nixio_file__tostring(lua_State *L) {
static const luaL_reg M[] = { static const luaL_reg M[] = {
{"write", nixio_file_write}, {"write", nixio_file_write},
{"read", nixio_file_read}, {"read", nixio_file_read},
{"numexp", nixio_file_numexp},
{"tell", nixio_file_tell}, {"tell", nixio_file_tell},
{"seek", nixio_file_seek}, {"seek", nixio_file_seek},
{"stat", nixio_file_stat}, {"stat", nixio_file_stat},

View File

@ -195,8 +195,57 @@ static int nixio_poll(lua_State *L) {
#ifdef __linux__ #ifdef __linux__
#include <stdint.h>
#include <unistd.h> #include <unistd.h>
#include <fcntl.h> #include <fcntl.h>
#include <sys/timerfd.h>
static int nixio_timerfd(lua_State *L) {
struct itimerspec its;
its.it_value.tv_sec = (time_t)luaL_optinteger(L, 1, 0);
its.it_value.tv_nsec = (long)luaL_optinteger(L, 2, 0);
its.it_interval.tv_sec = (time_t)luaL_optinteger(L, 3, 0);
its.it_interval.tv_nsec = (long)luaL_optinteger(L, 4, 0);
/* Create a timer object and associated fd */
int fd = timerfd_create(CLOCK_REALTIME, 0);
if (fd == -1) {
return nixio__perror(L);
}
/* Workaround for TFD_NONBLOCK 'invalid argument' in uClibc*/
int flags;
flags = fcntl(fd, F_GETFL);
if (flags == -1)
return nixio__perror(L);
flags |= O_NONBLOCK;
if(fcntl(fd, F_SETFL, flags) == -1)
return nixio__perror(L);
/* Arm the timer */
if (timerfd_settime(fd, 0, &its ,NULL) == -1) {
close(fd);
return nixio__perror(L);
}
/* Create a userdatum for fd */
int *udata = lua_newuserdata(L, sizeof(int));
if (!udata) {
close(fd);
return luaL_error(L, "out of memory");
}
*udata = fd;
luaL_getmetatable(L, NIXIO_FILE_META);
lua_setmetatable(L, -2);
return 1;
}
#include <signal.h> #include <signal.h>
#include <sys/signalfd.h> #include <sys/signalfd.h>
@ -263,6 +312,7 @@ static int nixio_setitimerfd(lua_State *L) {
/* module table */ /* module table */
static const luaL_reg R[] = { static const luaL_reg R[] = {
#ifdef __linux__ #ifdef __linux__
{"timerfd", nixio_timerfd},
{"setitimerfd", nixio_setitimerfd}, {"setitimerfd", nixio_setitimerfd},
#endif #endif
{"gettimeofday", nixio_gettimeofday}, {"gettimeofday", nixio_gettimeofday},