?
Solved

How to close a process on a task manager

Posted on 2006-04-20
17
Medium Priority
?
2,479 Views
Last Modified: 2013-12-03
i want to make a simple dialog base program that have a single button, and that button will close a specific program or process that is running. to be specific i want to close the spooler.exe

a simple code will do.


thank you very much.
0
Comment
Question by:haroldxious
  • 7
  • 4
  • 3
  • +2
17 Comments
 
LVL 22

Expert Comment

by:mahesh1402
ID: 16495724
You may refer this with src code 'Advanced Task Manager in MFC'

http://www.codeproject.com/system/advancedtaskmanager.asp <== This article demonstrates how to create a Task Manager in MFC which lists all the processes running in the system along with their process details and version information and  allows you to kill selected task.

MAHESH
0
 
LVL 1

Author Comment

by:haroldxious
ID: 16495789
hello mahesh, ive tried to download the source of advanced task manager then ive tried to run it, but it cannot delete the spoolsv.exe.

im using win xp. try it.

open the control pannel then in management tool go to service then to Print Spooler then click the play button. the spoolsv.exe will be seen in the process window. then ive tried to end task using the advanced task manager but it doesent work. pls help.


thank you very much
0
 
LVL 31

Expert Comment

by:Zoppo
ID: 16496186
Hi haroldxious,

I guess you don't have enough rights to kill the service - can you kill the service with Window's TaskManager?

BTW, I think the better way to stop a service (except maybe when the service hangs) would be to terminate it the same way as if you would press the 'Stop' button in service-control-panel.

You can do this via the Service Control Manager - see MSDN about functions OpenSCManager, OpenService and ControlService.

Hope that helps,

ZOPPO
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 1

Author Comment

by:haroldxious
ID: 16496205
yes i can kill it in the task manager. so im thinkin why i cant kill it on the advanced task manager program. ill try the OpenSCManager. If you have a code snippet to do this it is very much appreciated.
0
 
LVL 22

Expert Comment

by:mahesh1402
ID: 16496270
You may also try by killing a process by name with help of following src :

http://www.codeproject.com/threads/killprocess.asp <==

MAHESH
0
 
LVL 31

Expert Comment

by:Zoppo
ID: 16496303
Hi,

I tested this code, works for me, but I'm not sure how's about user rights, I work as local administrator ...

-----------------------------------
#include <windows.h>
#include <iostream>

int main(int argc, char* argv[])
{
      SC_HANDLE hServiceManager = OpenSCManager( NULL, NULL, SC_MANAGER_CONNECT );

      if ( NULL == hServiceManager )
      {
            std::cout << "Error opening SC-Manager; error code: " << GetLastError() << std::endl;
            return -1;
      }

      SC_HANDLE hService = OpenService( hServiceManager, "Spooler", SERVICE_STOP | SERVICE_QUERY_STATUS );

      if ( NULL == hService )
      {
            std::cout << "Error opening Spooler-service; error code: " << GetLastError() << std::endl;
            return -1;
      }

      SERVICE_STATUS ss;

      if ( FALSE == QueryServiceStatus( hService, &ss ) )
      {
            std::cout << "Error querying Spooler-service status; error code: " << GetLastError() << std::endl;
            return -1;
      }

      if ( ss.dwCurrentState == SERVICE_STOPPED )
      {
            std::cout << "Error: Spooler-service not running!" << std::endl;
            return -1;
      }
      else if ( ss.dwCurrentState == SERVICE_STOP_PENDING )
      {
            std::cout << "Error: Spooler-service is stopping!" << std::endl;
            return -1;
      }

      if ( FALSE == ControlService( hService, SERVICE_CONTROL_STOP, &ss ) )
      {
            std::cout << "Error sending STOP-message to  Spooler-service; error code: " << GetLastError() << std::endl;
            return -1;
      }

      return 0;
}
---------------------------------------

hope that helps,

ZOPPO
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 16501972
And don't forget the simple way:  Execute this at the commandline:

    NET STOP SPOOLER

Make a batch file with those three words and put an icon link to it on your desktop and you are just a double-click away from stopping the spooler andy time you want.

-- Dan
0
 
LVL 8

Expert Comment

by:mxjijo
ID: 16540190

As Zoppo mentioned, you need privilage to kill.
Call the following function once at the entry of your application to become a licensed :) killer
I would recomment to use the remote thread method to kill other apps, rather than using TerminateProcess()
good luck

