How to kill a service process?

user626528

I'm trying to kill a service process, if it stucks when trying to stop it via ServiceController. I have a Process object of this service; however, nothing happens when I call the Kill() method on it. No exceptions, and the process is still running.
So, how can I kill this process?

Harry Johnston

There's nothing unusual about service processes from the kernel's point of view, but the permissions on them do not explicitly give PROCESS_TERMINATE access to the Administrators group. To bypass this, you need to enable debug privilege.

For reference, here's the code I used to confirm that nothing unexpected was happening:

#include <Windows.h>

#include <stdio.h>

int main(int argc, char ** argv)
{
    HANDLE h, hToken;
    DWORD pid = atoi(argv[1]);

    printf("Process %u\n", pid);

    if (OpenProcessToken(GetCurrentProcess(), 
                TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) 
    {
        struct {

            DWORD PrivilegeCount;
            LUID_AND_ATTRIBUTES Privileges[1];

        } tkp;

        LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid); 

        tkp.PrivilegeCount = 1;
        tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; 

        AdjustTokenPrivileges(hToken, FALSE, (PTOKEN_PRIVILEGES)&tkp, 0, 
                (PTOKEN_PRIVILEGES)NULL, 0);

        CloseHandle(hToken);

    }

    h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
    if (h == NULL)
    {
        printf("OpenProcess: %u\n", GetLastError());
        return 1;
    }

    if (!TerminateProcess(h, 1))
    {
        printf("TerminateProcess: %u\n", GetLastError());
        return 1;
    }

    printf("Done!\n");
    return 0;
}

I'm not sure how much of that can be done natively in C#, but you can P/Invoke the relevant calls if necessary.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related