[Webinar] Streamline your web hosting managementRegister Today

x
?
Solved

How to start and then kill a process

Posted on 2000-01-17
10
Medium Priority
?
265 Views
Last Modified: 2010-04-06
How do I start a command line (DOS) process and then kill it from Delphi? My platform is NT.

Regards,
Morten
0
Comment
Question by:mdrasted
  • 5
  • 3
  • 2
10 Comments
 
LVL 2

Expert Comment

by:PeterLarsen
ID: 2359402
Use ShellExecute to activate the program and FindWindow to close it again.
You may search for it here.

0
 
LVL 10

Expert Comment

by:Lischke
ID: 2359406
You can call CreateProcess with cmd.exe as executable and keep the returned process handle (in TProcessInformation). Whenever you think it is time to close the process then you can try sending a WM_QUIT message to the process or (if it doesn't react) call KillProcess.

Ciao, Mike
0
 
LVL 1

Author Comment

by:mdrasted
ID: 2359476
Can you please give me an example on how to use CreateProcess?

Regards;
Morten
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 2

Expert Comment

by:PeterLarsen
ID: 2359496
Mike.
I dont think it is a good idea to remember the handle and use it to close the window again, because it may no longer exist.
-just a comment.
0
 
LVL 10

Accepted Solution

by:
Lischke earned 400 total points
ID: 2359507
A typical use is like:

WasOK := CreateProcess(nil, PChar(CommandLine), nil, nil, True, 0, nil, PChar(WorkDir), SI, PI);

I use this all the time and it works very well. Instead of posting all my (quite complex) code I give you another snippet created by Madshi:

unit runThread_;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
  ExtCtrls, ComCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private-Deklarationen}
  public
    { Public-Deklarationen}
  end;

var Form1 : TForm1 = nil;

implementation

{$R *.DFM}

const unitName = 'runThread_.';

type TRunThread = class(TThread)
  private
    processHandle : cardinal;
    processReady  : boolean;
    waitingThread : cardinal;
    procedure Execute; override;
  end;

procedure TRunThread.Execute;
begin
  WaitForSingleObject(processHandle,INFINITE);   // This call does not return, unless copy is stopped
  processReady:=true;                            // Set "processReady" flag for main thread
  PostThreadMessage(waitingThread,WM_NULL,0,0);  // Wake up main thread
                                                 // If you call Application.HandleMessage (see below) in the
                                                 // main thread, the main thread is sleeping the most time in
                                                 // winAPI "waitMessage". So we send a "dummy" message in order
                                                 // to let the main thread return from Application.HandleMessage
end;

procedure TForm1.Button1Click(Sender: TObject);
var si  : TStartupInfo;
    pi  : TProcessInformation;
    dw1 : dword;
begin
  enabled:=false;
  caption:='start copy...';
  ZeroMemory(@si,sizeOf(si)); si.cb:=sizeOf(si);
  si.dwFlags:=STARTF_USESHOWWINDOW; si.wShowWindow:=SW_HIDE;
  if CreateProcess(nil,'c:\command.com /c copy c:\autoexec.bat c:\test.bat >c:\output.txt',nil,nil,false,0,nil,nil,si,pi) then begin
    caption:='copy started...';
    with TRunThread.Create(true) do         // create the thread object, but do not start it now...
      try
        processHandle:=pi.hProcess;         // tell the thread what process it has to watch
        processReady:=false;                // flag for the loop (see below)
        waitingThread:=GetCurrentThreadID;  // the current threadID for the wakeup message (see above)
        caption:='wait for copy...';
        Resume;                             // now all information is prepared; so let's start the thread
        repeat
          Application.HandleMessage;        // message loop
        until Application.Terminated or processReady;  // continue with normal program when either the
                                                       // started process has stopped or our program is closed
        caption:='copy stopped...';
      finally Free end;
    GetExitCodeProcess(pi.hProcess,dw1);
    CloseHandle(pi.hThread); CloseHandle(pi.hProcess); // Never forget to close handles...
    caption:='ready... (exitCode='+IntToStr(dw1)+')';
  end else caption:='could not start copy...';
  enabled:=true;
end;

end.

Ciao, Mike
0
 
LVL 10

Expert Comment

by:Lischke
ID: 2359517
Peter, you don't need a window to post a message. All you need is a message queue which is automatically created when a thread calls GetMessage or PeekMessage the very first time. For these calls no window is needed but the command line program has indeed one so you can be sure that a message queue has been created.

Ciao, Mike
0
 
LVL 1

Author Comment

by:mdrasted
ID: 2359541
Thanks for your excellent help Mike!!

Regards,
Morten
0
 
LVL 10

Expert Comment

by:Lischke
ID: 2359596
I'm pleased to help you and thank you for the A grading :-)

Ciao, Mike
0
 
LVL 2

Expert Comment

by:PeterLarsen
ID: 2359604
Ok Mike, i understand this but it was not my point.
If you have a handle to a process and this process dont exist anymore or the handle has been recreated to another process - is it not possible that this may be a problem ??

I'm not asking just for keeping the discussion going, but because i dont know!

Regards
Peter
0
 
LVL 10

Expert Comment

by:Lischke
ID: 2359643
No problem. If the process is already gone without that the application got notified of this fact (which one can prevent with the WaitFor* calls) then the APIs will just return False on return (PostThreadMessage and the like). The process ID as such is not used again, AFAIK, until the computer is rebooted.

Ciao, Mike
0

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Question has a verified solution.

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

Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
This is an update to some code that someone else posted on Experts Exchange. It is an alternate approach, I think a little easier to use, & makes sure that things like the Task Bar will update.
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Enter Foreign and Special Characters Enter characters you can't find on a keyboard using its ASCII code ... and learn how to make a handy reference for yourself using Excel ~ Use these codes in any Windows application! ... whether it is a Micr…
Suggested Courses
Course of the Month10 days, 2 hours left to enroll

591 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