Software /
code /
prosody
Comparison
util-src/pposix.c @ 13574:f29d15aef6f8
util.pposix: Add fdopen() to return a Lua file object from an fd
Now we can, for example, read/write pipes using Lua's standard I/O routines.
author | Matthew Wild <mwild1@gmail.com> |
---|---|
date | Wed, 20 Nov 2024 12:08:59 +0000 |
parent | 13563:5d4d7ed83f1a |
comparison
equal
deleted
inserted
replaced
13573:9277fc78fe39 | 13574:f29d15aef6f8 |
---|---|
692 lua_pushinteger(L, fds[0]); | 692 lua_pushinteger(L, fds[0]); |
693 lua_pushinteger(L, fds[1]); | 693 lua_pushinteger(L, fds[1]); |
694 return 2; | 694 return 2; |
695 } | 695 } |
696 | 696 |
697 /* This helper function is adapted from Lua 5.3's liolib.c */ | |
698 static int stdio_fclose (lua_State *L) { | |
699 int res = -1; | |
700 luaL_Stream *p = ((luaL_Stream *)luaL_checkudata(L, 1, LUA_FILEHANDLE)); | |
701 if (p->f == NULL) { | |
702 return 0; | |
703 } | |
704 res = fclose(p->f); | |
705 p->f = NULL; | |
706 return luaL_fileresult(L, (res == 0), NULL); | |
707 } | |
708 | |
709 static int lc_fdopen(lua_State *L) { | |
710 int fd = luaL_checkinteger(L, 1); | |
711 const char *mode = luaL_checkstring(L, 2); | |
712 | |
713 luaL_Stream *file = (luaL_Stream *)lua_newuserdata(L, sizeof(luaL_Stream)); | |
714 file->closef = stdio_fclose; | |
715 file->f = fdopen(fd, mode); | |
716 | |
717 if (!file->f) { | |
718 luaL_pushfail(L); | |
719 lua_pushstring(L, strerror(errno)); | |
720 return 2; | |
721 } | |
722 | |
723 luaL_getmetatable(L, LUA_FILEHANDLE); | |
724 lua_setmetatable(L, -2); | |
725 return 1; | |
726 } | |
727 | |
697 static int lc_uname(lua_State *L) { | 728 static int lc_uname(lua_State *L) { |
698 struct utsname uname_info; | 729 struct utsname uname_info; |
699 | 730 |
700 if(uname(&uname_info) != 0) { | 731 if(uname(&uname_info) != 0) { |
701 luaL_pushfail(L); | 732 luaL_pushfail(L); |
909 { "umask", lc_umask }, | 940 { "umask", lc_umask }, |
910 | 941 |
911 { "mkdir", lc_mkdir }, | 942 { "mkdir", lc_mkdir }, |
912 | 943 |
913 { "pipe", lc_pipe }, | 944 { "pipe", lc_pipe }, |
945 { "fdopen", lc_fdopen }, | |
914 | 946 |
915 { "setrlimit", lc_setrlimit }, | 947 { "setrlimit", lc_setrlimit }, |
916 { "getrlimit", lc_getrlimit }, | 948 { "getrlimit", lc_getrlimit }, |
917 | 949 |
918 { "uname", lc_uname }, | 950 { "uname", lc_uname }, |