BOOL GrabKillerPrivilage()
{
    TOKEN_PRIVILEGES Priv, PrivOld;
    DWORD cbPriv = sizeof(PrivOld);
    HANDLE hToken;
     DWORD  dwError;

    // get current thread token
    if (!OpenThreadToken(GetCurrentThread(),
                         TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                         FALSE, &hToken))
    {
        if (GetLastError() != ERROR_NO_TOKEN)
            return FALSE;
        // revert to the process token, if not impersonating
        if (!OpenProcessToken(GetCurrentProcess(),
                              TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                              &hToken))
            return FALSE;
    }

    Priv.PrivilegeCount                    = 1;
    Priv.Privileges[0].Attributes     = SE_PRIVILEGE_ENABLED;
    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Priv.Privileges[0].Luid);

    // try to enable the privilege
    if (!AdjustTokenPrivileges(hToken,
                                        FALSE,
                                        &Priv,
                                        sizeof(Priv),
                                        &PrivOld,
                                        &cbPriv))
    {
        dwError = GetLastError();
        CloseHandle(hToken);
        return SetLastError(dwError), FALSE;
    }

    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
    {
        // the SE_DEBUG_NAME privilege is not in the caller's token
        CloseHandle(hToken);
        return SetLastError(ERROR_ACCESS_DENIED), FALSE;
    }

     return TRUE;
}
0
 
LVL 1

Author Comment

by:haroldxious
ID: 16542272
how will i end the explorer.exe and spoolsv.exe in the task manager.

i will be having a button in my application dialog that serves as an end task button. then when you press it it will automatically endtask the explorer.exe and spoolsv.exe.

please help.

thank you very much.
0
 
LVL 8

Expert Comment

by:mxjijo
ID: 16546357

Sorry abt the code alignment


#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include "psapi.h"


BOOL GrabKillerPrivilage()
{
    TOKEN_PRIVILEGES Priv, PrivOld;
    DWORD cbPriv = sizeof(PrivOld);
    HANDLE hToken;
     DWORD  dwError;

    // get current thread token
    if (!OpenThreadToken(GetCurrentThread(),
                         TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                         FALSE, &hToken))
    {
        if (GetLastError() != ERROR_NO_TOKEN)
            return FALSE;
        // revert to the process token, if not impersonating
        if (!OpenProcessToken(GetCurrentProcess(),
                              TOKEN_QUERY|TOKEN_ADJUST_PRIVILEGES,
                              &hToken))
            return FALSE;
    }

    Priv.PrivilegeCount                    = 1;
    Priv.Privileges[0].Attributes     = SE_PRIVILEGE_ENABLED;
    LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &Priv.Privileges[0].Luid);

    // try to enable the privilege
    if (!AdjustTokenPrivileges(hToken,
                                        FALSE,
                                        &Priv,
                                        sizeof(Priv),
                                        &PrivOld,
                                        &cbPriv))
    {
        dwError = GetLastError();
        CloseHandle(hToken);
        return SetLastError(dwError), FALSE;
    }

    if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
    {
        // the SE_DEBUG_NAME privilege is not in the caller's token
        CloseHandle(hToken);
        return SetLastError(ERROR_ACCESS_DENIED), FALSE;
    }

     return TRUE;
}

char* getProcessName(HANDLE hProcess)
{
    TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
    if (NULL != hProcess )
    {
        HMODULE hMod;
        DWORD cbNeeded;

        if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
             &cbNeeded) )
        {
            GetModuleBaseName( hProcess, hMod, szProcessName, MAX_PATH);
                  return strdup(szProcessName);            
        }
    }
      return NULL;
}

HANDLE openProcessToKill(char* procNameIn, DWORD* pidList, int pidCount){
      for (int i=0; i<pidCount; i++){
            HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD |
                                          PROCESS_QUERY_INFORMATION |
                                          PROCESS_VM_OPERATION |
                                          PROCESS_SET_QUOTA |
                                          PROCESS_TERMINATE |
                                          PROCESS_VM_WRITE |
                                          PROCESS_VM_READ,
                                          FALSE,
                                          pidList[i]);                                          
            
            if (hProcess){
                  char* thisProcName = getProcessName(hProcess);
                // FIXME free thisProcName after processing
                  if (thisProcName){
                        if (_stricmp(thisProcName, procNameIn) == 0){
                              _tprintf( TEXT("Targetting %s (PID=%d)\n"),  thisProcName, pidList[i]);
                              return hProcess;
                        }else{
                              CloseHandle(hProcess);
                        }
                  }
            }else{
                  _tprintf( TEXT("Cannot open PID %d\n"),  pidList[i]);
            }
      }
      return NULL;
}

void killProcess(HANDLE killableProcHandle){
      // TerminateProcess() works as well.
      DWORD id;
      CreateRemoteThread(killableProcHandle,
                                    NULL,
                                    0,
                                    (LPTHREAD_START_ROUTINE)ExitProcess,
                                    0,
                                    0,
                                    &id);
}

