无法从服务中关闭用户会话中的进程

时间:2017-08-07 17:28:20

标签: windows service process signals

该体系结构是一种服务,可以在具有系统特权的用户会话中的进程组内启动进程,代码片段为。

当服务需要自行停止时,我想向子进程发送一个信号,让它有机会优雅地关闭,代码片段2。

问题是它似乎根本没有任何明显的错误代码发送信号。我已经测试了从命令提示符运行的子进程,ctrl + break工作正常。

代码段1

PROCESS_INFORMATION processInfo;
ZeroMemory(&processInfo, sizeof(PROCESS_INFORMATION));

STARTUPINFO si;
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.lpDesktop = "winsta0\\Default";
si.dwFlags |= STARTF_USESTDHANDLES;

LPVOID environment;
BOOL createRet = CreateEnvironmentBlock(&environment, userToken, FALSE);
if (!createRet) {
    throw std::runtime_error("Failed to create environment block");
}

DWORD creationFlags =
    NORMAL_PRIORITY_CLASS |
    CREATE_NO_WINDOW |
    CREATE_UNICODE_ENVIRONMENT |
    CREATE_NEW_PROCESS_GROUP; // this create a process in a group

// launch a process in the user session
// the toke is a system privilege toke within the user session
createRet = CreateProcessAsUser(
    userToken, NULL, LPSTR(command.c_str()),
    sa, NULL, TRUE, creationFlags,
    environment, NULL, &si, &processInfo);

if (!createRet) {
    throw std::runtime_error("Failed to create the service in user session");
}

m_serviceGroupId = processInfo.dwProcessId;

DestroyEnvironmentBlock(environment);
CloseHandle(userToken);

代码段2

if (m_serviceGroupId == 0) {
    return;
}

HANDLE process;
const UINT kExitCode = 0;
const UINT kShutdownTimeout = 3000;
if (findProcessInSession(kServiceProcess, &process, getActiveSession())) {
    BOOL r = GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, m_serviceGroupId);
    // this won't success if I don't specifically call AllocConsole() in the constructor
    if (!r) {
        writeEventErrorLog(GetLastErrorAsString().c_str());
    }

    DWORD exitCode = WaitForSingleObject(process, kShutdownTimeout);
    if (exitCode != WAIT_OBJECT_0) {
        // always fall into forceful shutdown
        writeEventErrorLog("Forcefully shutdown synergy service");
        // GetLastErrorAsString returns empty string
        writeEventErrorLog(GetLastErrorAsString().c_str());
        if (!TerminateProcess(process, kExitCode)) {
            writeEventErrorLog("Failed to shutdown synergy service");
        }
    }
}

m_serviceGroupId = 0;

1 个答案:

答案 0 :(得分:1)

您的方法不起作用,因为服务进程和子进程不在同一会话中,因此请考虑使用Windows事件。请查看CreateEventSetEvent

当您的服务流程启动时,请调用CreateEvent(),例如:

HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\myevent");

当您的子进程启动时,调用CreateEvent(),并启动一个线程来捕获信号:

//The lpName should be identical with that in service process
HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\myevent");

std::thread mythread([hEvent] {
    WaitForSingleObject(hEvent, INFINITE);
    //then exit your child process gracefully
});

每当您打算停止子进程时,只需在服务进程中调用SetEvent():

SetEvent(hEvent);

将bManualReset设置为TRUE,然后您的服务可以同时向不同的子进程发送信号。