Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / C++
Article

Creating a process, and then killing it

Rate me:
Please Sign up or sign in to vote.
4.35/5 (17 votes)
22 Nov 19992 min read 252.6K   98   25
Creating a process, and then killing it.

Introduction

While I was creating an app that has the capability of starting a process, and then be able to kill it later on, I looked all over the net, and found some crazy ways of doing this. Searching, searching, searching, for a couple days, I did nothing but try to locate info on setting this up correctly (Since I never tried doing this before). Most of them I could not get to work, in their entirety, as they were written. I finally found a way that worked, without too much mish-mash. What is here, is a conglomerate of all. And needless to say, the simplest way was the key. I am sure there are better ways of doing this, but this way works for this application.

Please note that some of the techniques used in this article are based on the article Sending a message to the Main Frame Window of Another Application, given only the Process Handle by Martin-Pierre Frenette.

The basic method used is to start a process, store its process ID, and then when it comes time to kill the process, you enumerate all open windows and close the window that is associated with your process ID.

TerminateProcess() is easier, but doesn't unload the DLLs from memory, which means it doesn't let the DLLs know the process is terminated, and leaves them floating around in memory, lost, causing problems. It should only be used in worst-case situations. system(), WinExec(), ShellExecute(), and ShellExecueEx() are easier, but you don't get as much information about the process being started. Since CreateProcess() is very powerful, and seems rather intimidating at first, I decided to write this little article.

PostMessage() needs a window handle to send WM_CLOSE, so we have to use EnumWindows() to ramble through the windows, checking to see if our PID is the same. If it is, we have a match, and have the window handle to send it.

In CSomeDlg.h

static BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
DWORD processPid;

In CSomeDlg.cpp

void CSomeDlg::startProcess()
{
  BOOL bWorked;
  STARTUPINFO suInfo;
  PROCESS_INFORMATION procInfo;
  CString m_Process = "C:\\wherever\\process\\we\\want\\to\\start.exe";
  char *vip =  "C:\\wherever\\process\\we\\want\\to\\start.exe " 
                    "whatever command line arguments here";

  memset (&suInfo, 0, sizeof(suInfo));
  suInfo.cb = sizeof(suInfo);

  bWorked = ::CreateProcess(m_Process,
             vip,      // can also be NULL
             NULL,
             NULL,
             FALSE,
             NORMAL_PRIORITY_CLASS,
             NULL,
             NULL,
             &suInfo,
             &procInfo);

/*
procInfo has these members
    HANDLE hProcess;   // process handle
    HANDLE hThread;    // primary thread handle
    DWORD dwProcessId; // process PID
    DWORD dwThreadId;  // thread ID
*/

  if (procInfo.dwThreadId = NULL)
  {
     MessageBox("nope");
  }

  playerPid = procInfo.dwProcessId;
}



void CSomeDlg::killProcess()
{
  HANDLE ps = OpenProcess( SYNCHRONIZE|PROCESS_TERMINATE, 
                                        FALSE, processPid);
  // processPid = procInfo.dwProcessId;

  // This function enumerates all widows,
  // using the EnumWindowsProc callback
  // function, passing the PID of the process
  // you started earlier.
  EnumWindows(EnumWindowsProc, processPid);

  CloseHandle(ps) ;
}

BOOL CALLBACK CSomeDlg::EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
  DWORD wndPid;
  CString Title;
  // lParam = procInfo.dwProcessId;

  // This gets the windows handle and pid of enumerated window.
  GetWindowThreadProcessId(hwnd, &wndPid);

  // This gets the windows title text
  // from the window, using the window handle
  CWnd::FromHandle( hwnd )->GetWindowText(Title);

  //  this makes sure that the PID matches that PID we started, and window
  // text exists, before we kill it . I don't think this is really needed, 
  // I included it because some apps have more than one window.
  if ( wndPid == (DWORD)lParam && Title.GetLength() != 0)
  {
    //  Please kindly close this process
    ::PostMessage(hwnd, WM_CLOSE, 0, 0);
    return false;
  }
  else
  {
    // Keep enumerating
    return true;
  }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
