Click here to Skip to main content
Licence 
First Posted 22 Nov 1999
Views 192,264
Bookmarked 96 times

Creating a process, and then killing it

By | 22 Nov 1999 | Article
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

About the Author

ljp

Software Developer
Nokia Pty Ltd
Australia Australia

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalprocess creation PinmemberMember 425070523:29 22 Dec '08  
Generalprocess Pinmemberprathuraj0:04 9 Apr '07  
GeneralProcess in a Thread PinmemberGagan komal21:20 16 Nov '06  
GeneralGreat help Pinmemberellasunxl16:20 13 Jun '06  
GeneralRe: Great help Pinmembertifen17:22 27 Jul '09  
GeneralProblem in retreving the HANDLE of the window PinmemberRaj241123:12 28 Mar '06  
QuestionApplication? PinmemberRodolfo Brazil6:09 29 Mar '05  
GeneralLinking error PinmemberNTSC13:20 12 Nov '03  
GeneralRe: Linking error PinmemberAgus Subhan Akbar20:40 26 May '05  
GeneralPassing instruction to the screen Pinmembervgandhi13:42 13 Aug '03  
Generala simple question I hope PinmemberGregor Schiller9:14 1 Feb '03  
GeneralRe: a simple question I hope Pinmemberljp9:35 1 Feb '03  
QuestionUsing this in Visual c++? Pinmembermicrocyb6:27 26 Dec '02  
AnswerRe: Using this in Visual c++? PinsussAnonymous3:01 7 Aug '03  
GeneralhProcess.. PinmemberPreetham14:01 26 Apr '02  
GeneralRe: hProcess.. PinmemberAnonymous16:28 2 May '02  
QuestionNot working? PinmemberConphused112:11 9 Mar '02  
AnswerRe: Not working? PinsussRob maddison2:51 27 Jan '03  
GeneralplayerPid = procInfo.dwProcessId; Pinmembervirle19:17 23 Feb '02  
GeneralRe: playerPid = procInfo.dwProcessId; Pinmemberkidconan20:45 11 Aug '05  
Questionhow Can I start "service program"? PinmemberAhnse17:04 28 Jun '01  
AnswerRe: how Can I start "service program"? Pinmembercjc16:30 2 May '02  
GeneralError PinmemberGunter Blasek3:34 15 May '01  
GeneralKilling a process PinsussH.K. Subbu21:11 7 Aug '00  
GeneralA much different direction. Pinmembernerddude19:38 18 Oct '03  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 23 Nov 1999
Article Copyright 1999 by ljp
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid