1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
|
/*
* rhnop
*
* Copyright (C) 2011 Christian Pointner <equinox@helsinki.at>
*
* This file is part of rhnop.
*
* rhnop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* rhnop is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with rhnop. If not, see <http://www.gnu.org/licenses/>.
*/
#include <lua.h>
#include <lauxlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include "l_pipe.h"
static int pipefds_[2];
int pipe_init()
{
return pipe(pipefds_);
}
void pipe_close()
{
close(pipefds_[0]);
close(pipefds_[1]);
}
static int l_pipe_signal(lua_State *L)
{
char data = 1;
int ret = 0;
for(;;) {
ret = write(pipefds_[1], &data, 1);
if(ret == 1) break;
if(!ret) continue;
if(ret == -1 && (errno == EAGAIN || errno == EINTR)) continue;
break;
}
lua_pushinteger(L, ret);
return 1;
}
static int l_pipe_getfd(lua_State *L)
{
if(!lua_istable(L, -1))
luaL_error(L, "can't retreive pipe fd");
lua_pushliteral(L, "fd");
lua_gettable(L, -2);
return 1;
}
static int l_pipe_dirty(lua_State *L)
{
lua_pushboolean(L, 0);
return 1;
}
static int l_pipe_getreadfd(lua_State *L)
{
lua_newtable(L);
lua_pushliteral(L, "fd");
lua_pushinteger(L, pipefds_[0]);
lua_settable(L, -3);
lua_pushliteral(L, "getfd");
lua_pushcfunction(L, l_pipe_getfd);
lua_settable(L, -3);
lua_pushliteral(L, "dirty");
lua_pushcfunction(L, l_pipe_dirty);
lua_settable(L, -3);
return 1;
}
static int l_pipe_consume(lua_State *L)
{
char data;
int ret = 0;
for(;;) {
ret = read(pipefds_[0], &data, 1);
if(ret == 1 || ret == 0) break;
if(ret == -1 && (errno == EAGAIN || errno == EINTR)) continue;
break;
}
lua_pushinteger(L, ret);
return 1;
}
static const struct luaL_reg pipe_funcs [] = {
{ "signal", l_pipe_signal },
{ "getreadfd", l_pipe_getreadfd },
{ "consume", l_pipe_consume },
{ NULL, NULL }
};
LUALIB_API int luaopen_pipe(lua_State *L)
{
luaL_register(L, LUA_PIPELIBNAME, pipe_funcs);
return 1;
}
|