lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Apr 16, 2007, at 11:13 AM, Jesús Ruiz de Infante wrote:

Hi all,

I have a problem trying to write a Lua wrapper for the C syslog API. The problem is that ident in openlog(const char *ident, ...), a  string that is prepended to every logged message, should be accessible by later calls to syslog().

Basically I need to keep a pointer to the ident string that should outlive the invocation of openlog(). Making ident static is not the way to go since we need an ident instance for every process linking against the library.

Every process should get a copy of your global variables, not share them with other processes. Global variables are shared between (Posix) threads that are part of the same process, not between processes (the library loader usually uses copy-on-write pages to implement this). I would still prefer a reentrant solution though, so storing it in the module environment is the right thing to do.

Your solution is a little complicated, you could just store the ident string passed as an argument itself, not a userdata object, why keep two copies of the same thing around when Lua string are immutable? When you need it you just use lua_tolstring to get the same string pointer again (and again). So your code simplified to:


static int l_openlog(lua_State *L)
{
...
/* handle ident option */
size_t len;
const char *ident = luaL_checklstring(L, 1, &len);
   lua_pushvalue(L, 1);
/* store it in our environment table */
lua_setfield(L, LUA_ENVIRONINDEX, "ident");
openlog(ident, option, facility);
return 0;
}

If you're worried about efficiency you could store the string at integer index 1, but you'll bog down the syslog daemon long before that :-/ (syslogd tends to do an 'fsync' call after every write)


--
Gé Weijers