void main(int argc, char* argv[])
{
    // Get the list of process identifiers.
      if (argv[1]){

            DWORD aProcesses[1024], cbNeeded;
            GrabKillerPrivilage();

            if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){
                        return;
            }
            HANDLE hProcessToKill = openProcessToKill(argv[1], aProcesses, cbNeeded/sizeof(DWORD));
            if (hProcessToKill){
                  killProcess(hProcessToKill);
                  _tprintf( TEXT("\nTarget down!!\n\n"));
            }
      }else{
            _tprintf( TEXT("Usage: kill {processname}\n"));
      }
}
0
 
LVL 1

Author Comment

by:haroldxious
ID: 16549363
hi mxjijo, ur code is for win32 console application, im doing a dialog base application. i want that if you click a button it will kill the process, how will i parse your code to that.


many thanx
0
 
LVL 8

Expert Comment

by:mxjijo
ID: 16549486

Make a callable function out of main()

something like...

void
killProcessByName(char* procName) {
    DWORD aProcesses[1024], cbNeeded;
    GrabKillerPrivilage();

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){
        return;
    }
    HANDLE hProcessToKill = openProcessToKill(procName, aProcesses, cbNeeded/sizeof(DWORD));
    if (hProcessToKill){
        killProcess(hProcessToKill);
     }
}

Call the above function from you OnXxxClick();

that wud do.

Ps: please handle errors - i'm a lazy programmer

good luck.
0
 
LVL 1

Author Comment

by:haroldxious
ID: 16549676
thanx mxjijo but i cant compile the code, the errors are:
 EnumProcessModules, GetModuleBaseName and EnumProcesses are undeclared identifiers.

can i use this in mfc dialog base app? i know that this are SDK platforms.

and by the way i didnt put #include "psapi.h" coz unidentified.

0
 
LVL 22

Expert Comment

by:mahesh1402
ID: 16550600
>>ive tried to download the source of advanced task manager then ive tried to run it, but it cannot delete the spoolsv.exe.

To kill Service Process like spoolsv.exe in WMI there is StopService Method of the Win32_Service Class.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/stopservice_method_in_class_win32_service.asp

MAHESH
0
 
LVL 1

Author Comment

by:haroldxious
ID: 16551504
thanx mahesh, but how about killing the explorer.exe?
ive used the code of mxjijo but some errors occured...
0
 
LVL 8

Accepted Solution

by:
mxjijo earned 400 total points
ID: 16555167
>> EnumProcessModules, GetModuleBaseName and EnumProcesses are undeclared identifiers.
>> and by the way i didnt put #include "psapi.h" coz unidentified.

   If you have platform SDK you can use #include <psapi.h> and add [platform SDK]/include to the lookup path.
If you don't have platform SDK, you have to define function pointers to those functions as follows

// PSAPI definitions
typedef BOOL  (WINAPI *pfn_EnumProcesses)(DWORD*, DWORD, DWORD*);
typedef BOOL  (WINAPI *pfn_EnumProcessModules) (HANDLE, HMODULE*, DWORD, LPDWORD);
typedef DWORD (WINAPI *pfn_GetModuleFileNameEx) (HANDLE, HMODULE, LPTSTR, DWORD);

// now define function pointers
pfn_EnumProcesses            EnumProcesses;
pfn_EnumProcessModules      EnumProcessModules;
pfn_GetModuleFileNameEx      GetModuleFileNameEx;      

// then load those functions from psapi dll as follows

HMODULE m_hPsApidll = LoadLibrary("PsAPI.DLL");

if (m_hPsApidll)
{
  EnumProcesses = (pfn_EnumProcesses)GetProcAddress(m_hPsApidll, "EnumProcesses");
  EnumProcessModules = (pfn_EnumProcessModules)GetProcAddress(m_hPsApidll, "EnumProcessModules");
  GetModuleFileNameEx = (pfn_GetModuleFileNameEx)GetProcAddress(m_hPsApidll, "GetModuleFileNameExA");
}



FYI:
We have given you every single details of the implementation.
Poeple usually don't help you out this deep.
I have seen you posting the same question again - don't know why
Please note that there is no one line code to do what want to do :)

bye...
0
 
LVL 1

Author Comment

by:haroldxious
ID: 16559533
hello, im sorry guys if im such a noob. its my first time to use mfc.
im very very sorry
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Here is how to use MFC's automatic Radio Button handling in your dialog boxes and forms.  Beginner programmers usually start with a OnClick handler for each radio button and that's just not the right way to go.  MFC has a very cool system for handli…
Introduction: Dynamic window placements and drawing on a form, simple usage of windows registry as a storage place for information. Continuing from the first article about sudoku.  There we have designed the application and put a lot of user int…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Suggested Courses

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question