ljp
Software Developer Nokia Pty Ltd
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalprocess creation Pin
hrishiS22-Dec-08 23:29
hrishiS22-Dec-08 23:29 
Generalprocess Pin
prathuraj9-Apr-07 0:04
prathuraj9-Apr-07 0:04 
GeneralProcess in a Thread Pin
Gagan komal16-Nov-06 21:20
Gagan komal16-Nov-06 21:20 
GeneralGreat help Pin
ellasunxl13-Jun-06 16:20
ellasunxl13-Jun-06 16:20 
GeneralRe: Great help Pin
tifen27-Jul-09 17:22
tifen27-Jul-09 17:22 
GeneralProblem in retreving the HANDLE of the window Pin
Raj241128-Mar-06 23:12
Raj241128-Mar-06 23:12 
QuestionApplication? Pin
Rodolfo Huper29-Mar-05 6:09
Rodolfo Huper29-Mar-05 6:09 
GeneralLinking error Pin
NTSC12-Nov-03 13:20
NTSC12-Nov-03 13:20 
GeneralRe: Linking error Pin
Agus Subhan Akbar26-May-05 20:40
Agus Subhan Akbar26-May-05 20:40 
GeneralPassing instruction to the screen Pin
vgandhi13-Aug-03 13:42
vgandhi13-Aug-03 13:42 
Generala simple question I hope Pin
Gregor Schiller1-Feb-03 9:14
Gregor Schiller1-Feb-03 9:14 
GeneralRe: a simple question I hope Pin
ljp1-Feb-03 9:35
ljp1-Feb-03 9:35 
QuestionUsing this in Visual c++? Pin
microcyb26-Dec-02 6:27
microcyb26-Dec-02 6:27 
AnswerRe: Using this in Visual c++? Pin
Anonymous7-Aug-03 3:01
Anonymous7-Aug-03 3:01 
GeneralhProcess.. Pin
26-Apr-02 14:01
suss26-Apr-02 14:01 
GeneralRe: hProcess.. Pin
2-May-02 16:28
suss2-May-02 16:28 
QuestionNot working? Pin
Conphused19-Mar-02 12:11
Conphused19-Mar-02 12:11 
AnswerRe: Not working? Pin
Rob maddison27-Jan-03 2:51
sussRob maddison27-Jan-03 2:51 
GeneralplayerPid = procInfo.dwProcessId; Pin
23-Feb-02 19:17
suss23-Feb-02 19:17 
GeneralRe: playerPid = procInfo.dwProcessId; Pin
kidconan11-Aug-05 20:45
kidconan11-Aug-05 20:45 
Questionhow Can I start "service program"? Pin
28-Jun-01 17:04
suss28-Jun-01 17:04 
AnswerRe: how Can I start "service program"? Pin
2-May-02 16:30
suss2-May-02 16:30 
GeneralError Pin
15-May-01 3:34
suss15-May-01 3:34 
GeneralKilling a process Pin
H.K. Subbu7-Aug-00 21:11
sussH.K. Subbu7-Aug-00 21:11 
Article: Creating a process, and then killing it
URL: http://www.codeproject.com/cpp/kill_process.asp

Hi CodeProject,
Your article gave me valuable information.I have a problem.
I have to kill a process based on its ID or Application name or window name of the process. I have to kill depending upon the user input. User has 2 options.
1. Forcefully kill the process.
2. Normal killing.

Which API is preferred for forceful killing and which one is preferred for normal killing. The API should work taking process ID or application name or window name as the parameter. I thought of using TerminateProcess for forceful killing, but it does not perform a clean process shutdown.

It should work similar to KILL and KILL -9 in unix systems.
I have to develop the same for winnt, win2000 platforms.

Please send me ur valuable comments as soon as possible

bye
Regards,
Subbu

GeneralA much different direction. Pin
nerddude18-Oct-03 19:38
nerddude18-Oct-03 19:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.