redirect output to file from createprocessasuser

482 views Asked by At

I made a windows service which download a file from an address that I give and then execute with createprocessasuser function, all worked good till I tried to redirect the output to a file

I see the new window of the program thats running with nothing in it but nothing in the log file also..

here is my code:

void exeAfterDownload(wchar_t *file){

SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = NULL;
sa.bInheritHandle = TRUE;

HANDLE h = CreateFile(_T("c:\\temp\\out.log"),
    FILE_APPEND_DATA,
    FILE_SHARE_WRITE | FILE_SHARE_READ,
    &sa,
    OPEN_ALWAYS,
    FILE_ATTRIBUTE_NORMAL,
    NULL);

BOOL ret = FALSE;
DWORD flags = CREATE_NO_WINDOW;

ZeroMemory(&pi2, sizeof(PROCESS_INFORMATION));
ZeroMemory(&si2, sizeof(STARTUPINFO));
si2.cb = sizeof(STARTUPINFO);
si2.dwFlags |= STARTF_USESTDHANDLES;
si2.hStdInput = NULL;
si2.hStdError = h;
si2.hStdOutput = h;

sessionId2 = WTSGetActiveConsoleSessionId();

if (WTSQueryUserToken(sessionId2, &dummy2)) {
    if (!DuplicateTokenEx(dummy2, TOKEN_ALL_ACCESS, NULL, SecurityIdentification, TokenPrimary, &token2)) {
        CloseHandle(dummy2);
    }
    CloseHandle(dummy2);

    if (!CreateProcessAsUser(token2, L"c:\\temp\\run.exe", NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si2, &pi2)) {  // The "new console" is necessary. Otherwise the process can hang our main process

        CloseHandle(token2);
    }
    CloseHandle(token2);
}
else{

}

}

when I run it without the redirect, it works fine, and when I run this code on different program and use createprocess it also works fine with the redirect, but when I use the createprocessasuser (because it runs from win services ) nothing is in the log file . any ideas?

1

There are 1 answers

0
user3696488 On

You should set CreateProcessAsUser's from FALSE to TRUE. It's inheritHandles flag.