[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: os.execute and the dreaded Windows console
- From: Chris <coderight@...>
- Date: Mon, 8 Sep 2008 19:17:10 -0400
On Mon, Sep 8, 2008 at 7:03 PM, Fabio Mascarenhas <mascarenhas@acm.org> wrote:
> This is not really the same as os.execute, because CreateProcess is
> asynchronous. You also need to release the process and thread handles
> that Windows creates for the new process. Check
Yes, I should have mentioned my code was more of a starting example
than a full featured extension library. Here is something with a
little more functionality (returns exit code and useful error
messages, etc):
#ifdef _WIN32
static void PushFormatWinError(lua_State* L, DWORD err)
{
TCHAR* msgbuf;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&msgbuf, 0, NULL);
/* FIXME: doesn't handle UNICODE */
lua_pushstring(L, msgbuf);
LocalFree(msgbuf);
}
static int CreateProcess_(lua_State* L)
{
size_t len;
const char* cmd0 = luaL_checklstring(L, 1, &len);
char* cmd = lua_newuserdata(L, len + 1);
STARTUPINFO start;
PROCESS_INFORMATION info;
DWORD exitcode;
strcpy(cmd, cmd0);
memset(&start, 0x00, sizeof(start));
start.cb = sizeof(start);
if (!CreateProcess(NULL, cmd, NULL, NULL, FALSE,
CREATE_NO_WINDOW, NULL, NULL, &start, &info))
{
PushFormatWinError(L, GetLastError());
lua_error(L);
}
WaitForSingleObject(info.hProcess, INFINITE);
GetExitCodeProcess(info.hProcess, &exitcode);
CloseHandle(info.hProcess);
CloseHandle(info.hThread);
lua_pushinteger(L, exitcode);
return 1;
}
#endif /* _WIN32 */
Technically I don't think you need to close the handles because as it
is those CloseHandle calls returns errors (I assume because the
process is dead).
> "...something like io.popen or whatever with some work" is a little
> bit of an understatement :-), see
> http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx on how to
> do it.
Well I specifically didn't say how much work so I don't see how that
can be an understatement. ;)
CR